fern-api 0.64.35 → 0.64.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +7 -5
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1712,7 +1712,7 @@ ${lAp.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&BQs(th
|
|
|
1712
1712
|
`+SHi.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?SHi.default.cyan(gAp(t,this.opt.mask)):SHi.default.italic(SHi.default.dim("[hidden]")):this.opt.mask?gAp(t,this.opt.mask):SHi.default.italic(SHi.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 AFo=ui(z2(),1),Hqp=ui(SJs(),1),$qp=ui(zEe(),1);var RDa=class extends x2{_run(t){this.done=t,this.editorResult=new $qp.Subject;let r=wW(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"?AFo.default.dim("Received"):AFo.default.dim("Press <enter> to launch your preferred editor."),t&&(r=AFo.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,Hqp.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 Yqp=require("stream");var Jqp=ui(require("readline"),1),Kqp=ui(Qqp(),1),BHi=class{constructor(t){this.rl||=Jqp.default.createInterface(ApD(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 ApD(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 Kqp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var NDa=class extends BHi{constructor(t={}){super(t),this.log=new Yqp.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return gDa(this.rl,this.bottomBar.split(`
|
|
1713
1713
|
`).length),this}updateBottomBar(t){return gDa(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+`
|
|
1714
1714
|
`}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&&iFo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var LE=ui(zEe(),1),kqp=ui(USa(),1);var qFo=ui(zEe(),1),Xqp=ui(USa(),1),TFo=function(e,t,r){return typeof e[t]!="function"?(0,qFo.of)(e):(0,qFo.from)((0,Xqp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var Zqp={set:(e,t="",r)=>{let i=e;t.split(".").forEach((n,a,u)=>{n==="__proto__"||n==="constructor"||(a===u.length-1?i[n]=r:(!(n in i)||typeof i[n]!="object")&&(i[n]={}),i=i[n])})},get:(e,t="",r)=>{let i=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((u,l)=>u!=null?u[l]:u,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},kNn=class extends BHi{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,LE.from)(t):(0,LE.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,LE.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,LE.from)([t]),this.process=i.pipe((0,LE.concatMap)(this.processQuestion.bind(this)),(0,LE.publish)()),this.process.connect(),this.process.pipe((0,LE.reduce)((n,a)=>(Zqp.set(n,a.name,a.answer),n),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,LE.defer)(()=>(0,LE.of)(t).pipe((0,LE.concatMap)(this.setDefaultType.bind(this)),(0,LE.concatMap)(this.filterIfRunnable.bind(this)),(0,LE.concatMap)(()=>TFo(t,"message",this.answers)),(0,LE.concatMap)(()=>TFo(t,"default",this.answers)),(0,LE.concatMap)(()=>TFo(t,"choices",this.answers)),(0,LE.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,LE.defer)(()=>(0,LE.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,LE.defer)(()=>(0,LE.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&Zqp.get(this.answers,t.name)!==void 0)return LE.EMPTY;if(t.when===!1)return LE.EMPTY;if(typeof t.when!="function")return(0,LE.of)(t);let{answers:r}=this;return(0,LE.defer)(()=>(0,LE.from)((0,kqp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,LE.filter)(i=>i!=null)))}};function eTp(e){let t=function(r,i){let n;try{n=new kNn(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",mDa),this.registerPrompt("input",wHi),this.registerPrompt("number",PDa),this.registerPrompt("confirm",jDa),this.registerPrompt("rawlist",wDa),this.registerPrompt("expand",SDa),this.registerPrompt("checkbox",DDa),this.registerPrompt("password",EDa),this.registerPrompt("editor",RDa)},t.restoreDefaultPrompts(),t}var EJs=eTp();function TpD(e,t){EJs.registerPrompt(e,t)}function CpD(){EJs.restoreDefaultPrompts()}var BpD={prompt:EJs,ui:{BottomBar:NDa,Prompt:kNn},createPromptModule:eTp,registerPrompt:TpD,restoreDefaultPrompts:CpD,Separator:iae},CFo=BpD;var fFn=require("path"),ICp=require("fs"),zCp=require("readline"),aCp="posthog-node";function _yD(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 l=a.tags[e3o.POSTHOG_ID_TAG];if(l===void 0)return a;let d=e.options.host??"https://us.i.posthog.com",s=new URL(`/project/${e.apiKey}/person/${l}`,d).toString();a.tags["PostHog Person URL"]=s;let o=a.exception?.values||[],c=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:c,$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:l,properties:b}),a}}var e3o=class{constructor(t,r,i,n){this.name=aCp,this.name=aCp,this.setupOnce=function(a,u){let l=u()?.getClient()?.getDsn()?.projectId;a(_yD(t,{organization:r,projectId:l,prefix:i,severityAllowList:n}))}}};e3o.POSTHOG_ID_TAG="posthog_distinct_id";var KFo="0123456789abcdef",t3o=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+=KFo.charAt(this.bytes[r]>>>4),t+=KFo.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+=KFo.charAt(this.bytes[r]>>>4),t+=KFo.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}},yKs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??hyD()}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 t3o.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,t3o.ofInner(t)}},hyD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),oCp,vKs=()=>yyD().toString(),yyD=()=>(oCp||(oCp=new yKs)).generate();function vyD(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 byD(e,t){global.process.on("uncaughtException",vyD(e,t))}function gyD(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var YFo,uCp,XFo;function OyD(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return XFo&&r.length===uCp||(uCp=r.length,XFo=r.reduce((i,n)=>{YFo||(YFo={});let a=YFo[n];if(a)i[a[0]]=a[1];else{let u=e(n);for(let l=u.length-1;l>=0;l--){let s=u[l]?.filename,o=t[n];if(s&&o){i[s]=o,YFo[n]=[s,o];break}}}return i},{})),XFo}function myD(e){return typeof Event<"u"&&xCp(e,Event)}function PyD(e){return RCp(e,"Object")}function SKs(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return xCp(e,Error)}}function xCp(e,t){try{return e instanceof t}catch{return!1}}function jyD(e){return RCp(e,"ErrorEvent")}function RCp(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function wyD(e,t,r,i){let a=i&&i.mechanism||{handled:!0,type:"generic"},u=NCp(a,r,i);return{$exception_list:await Promise.all(u.map(async s=>{let o=await TyD(e,t,s);return o.value=o.value||"",o.type=o.type||"Error",o.mechanism=a,o}))}}function NCp(e,t,r){let i=SyD(e,t,r);return i.cause?[i,...NCp(e,i.cause,r)]:[i]}function SyD(e,t,r){if(SKs(t))return t;if(e.synthetic=!0,PyD(t)){let n=DyD(t);if(n)return n;let a=EyD(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 DyD(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(SKs(r))return r}}function EyD(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=AyD(e);if(jyD(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=MyD(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function MyD(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function AyD(e,t=40){let r=Object.keys(qyD(e));r.sort();let i=r[0];if(!i)return"[object has no keys]";if(i.length>=t)return sCp(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:sCp(a,t)}return""}function sCp(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function qyD(e){return SKs(e)?{message:e.message,name:e.name,stack:e.stack,...cCp(e)}:myD(e)?{type:e.type,target:lCp(e.target),currentTarget:lCp(e.currentTarget),...cCp(e)}:e}function cCp(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 lCp(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function TyD(e,t,r){let i={type:r.name||r.constructor.name,value:r.message},n=CyD(e,r);for(let a of t)n=await a(n);return n.length&&(i.stacktrace={frames:n,type:"raw"}),i}function CyD(e,t){return ByD(e(t.stack||"",1),e)}function ByD(e,t){let r=OyD(t);return e.forEach(i=>{i.filename&&(i.chunk_id=r[i.filename])}),e}var IyD=2e3,sFn=class e{static async captureException(t,r,i,n,a){let u={...a};n||(u.$process_person_profile=!1);let l=await wyD(this.stackParser,this.frameModifiers,r,i);t.capture({event:"$exception",distinctId:n||vKs(),properties:{...l,...u}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(byD(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(IyD)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function zyD(e=process.argv[1]?(0,fFn.dirname)(process.argv[1]):process.cwd(),t=fFn.sep==="\\"){let r=t?fCp(e):e;return i=>{if(!i)return;let n=t?fCp(i):i,{dir:a,base:u,ext:l}=fFn.posix.parse(n);(l===".js"||l===".mjs"||l===".cjs")&&(u=u.slice(0,l.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 fCp(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var r3o=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)}}},kFo=new r3o(25),FCp=new r3o(20),DKs=7,xyD=1e3,RyD=1e4;async function NyD(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"||VyD(u)||WyD(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(FCp.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let u=$yD(a);if(u.every(d=>HyD(n,d)))continue;let l=GyD(kFo,n,{});i.push(FyD(n,u,l))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&LyD(e,kFo),kFo.reduce(),e}function FyD(e,t,r){return new Promise(i=>{let n=(0,ICp.createReadStream)(e),a=(0,zCp.createInterface)({input:n});function u(){n.destroy(),i()}let l=0,d=0,s=t[d];if(s===void 0){u();return}let o=s[0],c=s[1];function b(){FCp.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(l++,!(l<o)&&(r[l]=QyD(g,0),l>=c)){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],c=O[1]}})})}function LyD(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;UyD(r.lineno,r,i)}}function UyD(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=LCp(e);n<e;n++){let a=r[n];if(a===void 0){dCp(t);return}t.pre_context.push(a)}if(r[e]===void 0){dCp(t);return}t.context_line=r[e];let i=UCp(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 dCp(e){delete e.pre_context,delete e.context_line,delete e.post_context}function VyD(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function WyD(e){return e.lineno!==void 0&&e.lineno>RyD||e.colno!==void 0&&e.colno>xyD}function HyD(e,t){let r=kFo.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 $yD(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=pCp(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+DKs:(n.push(i),i=pCp(a)),t++}return n}function pCp(e){return[LCp(e),UCp(e)]}function LCp(e){return Math.max(1,e-DKs)}function UCp(e){return e+DKs}function GyD(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function QyD(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 JyD="4.18.0",cae;(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"})(cae||(cae={}));var _Cp;(function(e){e.Left="left",e.Right="right",e.Center="center"})(_Cp||(_Cp={}));var hCp;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(hCp||(hCp={}));var yCp;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(yCp||(yCp={}));var vCp;(function(e){e.Html="html",e.Text="text"})(vCp||(vCp={}));var bCp;(function(e){e.Number="number",e.Emoji="emoji"})(bCp||(bCp={}));var gCp;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(gCp||(gCp={}));var OCp;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(OCp||(OCp={}));var mCp;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(mCp||(mCp={}));var PCp;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(PCp||(PCp={}));var KyD=e=>{if("flags"in e){let t=XyD(e.flags),r=ZyD(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,VCp(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,YyD(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function YyD(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 XyD=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,EKs(r)]).filter(([,t])=>t!==void 0)),ZyD=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?VCp(i):void 0]}))},EKs=e=>e===void 0?void 0:e.variant??e.enabled,VCp=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},kyD=1,evD=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"]),tvD="utf8";function rvD(e,t){if(!e||typeof e!="string"||ivD(e))throw new Error(t)}function ivD(e){return e.trim().length===0}function nvD(e){return e?.replace(/\/+$/,"")}async function avD(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 jCp(){return new Date().getTime()}function _Ks(){return new Date().toISOString()}function i3o(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function ovD(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function uvD(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 svD(e,t=0,r){let i=uvD(e);return r?.has(i)?!1:parseInt(i,16)/4294967295<t}function wCp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var JDa=String.fromCharCode,SCp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",ZFo={};function cvD(e,t){if(!ZFo[e]){ZFo[e]={};for(let r=0;r<e.length;r++)ZFo[e][e.charAt(r)]=r}return ZFo[e][t]}var oFn={compressToBase64:function(e){if(e==null)return"";let t=oFn._compress(e,6,function(r){return SCp.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:oFn._decompress(e.length,32,function(t){return cvD(SCp,e.charAt(t))})},compress:function(e){return oFn._compress(e,16,function(t){return JDa(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,d="",s="",o="",c=2,b=3,g=2,O=0,m=0,w;for(w=0;w<e.length;w+=1)if(d=e.charAt(w),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(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=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(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++)}for(l=2,u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>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:oFn._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,l=4,d=3,s="",o,c,b,g,O,m,w;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;w=JDa(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;w=JDa(b);break;case 2:return""}for(i[3]=w,c=w,n.push(w);;){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(w=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[l++]=JDa(b),w=l-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[l++]=JDa(b),w=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[w])s=i[w];else if(w===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,d),d++)}}},bKs=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)}},cFn=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()}},KDa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function DCp(e){if(e instanceof cFn){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 hKs(e){return typeof e=="object"&&(e instanceof cFn||e instanceof KDa)}function ECp(e){return typeof e=="object"&&e instanceof cFn&&e.status===413}var gKs;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(gKs||(gKs={}));var OKs=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new bKs,this._isInitialized=!1,rvD(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=nvD(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:hKs},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(cae.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(cae.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(cae.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=vKs();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 l=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",l,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 l=svD(this.apiKey,kyD,evD)?`${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",l)),this.fetchWithRetry(l,d,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(s=>s.json()).then(s=>KyD(s)).catch(s=>{this._events.emit("error",s)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagDetailStateless(t,r,i,n,a,u);if(l===void 0)return{response:void 0,requestId:void 0};let d=EKs(l.response);return d===void 0&&(d=!1),{response:d,requestId:l.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagDetailsStateless(r,i,n,a,u,[t]);return l===void 0?void 0:{response:l.flags[t],requestId:l.requestId}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u,[t]);if(!l)return;let d=l[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 l=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,u);return l?{flags:l.featureFlags,payloads:l.featureFlagPayloads,requestId:l.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,u){await this._initPromise;let l={};(a??this.disableGeoip)&&(l.geoip_disable=!0),u&&(l.flag_keys_to_evaluate=u);let d=await this.getDecide(t,r,i,n,l);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(gKs.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}`,l=new Error(u);this.logMsgIfDebug(()=>console.error(l)),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(cae.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(cae.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(cae.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(cae.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(cae.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=i3o(()=>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:_Ks()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),u=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${jCp()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,l=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(oFn.compressToBase64(a))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:a};try{await this.fetchWithRetry(u,l)}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:_Ks(),uuid:i?.uuid?i.uuid:vKs()};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 DCp(t)})}async flush(){let t=wCp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),wCp([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(cae.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(cae.Queue)||[]).slice(n.length);this.setPersistedProperty(cae.Queue,g),t=g},l={api_key:this.apiKey,batch:a,sent_at:_Ks()};this.historicalMigration&&(l.historical_migration=!0);let d=JSON.stringify(l),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${jCp()}&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(oFn.compressToBase64(d))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:d},c={retryCheck:b=>ECp(b)?!1:hKs(b)};try{await this.fetchWithRetry(s,o,c)}catch(b){if(ECp(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 KDa||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:"",l=-1;try{l=Buffer.byteLength(u,tvD)}catch{l=new TextEncoder().encode(u).length}return await avD(async()=>{let d=null;try{d=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(o){throw new KDa(o)}if(!(r.mode==="no-cors")&&(d.status<200||d.status>=400))throw new cFn(d,l);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(cae.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!hKs(n))throw n;await DCp(n)}};return Promise.race([new Promise((n,a)=>{i3o(()=>{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}},mKs=ovD();if(!mKs){let e=nCp();mKs=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 WCp=mKs,n3o=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()}},HCp=new n3o(async()=>{try{return await import("crypto")}catch{return}});async function lvD(){return await HCp.getValue()}var fvD=new n3o(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await HCp.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function dvD(){return await fvD.getValue()}async function pvD(e){let t=await lvD();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await dvD();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 _vD=60*1e3,hvD=1152921504606847e3,yvD=["is_not"],uFn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},R2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},PKs=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...l}){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=l.fetch||WCp,this.onError=l.onError,this.customHeaders=u,this.onLoad=l.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,l;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){l=d;break}if(l!==void 0)try{u=await this.computeFlagLocally(l,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof R2?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={},l=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 R2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),l=!0}})),{response:a,payloads:u,fallbackToDecide:l}}async computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new R2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let d=this.groupTypeMapping[String(l)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new R2("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,l,d=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of d)try{if(await this.isConditionMatch(t,r,s,i)){let o=s.variant,c=n.multivariate?.variants||[];o&&c.some(b=>b.key===o)?l=o:l=await this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof R2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new R2("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=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((i.properties||[]).length>0){for(let l of i.properties){let d=l.type,s=!1;if(d==="cohort"?s=GCp(l,n,this.cohorts,this.debugMode):s=$Cp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&await MCp(t.key,r)>a/100)}async getMatchingVariant(t,r){let i=await MCp(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(l=>{n=i+l.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:l.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(_vD,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 uFn(`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 uFn(`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 uFn(`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 uFn&&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=i3o(()=>{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=i3o(()=>{a.abort()},this.timeout),i.signal=a.signal}try{return this.fetch(r,i)}finally{clearTimeout(n)}}};async function MCp(e,t,r=""){let i=await pvD(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/hvD}function $Cp(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 R2("Operator is_not_set is not supported")}else throw new R2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!yvD.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function l(s,o){return Array.isArray(s)?s.map(c=>String(c).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,c){if(c==="gt")return s>o;if(c==="gte")return s>=o;if(c==="lt")return s<o;if(c==="lte")return s<=o;throw new Error(`Invalid operator: ${c}`)}switch(a){case"exact":return l(n,u);case"is_not":return!l(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 ACp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return ACp(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=vvD(String(n));if(s==null&&(s=qCp(n)),s==null)throw new R2(`Invalid date: ${n}`);let o=qCp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new R2(`Unknown operator: ${a}`)}}function GCp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new R2("can't match cohort without a given cohort property value");let a=r[n];return QCp(a,t,r,i)}function QCp(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 l of a)try{let d=QCp(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof R2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new R2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let d;l.type==="cohort"?d=GCp(l,t,r,i):d=$Cp(l,t);let s=l.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 R2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new R2("can't match cohort without a given cohort property value");return n==="AND"}}function ACp(e){try{return new RegExp(e),!0}catch{return!1}}function qCp(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 R2(`${e} is in an invalid date format`)}else throw new R2(`The date provided ${e} must be a string, number, or date object`)}function vvD(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 jKs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},bvD=100,TCp=30*1e3,gvD=50*1e3,wKs=class extends OKs{constructor(t,r={}){if(super(t,r),this._memoryStorage=new jKs,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,bvD):TCp,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 PKs({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 sFn(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||gvD}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):WCp(t,r)}getLibraryVersion(){return JyD}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:l,disableGeoip:d,uuid:s}=t,o=g=>{super.captureStateless(r,i,g,{timestamp:l,disableGeoip:d,uuid:s})},c=async(g,O,m)=>(await super.getFeatureFlagsStateless(g,O,void 0,void 0,m)).flags,b=Promise.resolve().then(async()=>{if(u)return await c(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[w,E]of Object.entries(g))O[`$feature/${w}`]=E;let m=Object.keys(g||{}).filter(w=>g?.[w]!==!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:l,disableGeoip:d,uuid:s}=t,o=g=>super.captureStatelessImmediate(r,i,g,{timestamp:l,disableGeoip:d,uuid:s}),c=async(g,O,m)=>(await super.getFeatureFlagsStateless(g,O,void 0,void 0,m)).flags;await Promise.resolve().then(async()=>{if(u)return await c(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[w,E]of Object.entries(g))O[`$feature/${w}`]=E;let m=Object.keys(g||{}).filter(w=>g?.[w]!==!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=TCp){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:l,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),b=c!==void 0,g,O;if(!b&&!u){let w=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(w===void 0)return;O=w.response,c=EKs(O),g=w?.requestId}let m=`${t}_${c}`;return l&&(!(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:c,$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}`]:c,$feature_flag_request_id:g},groups:n,disableGeoip:a})),c}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:l,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},c=this.addLocalPersonAndGroupProperties(r,a,s,o);s=c.allPersonProperties,o=c.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))),l==null&&(l=!1),d==null&&(d=!0),l==null&&(l=!1),!(b!==void 0)&&!l&&(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:l}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,l),o={},c={},b=!0;if(s&&(o=s.response,c=s.payloads,b=s.fallbackToDecide),b&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,l,n);o={...o,...g.flags||{}},c={...c,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:c}}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 l of Object.keys(r))u[l]={$group_key:r[l],...n?.[l]||{}};return{allPersonProperties:a,allGroupProperties:u}}captureException(t,r,i){let n=new Error("PostHog syntheticException");sFn.captureException(this,t,{syntheticException:n},r,i)}},CCp=/\(error: (.*)\)/,JCp=50,KCp="?";function OvD(e){let t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return i=>{let n=i.match(r);if(n){let a,u,l,d,s;if(n[1]){l=n[1];let b=l.lastIndexOf(".");if(l[b-1]==="."&&b--,b>0){a=l.slice(0,b),u=l.slice(b+1);let g=a.indexOf(".Module");g>0&&(l=l.slice(g+1),a=a.slice(0,g))}d=void 0}u&&(d=a,s=u),u==="<anonymous>"&&(s=void 0,l=void 0),l===void 0&&(s=s||KCp,l=d?`${d}.${s}`:s);let o=n[2]?.startsWith("file://")?n[2].slice(7):n[2],c=n[5]==="native";return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),!o&&n[5]&&!c&&(o=n[5]),{filename:o?decodeURI(o):void 0,module:e?e(o):void 0,function:l,lineno:BCp(n[3]),colno:BCp(n[4]),in_app:mvD(o||"",c),platform:"node:javascript"}}if(i.match(t))return{filename:i,platform:"node:javascript"}}}function mvD(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 BCp(e){return parseInt(e||"",10)||void 0}function PvD(e){return[90,OvD(e)]}function jvD(e){let r=[PvD(e)].sort((i,n)=>i[0]-n[0]).map(i=>i[1]);return(i,n=0)=>{let a=[],u=i.split(`
|
|
1715
|
-
`);for(let l=n;l<u.length;l++){let d=u[l];if(d.length>1024)continue;let s=CCp.test(d)?d.replace(CCp,"$1"):d;if(!s.match(/\S*Error: /)){for(let o of r){let c=o(s);if(c){a.push(c);break}}if(a.length>=JCp)break}}return wvD(a)}}function wvD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,JCp).map(r=>({...r,filename:r.filename||SvD(t).filename,function:r.function||KCp}))}function SvD(e){return e[e.length-1]||{}}sFn.stackParser=jvD(zyD());sFn.frameModifiers=[NyD];var lFn=class extends wKs{getLibraryId(){return"posthog-node"}};var a3o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new lFn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.64.35",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var YDa=class{async sendEvent(){}async identify(){}async flush(){}};var dFn=require("fs/promises"),kCp=require("os"),eBp=require("path");var YCp=ui(require("crypto")),u3o=new Uint8Array(256),o3o=u3o.length;function MKs(){return o3o>u3o.length-16&&(YCp.default.randomFillSync(u3o),o3o=0),u3o.slice(o3o,o3o+=16)}var EW=[];for(let e=0;e<256;++e)EW.push((e+256).toString(16).slice(1));function XCp(e,t=0){return EW[e[t+0]]+EW[e[t+1]]+EW[e[t+2]]+EW[e[t+3]]+"-"+EW[e[t+4]]+EW[e[t+5]]+"-"+EW[e[t+6]]+EW[e[t+7]]+"-"+EW[e[t+8]]+EW[e[t+9]]+"-"+EW[e[t+10]]+EW[e[t+11]]+EW[e[t+12]]+EW[e[t+13]]+EW[e[t+14]]+EW[e[t+15]]}var ZCp=ui(require("crypto")),AKs={randomUUID:ZCp.default.randomUUID};function DvD(e,t,r){if(AKs.randomUUID&&!t&&!e)return AKs.randomUUID();e=e||{};let i=e.random||(e.rng||MKs)();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 XCp(i)}var lae=DvD;var EvD="id",MvD=".fern",XDa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new lFn(r),this.userId=t==null?void 0:gVs(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.64.35",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ru(ll.of((0,kCp.homedir)()),Na.of(MvD),Na.of(EvD));await mf(t)||(await(0,dFn.mkdir)((0,eBp.dirname)(t),{recursive:!0}),await(0,dFn.writeFile)(t,lae())),this.persistedDistinctId=(await(0,dFn.readFile)(t)).toString()}return this.persistedDistinctId}};var qKs;async function pFn(){return qKs==null&&(qKs=await AvD()),qKs}async function AvD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new YDa;let r=await DBo();return r!=null?new XDa({token:r,posthogApiKey:e}):await dRn()!=null?new a3o({posthogApiKey:e}):new XDa({token:void 0,posthogApiKey:e})}catch{return new YDa}}function ZDa(e,t){return function(){return e.apply(t,arguments)}}var{toString:qvD}=Object.prototype,{getPrototypeOf:CKs}=Object,{iterator:c3o,toStringTag:rBp}=Symbol,l3o=(e=>t=>{let r=qvD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),iWt=e=>(e=e.toLowerCase(),t=>l3o(t)===e),f3o=e=>t=>typeof t===e,{isArray:_Fn}=Array,kDa=f3o("undefined");function TvD(e){return e!==null&&!kDa(e)&&e.constructor!==null&&!kDa(e.constructor)&&fae(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var iBp=iWt("ArrayBuffer");function CvD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&iBp(e.buffer),t}var BvD=f3o("string"),fae=f3o("function"),nBp=f3o("number"),d3o=e=>e!==null&&typeof e=="object",IvD=e=>e===!0||e===!1,s3o=e=>{if(l3o(e)!=="object")return!1;let t=CKs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(rBp in e)&&!(c3o in e)},zvD=iWt("Date"),xvD=iWt("File"),RvD=iWt("Blob"),NvD=iWt("FileList"),FvD=e=>d3o(e)&&fae(e.pipe),LvD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||fae(e.append)&&((t=l3o(e))==="formdata"||t==="object"&&fae(e.toString)&&e.toString()==="[object FormData]"))},UvD=iWt("URLSearchParams"),[VvD,WvD,HvD,$vD]=["ReadableStream","Request","Response","Headers"].map(iWt),GvD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function eEa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),_Fn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function aBp(e,t){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 FHi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,oBp=e=>!kDa(e)&&e!==FHi;function TKs(){let{caseless:e}=oBp(this)&&this||{},t={},r=(i,n)=>{let a=e&&aBp(t,n)||n;s3o(t[a])&&s3o(i)?t[a]=TKs(t[a],i):s3o(i)?t[a]=TKs({},i):_Fn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&eEa(arguments[i],r);return t}var QvD=(e,t,r,{allOwnKeys:i}={})=>(eEa(t,(n,a)=>{r&&fae(n)?e[a]=ZDa(n,r):e[a]=n},{allOwnKeys:i}),e),JvD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),KvD=(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)},YvD=(e,t,r,i)=>{let n,a,u,l={};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))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&CKs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},XvD=(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},ZvD=e=>{if(!e)return null;if(_Fn(e))return e;let t=e.length;if(!nBp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},kvD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&CKs(Uint8Array)),ebD=(e,t)=>{let i=(e&&e[c3o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},tbD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},rbD=iWt("HTMLFormElement"),ibD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),tBp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),nbD=iWt("RegExp"),uBp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};eEa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},abD=e=>{uBp(e,(t,r)=>{if(fae(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(fae(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+"'")})}})},obD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return _Fn(e)?i(e):i(String(e).split(t)),r},ubD=()=>{},sbD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function cbD(e){return!!(e&&fae(e.append)&&e[rBp]==="FormData"&&e[c3o])}var lbD=e=>{let t=new Array(10),r=(i,n)=>{if(d3o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=_Fn(i)?[]:{};return eEa(i,(u,l)=>{let d=r(u,n+1);!kDa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},fbD=iWt("AsyncFunction"),dbD=e=>e&&(d3o(e)||fae(e))&&fae(e.then)&&fae(e.catch),sBp=((e,t)=>e?setImmediate:t?((r,i)=>(FHi.addEventListener("message",({source:n,data:a})=>{n===FHi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),FHi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",fae(FHi.postMessage)),pbD=typeof queueMicrotask<"u"?queueMicrotask.bind(FHi):typeof process<"u"&&process.nextTick||sBp,_bD=e=>e!=null&&fae(e[c3o]),os={isArray:_Fn,isArrayBuffer:iBp,isBuffer:TvD,isFormData:LvD,isArrayBufferView:CvD,isString:BvD,isNumber:nBp,isBoolean:IvD,isObject:d3o,isPlainObject:s3o,isReadableStream:VvD,isRequest:WvD,isResponse:HvD,isHeaders:$vD,isUndefined:kDa,isDate:zvD,isFile:xvD,isBlob:RvD,isRegExp:nbD,isFunction:fae,isStream:FvD,isURLSearchParams:UvD,isTypedArray:kvD,isFileList:NvD,forEach:eEa,merge:TKs,extend:QvD,trim:GvD,stripBOM:JvD,inherits:KvD,toFlatObject:YvD,kindOf:l3o,kindOfTest:iWt,endsWith:XvD,toArray:ZvD,forEachEntry:ebD,matchAll:tbD,isHTMLForm:rbD,hasOwnProperty:tBp,hasOwnProp:tBp,reduceDescriptors:uBp,freezeMethods:abD,toObjectSet:obD,toCamelCase:ibD,noop:ubD,toFiniteNumber:sbD,findKey:aBp,global:FHi,isContextDefined:oBp,isSpecCompliantForm:cbD,toJSONObject:lbD,isAsyncFn:fbD,isThenable:dbD,setImmediate:sBp,asap:pbD,isIterable:_bD};function hFn(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)}os.inherits(hFn,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:os.toJSONObject(this.config),code:this.code,status:this.status}}});var cBp=hFn.prototype,lBp={};["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=>{lBp[e]={value:e}});Object.defineProperties(hFn,lBp);Object.defineProperty(cBp,"isAxiosError",{value:!0});hFn.from=(e,t,r,i,n,a)=>{let u=Object.create(cBp);return os.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),hFn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Fp=hFn;var fBp=ui(BFo(),1),p3o=fBp.default;function BKs(e){return os.isPlainObject(e)||os.isArray(e)}function pBp(e){return os.endsWith(e,"[]")?e.slice(0,-2):e}function dBp(e,t,r){return e?e.concat(t).map(function(n,a){return n=pBp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function hbD(e){return os.isArray(e)&&!e.some(BKs)}var ybD=os.toFlatObject(os,{},null,function(t){return/^is[A-Z]/.test(t)});function vbD(e,t,r){if(!os.isObject(e))throw new TypeError("target must be an object");t=t||new(p3o||FormData),r=os.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!os.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&os.isSpecCompliantForm(t);if(!os.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(os.isDate(O))return O.toISOString();if(os.isBoolean(O))return O.toString();if(!d&&os.isBlob(O))throw new Fp("Blob is not supported. Use a Buffer instead.");return os.isArrayBuffer(O)||os.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let E=O;if(O&&!w&&typeof O=="object"){if(os.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(os.isArray(O)&&hbD(O)||(os.isFileList(O)||os.endsWith(m,"[]"))&&(E=os.toArray(O)))return m=pBp(m),E.forEach(function(A,D){!(os.isUndefined(A)||A===null)&&t.append(u===!0?dBp([m],D,a):u===null?m:m+"[]",s(A))}),!1}return BKs(O)?!0:(t.append(dBp(w,m,a),s(O)),!1)}let c=[],b=Object.assign(ybD,{defaultVisitor:o,convertValue:s,isVisitable:BKs});function g(O,m){if(!os.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),os.forEach(O,function(E,q){(!(os.isUndefined(E)||E===null)&&n.call(t,E,os.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!os.isObject(e))throw new TypeError("data must be an object");return g(e),t}var VSi=vbD;function _Bp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function hBp(e,t){this._pairs=[],e&&VSi(e,this,t)}var yBp=hBp.prototype;yBp.append=function(t,r){this._pairs.push([t,r])};yBp.toString=function(t){let r=t?function(i){return t.call(this,i,_Bp)}:_Bp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var vBp=hBp;function bbD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function LHi(e,t,r){if(!t)return e;let i=r&&r.encode||bbD;os.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=os.isURLSearchParams(t)?t.toString():new vBp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var IKs=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){os.forEach(this.handlers,function(i){i!==null&&t(i)})}},zKs=IKs;var yFn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var mBp=ui(require("crypto"),1);var bBp=ui(require("url"),1),gBp=bBp.default.URLSearchParams;var xKs="abcdefghijklmnopqrstuvwxyz",OBp="0123456789",PBp={DIGIT:OBp,ALPHA:xKs,ALPHA_DIGIT:xKs+xKs.toUpperCase()+OBp},gbD=(e=16,t=PBp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);mBp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},jBp={isNode:!0,classes:{URLSearchParams:gBp,FormData:p3o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:PBp,generateString:gbD,protocols:["http","https","file","data"]};var FKs={};Po(FKs,{hasBrowserEnv:()=>NKs,hasStandardBrowserEnv:()=>ObD,hasStandardBrowserWebWorkerEnv:()=>mbD,navigator:()=>RKs,origin:()=>PbD});var NKs=typeof window<"u"&&typeof document<"u",RKs=typeof navigator=="object"&&navigator||void 0,ObD=NKs&&(!RKs||["ReactNative","NativeScript","NS"].indexOf(RKs.product)<0),mbD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",PbD=NKs&&window.location.href||"http://localhost";var aA={...FKs,...jBp};function LKs(e,t){return VSi(e,new aA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return aA.isNode&&os.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function jbD(e){return os.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function wbD(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 SbD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&os.isArray(n)?n.length:u,d?(os.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!os.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&os.isArray(n[u])&&(n[u]=wbD(n[u])),!l)}if(os.isFormData(e)&&os.isFunction(e.entries)){let r={};return os.forEachEntry(e,(i,n)=>{t(jbD(i),n,r,0)}),r}return null}var _3o=SbD;function DbD(e,t,r){if(os.isString(e))try{return(t||JSON.parse)(e),os.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var UKs={transitional:yFn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=os.isObject(t);if(a&&os.isHTMLForm(t)&&(t=new FormData(t)),os.isFormData(t))return n?JSON.stringify(_3o(t)):t;if(os.isArrayBuffer(t)||os.isBuffer(t)||os.isStream(t)||os.isFile(t)||os.isBlob(t)||os.isReadableStream(t))return t;if(os.isArrayBufferView(t))return t.buffer;if(os.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return LKs(t,this.formSerializer).toString();if((l=os.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return VSi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),DbD(t)):t}],transformResponse:[function(t){let r=this.transitional||UKs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(os.isResponse(t)||os.isReadableStream(t))return t;if(t&&os.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?Fp.from(l,Fp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:aA.classes.FormData,Blob:aA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};os.forEach(["delete","get","head","post","put","patch"],e=>{UKs.headers[e]={}});var vFn=UKs;var EbD=os.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"]),wBp=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1715
|
+
`);for(let l=n;l<u.length;l++){let d=u[l];if(d.length>1024)continue;let s=CCp.test(d)?d.replace(CCp,"$1"):d;if(!s.match(/\S*Error: /)){for(let o of r){let c=o(s);if(c){a.push(c);break}}if(a.length>=JCp)break}}return wvD(a)}}function wvD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,JCp).map(r=>({...r,filename:r.filename||SvD(t).filename,function:r.function||KCp}))}function SvD(e){return e[e.length-1]||{}}sFn.stackParser=jvD(zyD());sFn.frameModifiers=[NyD];var lFn=class extends wKs{getLibraryId(){return"posthog-node"}};var a3o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new lFn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.64.36",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var YDa=class{async sendEvent(){}async identify(){}async flush(){}};var dFn=require("fs/promises"),kCp=require("os"),eBp=require("path");var YCp=ui(require("crypto")),u3o=new Uint8Array(256),o3o=u3o.length;function MKs(){return o3o>u3o.length-16&&(YCp.default.randomFillSync(u3o),o3o=0),u3o.slice(o3o,o3o+=16)}var EW=[];for(let e=0;e<256;++e)EW.push((e+256).toString(16).slice(1));function XCp(e,t=0){return EW[e[t+0]]+EW[e[t+1]]+EW[e[t+2]]+EW[e[t+3]]+"-"+EW[e[t+4]]+EW[e[t+5]]+"-"+EW[e[t+6]]+EW[e[t+7]]+"-"+EW[e[t+8]]+EW[e[t+9]]+"-"+EW[e[t+10]]+EW[e[t+11]]+EW[e[t+12]]+EW[e[t+13]]+EW[e[t+14]]+EW[e[t+15]]}var ZCp=ui(require("crypto")),AKs={randomUUID:ZCp.default.randomUUID};function DvD(e,t,r){if(AKs.randomUUID&&!t&&!e)return AKs.randomUUID();e=e||{};let i=e.random||(e.rng||MKs)();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 XCp(i)}var lae=DvD;var EvD="id",MvD=".fern",XDa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new lFn(r),this.userId=t==null?void 0:gVs(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.64.36",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ru(ll.of((0,kCp.homedir)()),Na.of(MvD),Na.of(EvD));await mf(t)||(await(0,dFn.mkdir)((0,eBp.dirname)(t),{recursive:!0}),await(0,dFn.writeFile)(t,lae())),this.persistedDistinctId=(await(0,dFn.readFile)(t)).toString()}return this.persistedDistinctId}};var qKs;async function pFn(){return qKs==null&&(qKs=await AvD()),qKs}async function AvD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new YDa;let r=await DBo();return r!=null?new XDa({token:r,posthogApiKey:e}):await dRn()!=null?new a3o({posthogApiKey:e}):new XDa({token:void 0,posthogApiKey:e})}catch{return new YDa}}function ZDa(e,t){return function(){return e.apply(t,arguments)}}var{toString:qvD}=Object.prototype,{getPrototypeOf:CKs}=Object,{iterator:c3o,toStringTag:rBp}=Symbol,l3o=(e=>t=>{let r=qvD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),iWt=e=>(e=e.toLowerCase(),t=>l3o(t)===e),f3o=e=>t=>typeof t===e,{isArray:_Fn}=Array,kDa=f3o("undefined");function TvD(e){return e!==null&&!kDa(e)&&e.constructor!==null&&!kDa(e.constructor)&&fae(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var iBp=iWt("ArrayBuffer");function CvD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&iBp(e.buffer),t}var BvD=f3o("string"),fae=f3o("function"),nBp=f3o("number"),d3o=e=>e!==null&&typeof e=="object",IvD=e=>e===!0||e===!1,s3o=e=>{if(l3o(e)!=="object")return!1;let t=CKs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(rBp in e)&&!(c3o in e)},zvD=iWt("Date"),xvD=iWt("File"),RvD=iWt("Blob"),NvD=iWt("FileList"),FvD=e=>d3o(e)&&fae(e.pipe),LvD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||fae(e.append)&&((t=l3o(e))==="formdata"||t==="object"&&fae(e.toString)&&e.toString()==="[object FormData]"))},UvD=iWt("URLSearchParams"),[VvD,WvD,HvD,$vD]=["ReadableStream","Request","Response","Headers"].map(iWt),GvD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function eEa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),_Fn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function aBp(e,t){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 FHi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,oBp=e=>!kDa(e)&&e!==FHi;function TKs(){let{caseless:e}=oBp(this)&&this||{},t={},r=(i,n)=>{let a=e&&aBp(t,n)||n;s3o(t[a])&&s3o(i)?t[a]=TKs(t[a],i):s3o(i)?t[a]=TKs({},i):_Fn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&eEa(arguments[i],r);return t}var QvD=(e,t,r,{allOwnKeys:i}={})=>(eEa(t,(n,a)=>{r&&fae(n)?e[a]=ZDa(n,r):e[a]=n},{allOwnKeys:i}),e),JvD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),KvD=(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)},YvD=(e,t,r,i)=>{let n,a,u,l={};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))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&CKs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},XvD=(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},ZvD=e=>{if(!e)return null;if(_Fn(e))return e;let t=e.length;if(!nBp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},kvD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&CKs(Uint8Array)),ebD=(e,t)=>{let i=(e&&e[c3o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},tbD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},rbD=iWt("HTMLFormElement"),ibD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),tBp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),nbD=iWt("RegExp"),uBp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};eEa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},abD=e=>{uBp(e,(t,r)=>{if(fae(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(fae(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+"'")})}})},obD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return _Fn(e)?i(e):i(String(e).split(t)),r},ubD=()=>{},sbD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function cbD(e){return!!(e&&fae(e.append)&&e[rBp]==="FormData"&&e[c3o])}var lbD=e=>{let t=new Array(10),r=(i,n)=>{if(d3o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=_Fn(i)?[]:{};return eEa(i,(u,l)=>{let d=r(u,n+1);!kDa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},fbD=iWt("AsyncFunction"),dbD=e=>e&&(d3o(e)||fae(e))&&fae(e.then)&&fae(e.catch),sBp=((e,t)=>e?setImmediate:t?((r,i)=>(FHi.addEventListener("message",({source:n,data:a})=>{n===FHi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),FHi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",fae(FHi.postMessage)),pbD=typeof queueMicrotask<"u"?queueMicrotask.bind(FHi):typeof process<"u"&&process.nextTick||sBp,_bD=e=>e!=null&&fae(e[c3o]),os={isArray:_Fn,isArrayBuffer:iBp,isBuffer:TvD,isFormData:LvD,isArrayBufferView:CvD,isString:BvD,isNumber:nBp,isBoolean:IvD,isObject:d3o,isPlainObject:s3o,isReadableStream:VvD,isRequest:WvD,isResponse:HvD,isHeaders:$vD,isUndefined:kDa,isDate:zvD,isFile:xvD,isBlob:RvD,isRegExp:nbD,isFunction:fae,isStream:FvD,isURLSearchParams:UvD,isTypedArray:kvD,isFileList:NvD,forEach:eEa,merge:TKs,extend:QvD,trim:GvD,stripBOM:JvD,inherits:KvD,toFlatObject:YvD,kindOf:l3o,kindOfTest:iWt,endsWith:XvD,toArray:ZvD,forEachEntry:ebD,matchAll:tbD,isHTMLForm:rbD,hasOwnProperty:tBp,hasOwnProp:tBp,reduceDescriptors:uBp,freezeMethods:abD,toObjectSet:obD,toCamelCase:ibD,noop:ubD,toFiniteNumber:sbD,findKey:aBp,global:FHi,isContextDefined:oBp,isSpecCompliantForm:cbD,toJSONObject:lbD,isAsyncFn:fbD,isThenable:dbD,setImmediate:sBp,asap:pbD,isIterable:_bD};function hFn(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)}os.inherits(hFn,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:os.toJSONObject(this.config),code:this.code,status:this.status}}});var cBp=hFn.prototype,lBp={};["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=>{lBp[e]={value:e}});Object.defineProperties(hFn,lBp);Object.defineProperty(cBp,"isAxiosError",{value:!0});hFn.from=(e,t,r,i,n,a)=>{let u=Object.create(cBp);return os.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),hFn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Fp=hFn;var fBp=ui(BFo(),1),p3o=fBp.default;function BKs(e){return os.isPlainObject(e)||os.isArray(e)}function pBp(e){return os.endsWith(e,"[]")?e.slice(0,-2):e}function dBp(e,t,r){return e?e.concat(t).map(function(n,a){return n=pBp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function hbD(e){return os.isArray(e)&&!e.some(BKs)}var ybD=os.toFlatObject(os,{},null,function(t){return/^is[A-Z]/.test(t)});function vbD(e,t,r){if(!os.isObject(e))throw new TypeError("target must be an object");t=t||new(p3o||FormData),r=os.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!os.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&os.isSpecCompliantForm(t);if(!os.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(os.isDate(O))return O.toISOString();if(os.isBoolean(O))return O.toString();if(!d&&os.isBlob(O))throw new Fp("Blob is not supported. Use a Buffer instead.");return os.isArrayBuffer(O)||os.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let E=O;if(O&&!w&&typeof O=="object"){if(os.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(os.isArray(O)&&hbD(O)||(os.isFileList(O)||os.endsWith(m,"[]"))&&(E=os.toArray(O)))return m=pBp(m),E.forEach(function(A,D){!(os.isUndefined(A)||A===null)&&t.append(u===!0?dBp([m],D,a):u===null?m:m+"[]",s(A))}),!1}return BKs(O)?!0:(t.append(dBp(w,m,a),s(O)),!1)}let c=[],b=Object.assign(ybD,{defaultVisitor:o,convertValue:s,isVisitable:BKs});function g(O,m){if(!os.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),os.forEach(O,function(E,q){(!(os.isUndefined(E)||E===null)&&n.call(t,E,os.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!os.isObject(e))throw new TypeError("data must be an object");return g(e),t}var VSi=vbD;function _Bp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function hBp(e,t){this._pairs=[],e&&VSi(e,this,t)}var yBp=hBp.prototype;yBp.append=function(t,r){this._pairs.push([t,r])};yBp.toString=function(t){let r=t?function(i){return t.call(this,i,_Bp)}:_Bp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var vBp=hBp;function bbD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function LHi(e,t,r){if(!t)return e;let i=r&&r.encode||bbD;os.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=os.isURLSearchParams(t)?t.toString():new vBp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var IKs=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){os.forEach(this.handlers,function(i){i!==null&&t(i)})}},zKs=IKs;var yFn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var mBp=ui(require("crypto"),1);var bBp=ui(require("url"),1),gBp=bBp.default.URLSearchParams;var xKs="abcdefghijklmnopqrstuvwxyz",OBp="0123456789",PBp={DIGIT:OBp,ALPHA:xKs,ALPHA_DIGIT:xKs+xKs.toUpperCase()+OBp},gbD=(e=16,t=PBp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);mBp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},jBp={isNode:!0,classes:{URLSearchParams:gBp,FormData:p3o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:PBp,generateString:gbD,protocols:["http","https","file","data"]};var FKs={};Po(FKs,{hasBrowserEnv:()=>NKs,hasStandardBrowserEnv:()=>ObD,hasStandardBrowserWebWorkerEnv:()=>mbD,navigator:()=>RKs,origin:()=>PbD});var NKs=typeof window<"u"&&typeof document<"u",RKs=typeof navigator=="object"&&navigator||void 0,ObD=NKs&&(!RKs||["ReactNative","NativeScript","NS"].indexOf(RKs.product)<0),mbD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",PbD=NKs&&window.location.href||"http://localhost";var aA={...FKs,...jBp};function LKs(e,t){return VSi(e,new aA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return aA.isNode&&os.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function jbD(e){return os.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function wbD(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 SbD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&os.isArray(n)?n.length:u,d?(os.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!os.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&os.isArray(n[u])&&(n[u]=wbD(n[u])),!l)}if(os.isFormData(e)&&os.isFunction(e.entries)){let r={};return os.forEachEntry(e,(i,n)=>{t(jbD(i),n,r,0)}),r}return null}var _3o=SbD;function DbD(e,t,r){if(os.isString(e))try{return(t||JSON.parse)(e),os.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var UKs={transitional:yFn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=os.isObject(t);if(a&&os.isHTMLForm(t)&&(t=new FormData(t)),os.isFormData(t))return n?JSON.stringify(_3o(t)):t;if(os.isArrayBuffer(t)||os.isBuffer(t)||os.isStream(t)||os.isFile(t)||os.isBlob(t)||os.isReadableStream(t))return t;if(os.isArrayBufferView(t))return t.buffer;if(os.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return LKs(t,this.formSerializer).toString();if((l=os.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return VSi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),DbD(t)):t}],transformResponse:[function(t){let r=this.transitional||UKs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(os.isResponse(t)||os.isReadableStream(t))return t;if(t&&os.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?Fp.from(l,Fp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:aA.classes.FormData,Blob:aA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};os.forEach(["delete","get","head","post","put","patch"],e=>{UKs.headers[e]={}});var vFn=UKs;var EbD=os.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"]),wBp=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1716
1716
|
`).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&EbD[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var SBp=Symbol("internals");function tEa(e){return e&&String(e).trim().toLowerCase()}function h3o(e){return e===!1||e==null?e:os.isArray(e)?e.map(h3o):String(e)}function MbD(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 AbD=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function VKs(e,t,r,i,n){if(os.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!os.isString(t)){if(os.isString(i))return t.indexOf(i)!==-1;if(os.isRegExp(i))return i.test(t)}}function qbD(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function TbD(e,t){let r=os.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 bFn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,d,s){let o=tEa(d);if(!o)throw new Error("header name must be a non-empty string");let c=os.findKey(n,o);(!c||n[c]===void 0||s===!0||s===void 0&&n[c]!==!1)&&(n[c||d]=h3o(l))}let u=(l,d)=>os.forEach(l,(s,o)=>a(s,o,d));if(os.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(os.isString(t)&&(t=t.trim())&&!AbD(t))u(wBp(t),r);else if(os.isObject(t)&&os.isIterable(t)){let l={},d,s;for(let o of t){if(!os.isArray(o))throw TypeError("Object iterator must return a key-value pair");l[s=o[0]]=(d=l[s])?os.isArray(d)?[...d,o[1]]:[d,o[1]]:o[1]}u(l,r)}else t!=null&&a(r,t,i);return this}get(t,r){if(t=tEa(t),t){let i=os.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return MbD(n);if(os.isFunction(r))return r.call(this,n,i);if(os.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=tEa(t),t){let i=os.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||VKs(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=tEa(u),u){let l=os.findKey(i,u);l&&(!r||VKs(i,i[l],l,r))&&(delete i[l],n=!0)}}return os.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||VKs(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return os.forEach(this,(n,a)=>{let u=os.findKey(i,a);if(u){r[u]=h3o(n),delete r[a];return}let l=t?qbD(a):String(a).trim();l!==a&&delete r[a],r[l]=h3o(n),i[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return os.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&os.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(`
|
|
1717
1717
|
`)}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[SBp]=this[SBp]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=tEa(u);i[l]||(TbD(n,u),i[l]=!0)}return os.isArray(t)?t.forEach(a):a(t),this}};bFn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);os.reduceDescriptors(bFn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});os.freezeMethods(bFn);var rR=bFn;function rEa(e,t){let r=this||vFn,i=t||r,n=rR.from(i.headers),a=i.data;return os.forEach(e,function(l){a=l.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function iEa(e){return!!(e&&e.__CANCEL__)}function DBp(e,t,r){Fp.call(this,e??"canceled",Fp.ERR_CANCELED,t,r),this.name="CanceledError"}os.inherits(DBp,Fp,{__CANCEL__:!0});var REe=DBp;function Ltr(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Fp("Request failed with status code "+r.status,[Fp.ERR_BAD_REQUEST,Fp.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function WKs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function HKs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function UHi(e,t,r){let i=!WKs(t);return e&&(i||r==!1)?HKs(e,t):t}var VBp=ui(FDa(),1),WBp=ui(require("http"),1),HBp=ui(require("https"),1),$Bp=ui(require("util"),1),GBp=ui(HJs(),1),afi=ui(require("zlib"),1);var VHi="1.10.0";function nEa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var CbD=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function $Ks(e,t,r){let i=r&&r.Blob||aA.classes.Blob,n=nEa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=CbD.exec(e);if(!a)throw new Fp("Invalid URL",Fp.ERR_INVALID_URL);let u=a[1],l=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),l?"base64":"utf8");if(t){if(!i)throw new Fp("Blob is not supported",Fp.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new Fp("Unsupported protocol "+n,Fp.ERR_NOT_SUPPORT)}var HHi=ui(require("stream"),1);var EBp=ui(require("stream"),1);var GKs=Symbol("internals"),QKs=class extends EBp.default.Transform{constructor(t){t=os.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!os.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[GKs]={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[GKs];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[GKs],a=n.maxRate,u=this.readableHighWaterMark,l=n.timeWindow,d=1e3/l,s=a/d,o=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,c=(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),w=null,E=u,q,A=0;if(a){let D=Date.now();(!n.ts||(A=D-n.ts)>=l)&&(n.ts=D,q=s-n.bytes,n.bytes=q<0?-q:0,A=0),q=s-n.bytes}if(a){if(q<=0)return setTimeout(()=>{O(null,g)},l-A);q<E&&(E=q)}E&&m>E&&m-E>o&&(w=g.subarray(E),g=g.subarray(0,E)),c(g,w?()=>{process.nextTick(O,null,w)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},JKs=QKs;var QBp=require("events");var ABp=ui(require("util"),1),qBp=require("stream");var{asyncIterator:MBp}=Symbol,BbD=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[MBp]?yield*e[MBp]():yield e},y3o=BbD;var IbD=aA.ALPHABET.ALPHA_DIGIT+"-_",aEa=typeof TextEncoder=="function"?new TextEncoder:new ABp.default.TextEncoder,WHi=`\r
|
|
1718
1718
|
`,zbD=aEa.encode(WHi),xbD=2,KKs=class{constructor(t,r){let{escapeName:i}=this.constructor,n=os.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${WHi}`;n?r=aEa.encode(String(r).replace(/\r?\n|\r\n?/g,WHi)):a+=`Content-Type: ${r.type||"application/octet-stream"}${WHi}`,this.headers=aEa.encode(a+WHi),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+xbD,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;os.isTypedArray(t)?yield t:yield*y3o(t),yield zbD}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},RbD=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+aA.generateString(n,IbD)}=r||{};if(!os.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=aEa.encode("--"+a+WHi),l=aEa.encode("--"+a+"--"+WHi),d=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new KKs(c,b);return d+=g.size,g});d+=u.byteLength*s.length,d=os.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),qBp.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},TBp=RbD;var CBp=ui(require("stream"),1),YKs=class extends CBp.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)}},BBp=YKs;var NbD=(e,t)=>os.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,IBp=NbD;function FbD(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 c=a,b=0;for(;c!==n;)b+=r[c++],c=c%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 zBp=FbD;function LbD(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.apply(null,s)};return[(...s)=>{let o=Date.now(),c=o-r;c>=i?u(s,o):(n=s,a||(a=setTimeout(()=>{a=null,u(n)},i-c)))},()=>n&&u(n)]}var xBp=LbD;var nfi=(e,t,r=3)=>{let i=0,n=zBp(50,250);return xBp(a=>{let u=a.loaded,l=a.lengthComputable?a.total:void 0,d=u-i,s=n(d),o=u<=l;i=u;let c={loaded:u,total:l,progress:l?u/l:void 0,bytes:d,rate:s||void 0,estimated:s&&l&&o?(l-u)/s:void 0,event:a,lengthComputable:l!=null,[t?"download":"upload"]:!0};e(c)},r)},gFn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},OFn=e=>(...t)=>os.asap(()=>e(...t));var RBp={flush:afi.default.constants.Z_SYNC_FLUSH,finishFlush:afi.default.constants.Z_SYNC_FLUSH},UbD={flush:afi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:afi.default.constants.BROTLI_OPERATION_FLUSH},NBp=os.isFunction(afi.default.createBrotliDecompress),{http:VbD,https:WbD}=GBp.default,HbD=/https:?/,FBp=aA.protocols.map(e=>e+":"),LBp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function $bD(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function JBp(e,t,r){let i=t;if(!i&&i!==!1){let n=VBp.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){JBp(a,t,a.href)}}var GbD=typeof process<"u"&&os.kindOf(process)==="process",QbD=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},u=d=>{a(d),t(d)},l=d=>{a(d,!0),r(d)};e(u,l,d=>i=d).catch(l)}),JbD=({address:e,family:t})=>{if(!os.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},UBp=(e,t)=>JbD(os.isObject(e)?e:{address:e,family:t}),KBp=GbD&&function(t){return QbD(async function(i,n,a){let{data:u,lookup:l,family:d}=t,{responseType:s,responseEncoding:o}=t,c=t.method.toUpperCase(),b,g=!1,O;if(l){let Oe=IBp(l,Ue=>os.isArray(Ue)?Ue:[Ue]);l=(Ue,wt,De)=>{Oe(Ue,wt,(Te,xt,Pe)=>{if(Te)return De(Te);let ot=os.isArray(xt)?xt.map(at=>UBp(at)):[UBp(xt,Pe)];wt.all?De(Te,ot):De(Te,ot[0].address,ot[0].family)})}}let m=new QBp.EventEmitter,w=()=>{t.cancelToken&&t.cancelToken.unsubscribe(E),t.signal&&t.signal.removeEventListener("abort",E),m.removeAllListeners()};a((Oe,Ue)=>{b=!0,Ue&&(g=!0,w())});function E(Oe){m.emit("abort",!Oe||Oe.type?new REe(null,t,O):Oe)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(E),t.signal&&(t.signal.aborted?E():t.signal.addEventListener("abort",E)));let q=UHi(t.baseURL,t.url,t.allowAbsoluteUrls),A=new URL(q,aA.hasBrowserEnv?aA.origin:void 0),D=A.protocol||FBp[0];if(D==="data:"){let Oe;if(c!=="GET")return Ltr(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{Oe=$Ks(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Ue){throw Fp.from(Ue,Fp.ERR_BAD_REQUEST,t)}return s==="text"?(Oe=Oe.toString(o),(!o||o==="utf8")&&(Oe=os.stripBOM(Oe))):s==="stream"&&(Oe=HHi.default.Readable.from(Oe)),Ltr(i,n,{data:Oe,status:200,statusText:"OK",headers:new rR,config:t})}if(FBp.indexOf(D)===-1)return n(new Fp("Unsupported protocol "+D,Fp.ERR_BAD_REQUEST,t));let C=rR.from(t.headers).normalize();C.set("User-Agent","axios/"+VHi,!1);let{onUploadProgress:x,onDownloadProgress:$}=t,I=t.maxRate,F,V;if(os.isSpecCompliantForm(u)){let Oe=C.getContentType(/boundary=([-_\w\d]{10,70})/i);u=TBp(u,Ue=>{C.set(Ue)},{tag:`axios-${VHi}-boundary`,boundary:Oe&&Oe[1]||void 0})}else if(os.isFormData(u)&&os.isFunction(u.getHeaders)){if(C.set(u.getHeaders()),!C.hasContentLength())try{let Oe=await $Bp.default.promisify(u.getLength).call(u);Number.isFinite(Oe)&&Oe>=0&&C.setContentLength(Oe)}catch{}}else if(os.isBlob(u)||os.isFile(u))u.size&&C.setContentType(u.type||"application/octet-stream"),C.setContentLength(u.size||0),u=HHi.default.Readable.from(y3o(u));else if(u&&!os.isStream(u)){if(!Buffer.isBuffer(u))if(os.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(os.isString(u))u=Buffer.from(u,"utf-8");else return n(new Fp("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Fp.ERR_BAD_REQUEST,t));if(C.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new Fp("Request body larger than maxBodyLength limit",Fp.ERR_BAD_REQUEST,t))}let K=os.toFiniteNumber(C.getContentLength());os.isArray(I)?(F=I[0],V=I[1]):F=V=I,u&&(x||F)&&(os.isStream(u)||(u=HHi.default.Readable.from(u,{objectMode:!1})),u=HHi.default.pipeline([u,new JKs({maxRate:os.toFiniteNumber(F)})],os.noop),x&&u.on("progress",LBp(u,gFn(K,nfi(OFn(x),!1,3)))));let Y;if(t.auth){let Oe=t.auth.username||"",Ue=t.auth.password||"";Y=Oe+":"+Ue}if(!Y&&A.username){let Oe=A.username,Ue=A.password;Y=Oe+":"+Ue}Y&&C.delete("authorization");let Z;try{Z=LHi(A.pathname+A.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(Oe){let Ue=new Error(Oe.message);return Ue.config=t,Ue.url=t.url,Ue.exists=!0,n(Ue)}C.set("Accept-Encoding","gzip, compress, deflate"+(NBp?", br":""),!1);let oe={path:Z,method:c,headers:C.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:Y,protocol:D,family:d,beforeRedirect:$bD,beforeRedirects:{}};!os.isUndefined(l)&&(oe.lookup=l),t.socketPath?oe.socketPath=t.socketPath:(oe.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,oe.port=A.port,JBp(oe,t.proxy,D+"//"+A.hostname+(A.port?":"+A.port:"")+oe.path));let pe,de=HbD.test(oe.protocol);if(oe.agent=de?t.httpsAgent:t.httpAgent,t.transport?pe=t.transport:t.maxRedirects===0?pe=de?HBp.default:WBp.default:(t.maxRedirects&&(oe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(oe.beforeRedirects.config=t.beforeRedirect),pe=de?WbD:VbD),t.maxBodyLength>-1?oe.maxBodyLength=t.maxBodyLength:oe.maxBodyLength=1/0,t.insecureHTTPParser&&(oe.insecureHTTPParser=t.insecureHTTPParser),O=pe.request(oe,function(Ue){if(O.destroyed)return;let wt=[Ue],De=+Ue.headers["content-length"];if($||V){let at=new JKs({maxRate:os.toFiniteNumber(V)});$&&at.on("progress",LBp(at,gFn(De,nfi(OFn($),!0,3)))),wt.push(at)}let Te=Ue,xt=Ue.req||O;if(t.decompress!==!1&&Ue.headers["content-encoding"])switch((c==="HEAD"||Ue.statusCode===204)&&delete Ue.headers["content-encoding"],(Ue.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":wt.push(afi.default.createUnzip(RBp)),delete Ue.headers["content-encoding"];break;case"deflate":wt.push(new BBp),wt.push(afi.default.createUnzip(RBp)),delete Ue.headers["content-encoding"];break;case"br":NBp&&(wt.push(afi.default.createBrotliDecompress(UbD)),delete Ue.headers["content-encoding"])}Te=wt.length>1?HHi.default.pipeline(wt,os.noop):wt[0];let Pe=HHi.default.finished(Te,()=>{Pe(),w()}),ot={status:Ue.statusCode,statusText:Ue.statusMessage,headers:new rR(Ue.headers),config:t,request:xt};if(s==="stream")ot.data=Te,Ltr(i,n,ot);else{let at=[],me=0;Te.on("data",function(jt){at.push(jt),me+=jt.length,t.maxContentLength>-1&&me>t.maxContentLength&&(g=!0,Te.destroy(),n(new Fp("maxContentLength size of "+t.maxContentLength+" exceeded",Fp.ERR_BAD_RESPONSE,t,xt)))}),Te.on("aborted",function(){if(g)return;let jt=new Fp("stream has been aborted",Fp.ERR_BAD_RESPONSE,t,xt);Te.destroy(jt),n(jt)}),Te.on("error",function(jt){O.destroyed||n(Fp.from(jt,null,t,xt))}),Te.on("end",function(){try{let jt=at.length===1?at[0]:Buffer.concat(at);s!=="arraybuffer"&&(jt=jt.toString(o),(!o||o==="utf8")&&(jt=os.stripBOM(jt))),ot.data=jt}catch(jt){return n(Fp.from(jt,null,t,ot.request,ot))}Ltr(i,n,ot)})}m.once("abort",at=>{Te.destroyed||(Te.emit("error",at),Te.destroy())})}),m.once("abort",Oe=>{n(Oe),O.destroy(Oe)}),O.on("error",function(Ue){n(Fp.from(Ue,null,t,O))}),O.on("socket",function(Ue){Ue.setKeepAlive(!0,1e3*60)}),t.timeout){let Oe=parseInt(t.timeout,10);if(Number.isNaN(Oe)){n(new Fp("error trying to parse `config.timeout` to int",Fp.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(Oe,function(){if(b)return;let wt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",De=t.transitional||yFn;t.timeoutErrorMessage&&(wt=t.timeoutErrorMessage),n(new Fp(wt,De.clarifyTimeoutError?Fp.ETIMEDOUT:Fp.ECONNABORTED,t,O)),E()})}if(os.isStream(u)){let Oe=!1,Ue=!1;u.on("end",()=>{Oe=!0}),u.once("error",wt=>{Ue=!0,O.destroy(wt)}),u.on("close",()=>{!Oe&&!Ue&&E(new REe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var YBp=aA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,aA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(aA.origin),aA.navigator&&/(msie|trident)/i.test(aA.navigator.userAgent)):()=>!0;var XBp=aA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];os.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),os.isString(i)&&u.push("path="+i),os.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 ZBp=e=>e instanceof rR?{...e}:e;function nWt(e,t){t=t||{};let r={};function i(s,o,c,b){return os.isPlainObject(s)&&os.isPlainObject(o)?os.merge.call({caseless:b},s,o):os.isPlainObject(o)?os.merge({},o):os.isArray(o)?o.slice():o}function n(s,o,c,b){if(os.isUndefined(o)){if(!os.isUndefined(s))return i(void 0,s,c,b)}else return i(s,o,c,b)}function a(s,o){if(!os.isUndefined(o))return i(void 0,o)}function u(s,o){if(os.isUndefined(o)){if(!os.isUndefined(s))return i(void 0,s)}else return i(void 0,o)}function l(s,o,c){if(c in t)return i(s,o);if(c 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:l,headers:(s,o,c)=>n(ZBp(s),ZBp(o),c,!0)};return os.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=d[o]||n,b=c(e[o],t[o],o);os.isUndefined(b)&&c!==l||(r[o]=b)}),r}var v3o=e=>{let t=nWt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=rR.from(u),t.url=LHi(UHi(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),l&&u.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):"")));let d;if(os.isFormData(r)){if(aA.hasStandardBrowserEnv||aA.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((d=u.getContentType())!==!1){let[s,...o]=d?d.split(";").map(c=>c.trim()).filter(Boolean):[];u.setContentType([s||"multipart/form-data",...o].join("; "))}}if(aA.hasStandardBrowserEnv&&(i&&os.isFunction(i)&&(i=i(t)),i||i!==!1&&YBp(t.url))){let s=n&&a&&XBp.read(a);s&&u.set(n,s)}return t};var KbD=typeof XMLHttpRequest<"u",kBp=KbD&&function(e){return new Promise(function(r,i){let n=v3o(e),a=n.data,u=rR.from(n.headers).normalize(),{responseType:l,onUploadProgress:d,onDownloadProgress:s}=n,o,c,b,g,O;function m(){g&&g(),O&&O(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let w=new XMLHttpRequest;w.open(n.method.toUpperCase(),n.url,!0),w.timeout=n.timeout;function E(){if(!w)return;let A=rR.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),C={data:!l||l==="text"||l==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:A,config:e,request:w};Ltr(function($){r($),m()},function($){i($),m()},C),w=null}"onloadend"in w?w.onloadend=E:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(E)},w.onabort=function(){w&&(i(new Fp("Request aborted",Fp.ECONNABORTED,e,w)),w=null)},w.onerror=function(){i(new Fp("Network Error",Fp.ERR_NETWORK,e,w)),w=null},w.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",C=n.transitional||yFn;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new Fp(D,C.clarifyTimeoutError?Fp.ETIMEDOUT:Fp.ECONNABORTED,e,w)),w=null},a===void 0&&u.setContentType(null),"setRequestHeader"in w&&os.forEach(u.toJSON(),function(D,C){w.setRequestHeader(C,D)}),os.isUndefined(n.withCredentials)||(w.withCredentials=!!n.withCredentials),l&&l!=="json"&&(w.responseType=n.responseType),s&&([b,O]=nfi(s,!0),w.addEventListener("progress",b)),d&&w.upload&&([c,g]=nfi(d),w.upload.addEventListener("progress",c),w.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=A=>{w&&(i(!A||A.type?new REe(null,e,w):A),w.abort(),w=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let q=nEa(n.url);if(q&&aA.protocols.indexOf(q)===-1){i(new Fp("Unsupported protocol "+q+":",Fp.ERR_BAD_REQUEST,e));return}w.send(a||null)})};var YbD=(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,l();let o=s instanceof Error?s:this.reason;i.abort(o instanceof Fp?o:new REe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new Fp(`timeout ${t} of ms exceeded`,Fp.ETIMEDOUT))},t),l=()=>{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=()=>os.asap(l),d}},eIp=YbD;var XbD=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},ZbD=async function*(e,t){for await(let r of kbD(e))yield*XbD(r,t)},kbD=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()}},XKs=(e,t,r,i)=>{let n=ZbD(e,t),a=0,u,l=d=>{u||(u=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:o}=await n.next();if(s){l(),d.close();return}let c=o.byteLength;if(r){let b=a+=c;r(b)}d.enqueue(new Uint8Array(o))}catch(s){throw l(s),s}},cancel(d){return l(d),n.return()}},{highWaterMark:2})};var g3o=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",rIp=g3o&&typeof ReadableStream=="function",e0D=g3o&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),iIp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},t0D=rIp&&iIp(()=>{let e=!1,t=new Request(aA.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),tIp=64*1024,ZKs=rIp&&iIp(()=>os.isReadableStream(new Response("").body)),b3o={stream:ZKs&&(e=>e.body)};g3o&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!b3o[t]&&(b3o[t]=os.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new Fp(`Response type '${t}' is not supported`,Fp.ERR_NOT_SUPPORT,i)})})})(new Response);var r0D=async e=>{if(e==null)return 0;if(os.isBlob(e))return e.size;if(os.isSpecCompliantForm(e))return(await new Request(aA.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(os.isArrayBufferView(e)||os.isArrayBuffer(e))return e.byteLength;if(os.isURLSearchParams(e)&&(e=e+""),os.isString(e))return(await e0D(e)).byteLength},i0D=async(e,t)=>{let r=os.toFiniteNumber(e.getContentLength());return r??r0D(t)},nIp=g3o&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:a,timeout:u,onDownloadProgress:l,onUploadProgress:d,responseType:s,headers:o,withCredentials:c="same-origin",fetchOptions:b}=v3o(e);s=s?(s+"").toLowerCase():"text";let g=eIp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),w;try{if(d&&t0D&&r!=="get"&&r!=="head"&&(w=await i0D(o,i))!==0){let C=new Request(t,{method:"POST",body:i,duplex:"half"}),x;if(os.isFormData(i)&&(x=C.headers.get("content-type"))&&o.setContentType(x),C.body){let[$,I]=gFn(w,nfi(OFn(d)));i=XKs(C.body,tIp,$,I)}}os.isString(c)||(c=c?"include":"omit");let E="credentials"in Request.prototype;O=new Request(t,{...b,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:E?c:void 0});let q=await fetch(O,b),A=ZKs&&(s==="stream"||s==="response");if(ZKs&&(l||A&&m)){let C={};["status","statusText","headers"].forEach(F=>{C[F]=q[F]});let x=os.toFiniteNumber(q.headers.get("content-length")),[$,I]=l&&gFn(x,nfi(OFn(l),!0))||[];q=new Response(XKs(q.body,tIp,$,()=>{I&&I(),m&&m()}),C)}s=s||"text";let D=await b3o[os.findKey(b3o,s)||"text"](q,e);return!A&&m&&m(),await new Promise((C,x)=>{Ltr(C,x,{data:D,headers:rR.from(q.headers),status:q.status,statusText:q.statusText,config:e,request:O})})}catch(E){throw m&&m(),E&&E.name==="TypeError"&&/Load failed|fetch/i.test(E.message)?Object.assign(new Fp("Network Error",Fp.ERR_NETWORK,e,O),{cause:E.cause||E}):Fp.from(E,E&&E.code,e,O)}});var kKs={http:KBp,xhr:kBp,fetch:nIp};os.forEach(kKs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var aIp=e=>`- ${e}`,n0D=e=>os.isFunction(e)||e===null||e===!1,O3o={getAdapter:e=>{e=os.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,!n0D(r)&&(i=kKs[(u=String(r)).toLowerCase()],i===void 0))throw new Fp(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([l,d])=>`adapter ${l} `+(d===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
|
|
@@ -1913,7 +1913,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
|
|
|
1913
1913
|
For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.`)}}return n.executablePath}};pTa=new WeakMap;var z9o=class extends R6n{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
|
|
1914
1914
|
`].join(`
|
|
1915
1915
|
`)),super.launch(t)}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],pipe:n=!1,debuggingPort:a,channel:u,executablePath:l}=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?(Yc(!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,e$p.mkdtemp)(this.getProfilePath())}`),o=d.length-1);let c=d[o].split("=",2)[1];Yc(typeof c=="string","`--user-data-dir` is malformed");let b=l;return b||(Yc(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:c}}async cleanUserDataDir(t,r){if(r.isTemp)try{await s6n(t)}catch(i){throw B0(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=${t$p.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(l=>l.startsWith("-"))&&r.push("about:blank"),r.push(...a),r}executablePath(t){return t?N5o({browser:HA.CHROME,channel:Q4D(t)}):this.resolveExecutablePath()}};function Q4D(e){switch(e){case"chrome":return y3.STABLE;case"chrome-dev":return y3.DEV;case"chrome-beta":return y3.BETA;case"chrome-canary":return y3.CANARY}}var pac=ui(require("fs"),1),MGi=require("fs/promises"),r$p=ui(require("os"),1),x9o=ui(require("path"),1);dC();oA();var R9o=class extends R6n{constructor(t){super(t,"firefox")}async computeLaunchArguments(t={}){let{ignoreDefaultArgs:r=!1,args:i=[],executablePath:n,pipe:a=!1,extraPrefsFirefox:u={},debuggingPort:l=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&&Yc(l===null,"Browser should be launched with either pipe or debugging port - not both."),d.push(`--remote-debugging-port=${l||0}`));let s,o=!0,c=d.findIndex(g=>["-profile","--profile"].includes(g));if(c!==-1){if(s=d[c+1],!s||!pac.default.existsSync(s))throw new Error(`Firefox profile not found at '${s}'`);o=!1}else s=await(0,MGi.mkdtemp)(this.getProfilePath()),d.push("--profile"),d.push(s);await Fic(HA.FIREFOX,{path:s,preferences:u});let b;return this.puppeteer._isPuppeteerCore||n?(Yc(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 s6n(t)}catch(i){throw B0(i),i}else try{await(0,MGi.unlink)(x9o.default.join(t,"user.js"));let i=x9o.default.join(t,"prefs.js.puppeteer");if(pac.default.existsSync(i)){let n=x9o.default.join(t,"prefs.js");await(0,MGi.unlink)(n),await(0,MGi.rename)(i,n)}}catch(i){B0(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(r$p.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(l=>l.startsWith("-"))&&u.push("about:blank"),u.push(...n),u}};var i$p=require("path");var hTa=Object.freeze({chromium:"1108766",firefox:"latest"});var _ac=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},BWt=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)},N6n,Hfi,vTa,yTa,F6n=class extends _qa{constructor(t){let{configuration:r,...i}=t;switch(super(i),N6n.add(this),Hfi.set(this,void 0),vTa.set(this,void 0),this.configuration={},r&&(this.configuration=r),this.configuration.defaultProduct){case"firefox":this.defaultBrowserRevision=hTa.firefox;break;default:this.configuration.defaultProduct="chrome",this.defaultBrowserRevision=hTa.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 _ac(this,vTa,r,"f"),BWt(this,N6n,"a",yTa).launch(t)}executablePath(t){return BWt(this,N6n,"a",yTa).executablePath(t)}get browserRevision(){var t,r,i;return(i=(r=(t=BWt(this,Hfi,"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,i$p.join)(this.configuration.cacheDirectory,this.product)}get lastLaunchedProduct(){var t;return(t=BWt(this,vTa,"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 BWt(this,N6n,"a",yTa).product}defaultArgs(t={}){return BWt(this,N6n,"a",yTa).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 E5o(t)}};Hfi=new WeakMap,vTa=new WeakMap,N6n=new WeakSet,yTa=function(){if(BWt(this,Hfi,"f")&&BWt(this,Hfi,"f").product===this.lastLaunchedProduct)return BWt(this,Hfi,"f");switch(this.lastLaunchedProduct){case"chrome":this.defaultBrowserRevision=hTa.chromium,_ac(this,Hfi,new z9o(this),"f");break;case"firefox":this.defaultBrowserRevision=hTa.firefox,_ac(this,Hfi,new R9o(this),"f");break;default:throw new Error(`Unknown product: ${BWt(this,vTa,"f")}`)}return BWt(this,Hfi,"f")};_tc();TMa();var J4D=new F6n({isPuppeteerCore:!0}),{connect:Gd8,createBrowserFetcher:Qd8,defaultArgs:Jd8,executablePath:Kd8,launch:Yd8}=J4D;var CQp=require("os"),BQp=require("path"),IQp=ui(TQp(),1);function O9D(e){switch(e){case"chrome":case"firefox":return!0;default:return!1}}var zQp=()=>{var e,t,r,i,n,a,u,l,d,s,o,c,b,g,O,m,w,E,q,A,D,C,x,$,I,F,V,K,Y,Z,oe,pe,de,Oe,Ue,wt,De;let Te=(0,IQp.cosmiconfigSync)("puppeteer").search(),xt=Te?Te.config:{};if(xt.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:xt.defaultProduct)!==null&&i!==void 0?i:"chrome",xt.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:xt.executablePath,xt.executablePath&&(xt.skipDownload=!0),xt.skipDownload=!!((b=(c=(o=(s=(d=(l=process.env.PUPPETEER_SKIP_DOWNLOAD)!==null&&l!==void 0?l: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&&c!==void 0?c:process.env.npm_package_config_puppeteer_skip_chromium_download)!==null&&b!==void 0?b:xt.skipDownload),xt.skipDownload||(xt.browserRevision=(w=(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&&w!==void 0?w:xt.browserRevision,xt.downloadHost=(A=(q=(E=process.env.PUPPETEER_DOWNLOAD_HOST)!==null&&E!==void 0?E:process.env.npm_config_puppeteer_download_host)!==null&&q!==void 0?q:process.env.npm_package_config_puppeteer_download_host)!==null&&A!==void 0?A:xt.downloadHost,xt.downloadPath=(x=(C=(D=process.env.PUPPETEER_DOWNLOAD_PATH)!==null&&D!==void 0?D:process.env.npm_config_puppeteer_download_path)!==null&&C!==void 0?C:process.env.npm_package_config_puppeteer_download_path)!==null&&x!==void 0?x:xt.downloadPath),xt.cacheDirectory=(V=(F=(I=($=process.env.PUPPETEER_CACHE_DIR)!==null&&$!==void 0?$:process.env.npm_config_puppeteer_cache_dir)!==null&&I!==void 0?I:process.env.npm_package_config_puppeteer_cache_dir)!==null&&F!==void 0?F:xt.cacheDirectory)!==null&&V!==void 0?V:(0,BQp.join)((0,CQp.homedir)(),".cache","puppeteer"),xt.temporaryDirectory=(Z=(Y=(K=process.env.PUPPETEER_TMP_DIR)!==null&&K!==void 0?K:process.env.npm_config_puppeteer_tmp_dir)!==null&&Y!==void 0?Y:process.env.npm_package_config_puppeteer_tmp_dir)!==null&&Z!==void 0?Z:xt.temporaryDirectory,(oe=xt.experiments)!==null&&oe!==void 0||(xt.experiments={}),xt.experiments.macArmChromiumEnabled=!!((Oe=(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&&Oe!==void 0?Oe:xt.experiments.macArmChromiumEnabled),xt.logLevel=(De=(wt=(Ue=process.env.PUPPETEER_LOGLEVEL)!==null&&Ue!==void 0?Ue:process.env.npm_config_LOGLEVEL)!==null&&wt!==void 0?wt:process.env.npm_package_config_LOGLEVEL)!==null&&De!==void 0?De:xt.logLevel,!O9D(xt.defaultProduct))throw new Error(`Unsupported product ${xt.defaultProduct}`);return xt};var m9D=zQp(),P9D=new F6n({isPuppeteerCore:!1,configuration:m9D}),{connect:a_8,createBrowserFetcher:o_8,defaultArgs:u_8,executablePath:s_8,launch:xQp}=P9D;var j9D="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",w9D={"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 CTa(e,t=3,r=1e3,i=2){try{return await e()}catch(n){if(t>0)return await new Promise(a=>setTimeout(a,r)),CTa(e,t-1,r*i,i);throw n}}async function RQp(){try{return await xQp({headless:"new",ignoreHTTPSErrors:!0})}catch{throw new Error("Could not create a Puppeteer instance")}}async function S9D(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(w9D),await r.setUserAgent(j9D),await r.setJavaScriptEnabled(!0),await CTa(()=>r.goto(t.toString(),{waitUntil:"networkidle2",timeout:3e4}));let i=await CTa(()=>r.content());return await r.close(),i}catch{throw new Error("Failed to download page from Puppeteer")}}async function D9D(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 moc({url:e,browser:t}){try{let r;if(t?r=await S9D(t,e):r=await CTa(()=>D9D(e)),r)return r;throw new Error("An unknown error occurred.")}catch{throw new Error(`Error retrieving HTML for ${e.toString()}`)}}async function NQp(e){try{let t=await CTa(()=>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 E9D=["png","jpeg","jpg","webp","avif","svg","ico","jfif","pjpeg","pjp","svgz","bmp"];async function FQp(e){if(!e)return{success:!1,data:void 0};if(e.startsWith("data:image/"))return{success:!0,data:[e,e]};let t=(0,Q6n.join)(process.cwd(),"fern");try{let r=await M9D(e,(0,Q6n.join)(t,"images"));return r=r.replace(t,""),{success:!0,data:[e,r]}}catch{return{success:!1,data:void 0}}}async function M9D(e,t){let r=q9D(e),i=(0,Q6n.join)(t,r);if(!A9D(r))throw new Error(`${r} - file extension not supported`);if((0,oLo.existsSync)(i))return i;try{(0,oLo.mkdirSync)((0,Q6n.dirname)(i),{recursive:!0})}catch{throw new Error(`${i} - failed to create directory`)}try{let n=await NQp(e);return V2p(i,n),i}catch{throw new Error(`${i}: failed to download file from source`)}}function A9D(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&&!E9D.includes(i))}function q9D(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 T9D(e){let t=[];return Ff(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 LQp(e,t){let r=h3n(e),i=T9D(r);if(i!=null){let n=await Promise.all(i.map(async a=>{let u=await FQp(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 UQp=28;async function VQp(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 LQp(a,r)))}let i=[...new Set(r).values()];if(i.length!==0){if(i.length===1&&i[0]!=null){let n=Na.of(GG(i[0]));return{light:n,dark:n,height:UQp}}if(i[0]!=null&&i[1]!=null){let n=Na.of(GG(i[0])),a=Na.of(GG(i[1]));return{light:n,dark:a,height:UQp}}}}var uLo=class extends XHi{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:wEa});let i=await this.getHastForUrl(this.url),n=Z8p(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 c=await this.scrapeTab({name:o.name,url:o.url});if(!c)continue;let b=r.getNavigationBuilder({tabId:this.kebabCaseWithoutEmojis(o.name),tabConfig:{slug:o.url,displayName:o.name}}),g=Ru(this.absolutePathToFernDirectory,Na.of(this.kebabCaseWithoutEmojis(o.name)));await this.downloadMarkdownPages({absolutePathToOutputDirectory:g,sections:c});let O=await this.getNavigationItems({absolutePathToOutputDirectory:g,sections:c});for(let m of O)b.addItem({item:m})}let a=await RQp(),u=await VQp(this.url,a);u!=null&&r.setLogo({logo:u});let l=await P3p(i);r.setTitle({title:l});let d=await b3p(i);if(d!=null){let o=await this.getAndCreateAssetsDirectory(),c=await fetch(d);if(c.ok){let b=Buffer.from(await c.arrayBuffer()),g=Ru(o,Na.of("favicon"));await(0,uEi.writeFile)(g,new Uint8Array(b)),r.setFavicon({favicon:Cie(this.absolutePathToFernDirectory,g)})}}let s=await e5p(i);r.setColors({colors:s}),a&&await a.close(),r.build({outputDirectory:this.absolutePathToFernDirectory})}async getAndCreateAssetsDirectory(){let t=Ru(this.absolutePathToFernDirectory,Na.of("assets"));return await(0,uEi.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=K8p(n);if(!a){this.logger.debug(`No sidebar element found for tab: ${t} (${r})`);return}let u=Y8p(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 moc({url:t});return h3n(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,uEi.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 l=await moc({url:u}),d=await J8p({logger:this.logger,html:l,url:u});if(d.success&&d.data){let s=this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:n,page:a.slug});await(0,uEi.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,c])=>{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=Ru(n,Na.of(c)),m=Cd(O);await(0,uEi.mkdir)(m,{recursive:!0}),await(0,uEi.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 l of n.pages)if(l.type==="page")u.contents.push({page:l.page,path:Cie(this.absolutePathToFernDirectory,this.getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:a,page:l.slug}))});else{let d=await this.getNavigationItems({absolutePathToOutputDirectory:a,sections:[l]});u.contents.push(...d)}i.push(u)}return i}getAbsolutePathToOutputFileForPage({absolutePathToOutputDirectoryForSection:t,page:r}){return Ru(t,Na.of(`${this.kebabCaseWithoutEmojis(r.split("/").pop()||r)}.mdx`))}getAbsolutePathToOutputDirectoryForSection({absolutePathToOutputDirectory:t,section:r}){return Ru(t,Na.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 WQp=require("fs/promises");async function Poc({readmeUrl:e,outputPath:t,taskContext:r,versionOfCli:i,organization:n}){let a=new ZHi;a.setInstance({companyName:n}),await new uLo({url:e,context:r,builder:a,absolutePathToFernDirectory:Ru(ll.of(process.cwd()),Na.of("fern"))}).import({args:{},builder:a}),await a.build({outputDirectory:t}),await(0,WQp.writeFile)(Ru(ll.of(t),Na.of(HV),Na.of(Mie)),JSON.stringify({version:i,organization:n},void 0,4))}var joc=async({readmeUrl:e,organization:t,taskContext:r,versionOfCli:i})=>{if(!e||!UUi(e)){r.failAndThrow("Provide a URL to a readme-generated site");return}let n=ll.of(Xz());await Poc({readmeUrl:e,outputPath:n,taskContext:r,versionOfCli:i,organization:t})};var HQp="0.0.0";var $Qp={[gy.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,VC(e)])),[gy.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"]),[gy.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"]),[gy.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"]),[gy.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","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[gy.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"]),[gy.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"]),[gy.GenerationLanguage.SWIFT]:new Set([])};var B9D=["go","ruby"];function BZ({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:I9D({name:c,keywords:z9D({generationLanguage:e,keywords:t})})}),l=d_(n),d=VC(l),s=aUi(n),o=tUi(l);return r&&(!N9D(o)&&(e==null||B9D.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=sLo(c);if(g!=null)return g;if(cLo(c))return c.toUpperCase()}return c}).join(""),d=VC(o.map((c,b)=>{let g=sLo(c);return g??(cLo(c)?c.toUpperCase():b===0?VC(c):c)}).join(""))),s=n.split(" ").map(c=>c.split(/(\d+)/).map(aUi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),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 I9D({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":R9D(e)?"_"+e:e}function z9D({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return $Qp[e]}var x9D=/^[0-9]/;function R9D(e){return x9D.test(e)}function N9D(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=sLo(i)!=null||cLo(i),a=sLo(t)!=null||cLo(t);return n&&a})}function sLo(e){return L9D.get(e.toUpperCase())}function cLo(e){return F9D.has(e.toUpperCase())}var F9D=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"]),L9D=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);function JN(e){let t=V9D(e),{value:r,done:i}=woc(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...U9D(t)]}}function*U9D(e){let t;do{let{value:r}=woc(e,"}"),i=woc(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*V9D(e){for(let t of e)yield t}function woc(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 BTa(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((l,d)=>{d>0&&i(","),i(l),i(":"),r(n[l],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 Drr({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 GQp({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return Err({containerType:t});switch(t.type){case"list":{let u=Nq({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?Err({containerType:t}):{type:"success",example:mm.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:mm.literal({literal:t.literal._visit({boolean:u=>Fd.boolean(u),string:u=>Fd.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 Err({containerType:t});let u=Nq({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?Err({containerType:t}):{type:"success",example:mm.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return Err({containerType:t});let u=Nq({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?Err({containerType:t}):{type:"success",example:mm.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=Nq({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?Err({containerType:t}):{type:"success",example:mm.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=Nq({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=Nq({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?Err({containerType:t}):{type:"success",example:mm.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:jo(t)}}function Err({containerType:e}){switch(e.type){case"list":return{type:"success",example:mm.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:mm.literal({literal:e.literal._visit({boolean:t=>Fd.boolean(t),string:t=>Fd.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:mm.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:mm.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:mm.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:mm.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:jo(e)}}function JQp({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return Q9D({fieldName:e,default_:W9D(t.v2),validation:H9D(t.v2)});case"BASE_64":return{type:"success",example:Fd.base64(ky.BASE64),jsonExample:ky.BASE64};case"BOOLEAN":return{type:"success",example:Fd.boolean(ky.BOOLEAN),jsonExample:ky.BOOLEAN};case"DATE":return{type:"success",example:Fd.date(ky.DATE),jsonExample:ky.DATE};case"DATE_TIME":return{type:"success",example:Fd.datetime({datetime:new Date(ky.DATE_TIME),raw:ky.DATE_TIME}),jsonExample:ky.DATE_TIME};case"DOUBLE":return J9D({fieldName:e,validation:$9D(t.v2)});case"FLOAT":return{type:"success",example:Fd.float(ky.FLOAT),jsonExample:ky.FLOAT};case"INTEGER":return K9D({fieldName:e,validation:G9D(t.v2)});case"UINT_64":return{type:"success",example:Fd.uint64(ky.INT64),jsonExample:ky.INT64};case"UINT":return{type:"success",example:Fd.uint(ky.UINT),jsonExample:ky.UINT};case"BIG_INTEGER":return{type:"success",example:Fd.bigInteger(ky.INT64.toString()),jsonExample:`${ky.INT64}`};case"LONG":return{type:"success",example:Fd.long(ky.INT64),jsonExample:ky.INT64};case"UUID":return{type:"success",example:Fd.uuid(ky.UUID),jsonExample:ky.UUID};default:jo(t.v1)}}function W9D(e){if(e?.type==="string")return e.default}function H9D(e){if(e?.type==="string")return e.validation}function $9D(e){if(e?.type==="double")return e.validation}function G9D(e){if(e?.type==="integer")return e.validation}function QQp(e){if(e<=ky.SAMPLE_STRINGS.length){let t=ky.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return ky.SAMPLE_STRINGS[ky.SAMPLE_STRINGS.length-1]+".".repeat(e-ky.SAMPLE_STRINGS.length)}function Q9D({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Fd.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=QQp(n);return{type:"success",example:Fd.string({original:u}),jsonExample:u}}else if(a){let u=QQp(a);return{type:"success",example:Fd.string({original:u}),jsonExample:u}}}let i=e??ky.STRING;return{type:"success",example:Fd.string({original:i}),jsonExample:i}}function J9D({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Fd.double(r),jsonExample:r};if(i)return{type:"success",example:Fd.double(i),jsonExample:i}}return{type:"success",example:Fd.double(ky.DOUBLE),jsonExample:ky.DOUBLE}}function K9D({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Fd.integer(r),jsonExample:r};if(i)return{type:"success",example:Fd.integer(i),jsonExample:i}}return{type:"success",example:Fd.integer(ky.INT),jsonExample:ky.INT}}function J6n({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=Nq({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:l,jsonExample:d}=u;return{type:"success",example:Rw.alias({value:l}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:Rw.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},l=[];if((r.shape.extendedProperties==null||r.shape.extendedProperties.length===0)&&r.shape.extends!=null)for(let c of r.shape.extends){let b=t[c.typeId];if(b==null)continue;let g=J6n({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),l.push(...g.example.properties))}let d=Y9D({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:Rw.object({properties:[...l,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let d=Nq({fieldName:e,typeReference:l.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:Rw.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,l={};if(r.shape.baseProperties!=null)for(let d of r.shape.baseProperties){let s=Nq({fieldName:d.name.wireValue,typeReference:d.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(l[d.name.wireValue]=s.jsonExample)}for(let d of r.shape.types){let s=d.shape._visit({noProperties:()=>({type:"success",example:Rw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:r3.noProperties()}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...l}}),samePropertiesAsObject:o=>{let c=t[o.typeId];if(c==null)return{type:"failure",message:`Failed to find type declaration with id ${o.typeId}`};let b=J6n({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:c,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:Rw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:r3.samePropertiesAsObject({typeId:c.name.typeId,object:g.type==="object"?g:{properties:[]}})}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...typeof O=="object"?O:{},...l}}},singleProperty:o=>{let c=Nq({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(c.type==="failure")return c;let{example:b,jsonExample:g}=c;return{type:"success",example:Rw.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:r3.singleProperty(b)}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,[o.name.wireValue]:g,...l}}},_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 Y9D({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let l={},d=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=Nq({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!Drr({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:c,jsonExample:b}=o;d.push({name:s.name,originalTypeDeclaration:t.name,value:c}),l[s.name.wireValue]=b}return{type:"success",example:Rw.object({properties:d}),jsonExample:l}}function Nq({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 l=J6n({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(l==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(l.type==="failure")return l;let{example:d,jsonExample:s}=l;return{type:"success",example:{jsonExample:s,shape:Vh.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=GQp({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=Err({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:Vh.container(s)},jsonExample:o}}let{example:l,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:Vh.container(l)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:l}=JQp({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:Vh.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:Vh.unknown(u)},jsonExample:u}}}}function zGi(e,t){let r=[];for(let i of e){let n=Nq({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 K6n(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Drr({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=Nq({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 lLo(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&Drr({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=Nq({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?A2.exploded():A2.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var Soc=Kc.primitive({v1:Uh.String,v2:Ed.string({default:void 0,validation:void 0})});function ITa({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:IT.ok(YC.body(void 0)),docs:void 0},l=zGi(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointPathParameters=l.example;let d=zGi(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;u.servicePathParameters=d.example;let s=zGi(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=lLo(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let c=K6n(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointHeaders=c.example;let b=K6n(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 w=i[m.typeId];if(w==null)throw new Error(`Failed to find extended type declaration with id ${m.typeId}`);let E=J6n({typeDeclaration:w,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});E!=null&&E.type==="success"&&Object.assign(g,E.jsonExample)}for(let m of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let w=Nq({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(w.type==="failure"&&!Drr({typeDeclarations:i,typeReference:m.valueType}))return{type:"failure",message:`Failed to generate required property ${m.name.wireValue} b/c ${w.message}`};if(w.type==="failure")continue;let{example:E,jsonExample:q}=w;O.push({name:m.name,originalTypeDeclaration:void 0,value:E}),g[m.name.wireValue]=q}u.request=yQ.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=Nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=yQ.reference(O);break}default:jo(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=Nq({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=IT.ok(YC.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=Nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=Nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Soc,skipOptionalProperties:!1});break;default:jo(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=IT.ok(YC.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=Nq({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=IT.ok(YC.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=Nq({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=IT.ok(YC.stream([{...O,jsonExample:m}]));break}case"text":{if(g=Nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Soc,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=IT.ok(YC.stream([{...O,jsonExample:m}]));break}default:jo(t.response.body.value)}break}case"text":{let g=Nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:Soc,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=IT.ok(YC.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:jo(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=IT.error({body:void 0,error:a.declaration.name});else{let g=Nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=IT.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:BTa(u),url:X9D(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function X9D(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 Doc({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=zGi(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=zGi(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let l=lLo(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(l.type==="failure")return l;n.queryParameters=l.example;let d=K6n(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=K6n(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let c=t.messages.filter(O=>O.origin==="client")[0];if(c!=null){let O=KQp({message:c,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:c.type,body:O})}let g=t.messages.filter(O=>O.origin==="server")[0];if(g!=null){let O=KQp({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:Z9D(t,n)},jsonExample:void 0}}function KQp({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=Nq({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return DEe.reference(i.example)}function Z9D(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 Y6n(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{},i=Object.values(t)[0],n=Object.values(r)[0];return{userExample:i,autoExample:n}}function sEi(e){let t=e?.userSpecifiedExamples??{},r=e?.autogeneratedExamples??{};return{userExamples:t,autoExamples:r}}function YQp({ir:e,endpoint:t,skipOptionalRequestProperties:r}){let i=e.types,n={pathParameters:{},queryParameters:{},headers:{}};for(let u of t.pathParameters){let{userExample:l,autoExample:d}=Y6n(u.v2Examples);l!==void 0?n.pathParameters[u.name.originalName]=l:d!==void 0&&(n.pathParameters[u.name.originalName]=d)}for(let u of t.queryParameters){let{userExample:l,autoExample:d}=Y6n(u.v2Examples);if(l!==void 0)n.queryParameters[u.name.name.originalName]=l;else if(d!==void 0){if(r&&Drr({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:l,autoExample:d}=Y6n(u.v2Examples);if(l!==void 0)n.headers[u.name.wireValue]=l;else if(d!==void 0){if(r&&Drr({typeReference:u.valueType,typeDeclarations:i}))continue;n.headers[u.name.wireValue]=d}}return n}function XQp({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let{pathParameters:i,queryParameters:n,headers:a}=YQp({endpoint:e,ir:t,skipOptionalRequestProperties:r}),u={},l={},d={endpoint:{method:e.method,path:k9D(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}=sEi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}case"inlinedRequestBody":{let{userExamples:s,autoExamples:o}=sEi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}case"reference":{let{userExamples:s,autoExamples:o}=sEi(e.requestBody.v2Examples);for(let[c,b]of Object.entries(s))u[c]={...d,requestBody:b};for(let[c,b]of Object.entries(o))l[c]={...d,requestBody:b};break}default:jo(e.requestBody)}return{userRequestExamples:u,autoRequestExamples:l,baseExample:d}}function k9D(e){let t={};[...e.pathParameters,...e.allPathParameters].forEach(i=>{let{userExample:n,autoExample:a}=Y6n(i.v2Examples),u=n??a,l;u==null?l=i.name.originalName:l=typeof u=="string"?u:JSON.stringify(u),t[i.name.originalName]=l});let r=e.fullPath.head+e.fullPath.parts.map(i=>encodeURIComponent(`${t[i.pathParameter]}`)+i.tail).join("");return r.startsWith("/")||r===""?r:`/${r}`}function ZQp({endpoint:e}){let t={},r={},i={statusCode:e.response?.statusCode,body:void 0,docs:void 0};if(e.response==null)return{userResponseExamples:{},autoResponseExamples:{},baseExample:i};if(e.response.body==null)return e.source?.type==="openrpc"?{userResponseExamples:{},autoResponseExamples:{},baseExample:{...i,body:m9.json(zTa(null))}}:{userResponseExamples:{},autoResponseExamples:{},baseExample:i};switch(e.response.body.type){case"bytes":break;case"fileDownload":break;case"text":{let n=e.response.body,{userExamples:a,autoExamples:u}=sEi(n.v2Examples);for(let[l,d]of Object.entries(a)){let s=e.source?.type==="openrpc"?zTa(d):d;t[l]={...i,body:m9.json(s)}}for(let[l,d]of Object.entries(u)){let s=e.source?.type==="openrpc"?zTa(d):d;r[l]={...i,body:m9.json(s)}}break}case"json":{let n=e.response.body.value;if(n.type==="response"){let{userExamples:a,autoExamples:u}=sEi(n.v2Examples);for(let[l,d]of Object.entries(a)){let s=e.source?.type==="openrpc"?zTa(d):d;t[l]={...i,body:m9.json(s)}}for(let[l,d]of Object.entries(u)){let s=e.source?.type==="openrpc"?zTa(d):d;r[l]={...i,body:m9.json(s)}}}break}case"streaming":{let n=e.response.body.value;if(n.type==="json"){let{userExamples:a,autoExamples:u}=sEi(n.v2Examples);for(let[l,d]of Object.entries(a))t[l]={...i,body:m9.stream([d])};for(let[l,d]of Object.entries(u))r[l]={...i,body:m9.stream([d])}}break}case"streamParameter":break;default:jo(e.response.body)}return{userResponseExamples:t,autoResponseExamples:r,baseExample:i}}function zTa(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}function kQp({endpoint:e,ir:t,skipOptionalRequestProperties:r}){let i={},n={},{userRequestExamples:a,autoRequestExamples:u,baseExample:l}=XQp({endpoint:e,ir:t,skipOptionalRequestProperties:r}),{userResponseExamples:d,autoResponseExamples:s,baseExample:o}=ZQp({endpoint:e}),c=Object.keys(u)[0],b=Object.values(u)[0],g=Object.values(s)[0];for(let[O,m]of Object.entries(a))i[O]={request:m,response:d[O]??g??o,codeSamples:void 0};for(let[O,m]of Object.entries(d))i[O]={request:a[O]??b??l,response:m,codeSamples:void 0};return Object.keys(i).length===0&&(n[c??d_(`${e.name.originalName}_example`)]={request:b??l,response:g??o,codeSamples:void 0}),{userFullExamples:i,autoFullExamples:n}}function xTa({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){if(n.userSpecifiedExamples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let a=ITa({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});if(a.type==="failure")continue;let{example:u}=a;n.autogeneratedExamples=[{example:u}]}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=Doc({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function Eoc({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){n.v2Examples==null&&(n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}});let{userFullExamples:a,autoFullExamples:u}=kQp({endpoint:n,ir:e,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(Object.keys(n.v2Examples.userSpecifiedExamples).length>0){if(Object.values(n.v2Examples.userSpecifiedExamples).some(d=>d.request!=null||d.response!=null))continue;let l=Object.values(n.v2Examples.userSpecifiedExamples).filter(d=>d!=null).flatMap(d=>d.codeSamples??[]);for(let[d,s]of Object.entries(u))u[d]={...s,codeSamples:l};for(let[d,s]of Object.entries(a))a[d]={...s,codeSamples:l}}n.v2Examples.autogeneratedExamples=u,n.v2Examples.userSpecifiedExamples=a}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=Doc({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function xGi(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=tLD(e.environments,t.environments,r),{services:u,websocketChannels:l}=rLD(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:eLD(e.subpackages,t.subpackages),websocketChannels:l,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 eLD(e,t){let r=e;for(let[i,n]of Object.entries(t))r[i]==null?r[i]=n:r[i]={name:n.name,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 tLD(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=eJp(e),n=eJp(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:ex.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,u=e.environments,l=t.environments;if(u.type==="singleBaseUrl"&&l.type==="singleBaseUrl"){let d=i?l:u,s=i?u:l,o={},{deconflictedEnvironments2:c,changedBaseUrlIds2:b}=iLD(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:ex.multipleBaseUrls({baseUrls:[{id:g,name:O},...c.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(c.environments.map(w=>[w.id,w.url]))},docs:void 0}))})},changedBaseUrlIds1:i?b:o,changedBaseUrlIds2:i?o:b}}if(u.type==="multipleBaseUrls"&&l.type==="singleBaseUrl"||u.type==="singleBaseUrl"&&l.type==="multipleBaseUrls"){let d=u.type==="singleBaseUrl"?u:l,s=u.type==="multipleBaseUrls"?u:l,{deconflictedEnvironments1:o,changedBaseUrlIds1:c}=nLD(d,s,r);return{environments:{defaultEnvironment:a,environments:ex.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"?c:void 0,changedBaseUrlIds2:u.type==="singleBaseUrl"?void 0:c}}if(u.type==="multipleBaseUrls"&&l.type==="multipleBaseUrls"){let{deconflictedEnvironments:d,changedBaseUrlIds:s}=aLD(u,l,r);return{environments:{defaultEnvironment:a,environments:ex.multipleBaseUrls({baseUrls:[...u.baseUrls,...d.baseUrls],environments:u.environments.flatMap(o=>d.environments.map(c=>({...o,urls:{...o.urls,...c.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function rLD(e,t,r,i){if(r!=null)for(let[u,l]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=l),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?l:o));for(let d of Object.values(e.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}if(i!=null)for(let[u,l]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=l),s.v2BaseUrls?.includes(u)&&(s.v2BaseUrls=s.v2BaseUrls.map(o=>o===u?l:o));for(let d of Object.values(t.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}let n=e.services;for(let[u,l]of Object.entries(t.services))n[u]==null?n[u]=l:n[u]={availability:l.availability,name:l.name,displayName:l.displayName,basePath:l.basePath,endpoints:[...n[u].endpoints??[],...l.endpoints],pathParameters:[...n[u].pathParameters??[],...l.pathParameters??[]],headers:[...n[u].headers??[],...l.headers??[]],encoding:l.encoding,transport:l.transport,audiences:[...n[u].audiences??[],...l.audiences??[]]};let a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function iLD(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])),l=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=Moc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:ex.singleBaseUrl({environments:l}),changedBaseUrlIds2:i}}function nLD(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=Moc(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:ex.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function aLD(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=Moc(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s}),l=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([o,c])=>[i[o]??o,c]))}));return{deconflictedEnvironments:ex.multipleBaseUrls({baseUrls:u,environments:l}),changedBaseUrlIds:i}}function eJp(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 Moc(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}function qoc({rawApiFileSchema:e,casingsGenerator:t}){if(e.auth==null)return{docs:void 0,requirement:bne.All,schemes:[]};let r=typeof e.auth!="string"?e.auth.docs:void 0;return cWi(e.auth,{single:i=>{let n=tJp({reference:i,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t});return{docs:r,requirement:bne.All,schemes:[n]}},any:({any:i})=>({docs:r,requirement:bne.Any,schemes:i.map(n=>tJp({reference:n,authSchemeDeclarations:e["auth-schemes"],casingsGenerator:t}))})})}function tJp({reference:e,authSchemeDeclarations:t,casingsGenerator:r}){let i=(a,u)=>{let l=t?.[a];if(l==null)throw new Error("Unknown auth scheme: "+a);return d1a(l,{header:d=>BT.header({docs:u,name:r.generateNameAndWireValue({name:d.name??a,wireValue:d.header}),valueType:Kc.primitive({v1:Uh.String,v2:Ed.string({default:void 0,validation:void 0})}),prefix:d.prefix,headerEnvVar:d.env}),basic:d=>rJp({casingsGenerator:r,docs:u,rawScheme:d}),bearer:d=>Aoc({casingsGenerator:r,docs:u,rawScheme:d}),oauth:d=>Aoc({casingsGenerator:r,docs:u,rawScheme:void 0})})},n=typeof e=="string"?e:e.scheme;switch(n){case"bearer":case"oauth":return Aoc({casingsGenerator:r,docs:void 0,rawScheme:void 0});case"basic":return rJp({casingsGenerator:r,docs:void 0,rawScheme:void 0});default:return i(n,typeof e!="string"?e.docs:void 0)}}function Aoc({casingsGenerator:e,docs:t,rawScheme:r}){return BT.bearer({docs:t,token:e.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function rJp({casingsGenerator:e,docs:t,rawScheme:r}){return BT.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 RTa({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:fkt(i,{singleBaseUrl:()=>ex.singleBaseUrl(oLD({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>ex.multipleBaseUrls(uLD({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})},audiences:{...Object.fromEntries(Object.entries(t).map(([n,a])=>[n,fkt(a,{singleBaseUrl:u=>[...typeof u=="string"?[]:u.audiences??[]],multipleBaseUrls:u=>[...u.audiences??[]]})]))}}}function oLD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>fkt(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:iJp(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function uLD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>fkt(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:fd(a.urls,u=>iJp(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function iJp(e){return e.endsWith("/")?e.slice(0,-1):e}function tMe(e){return e.allParts.map(t=>t.originalName).join("/")}var jm={generateTypeId:e=>`type_${tMe(e.fernFilepath)}:${e.name.originalName}`,generateErrorId:e=>`error_${tMe(e.fernFilepath)}:${e.name.originalName}`,generateServiceId:e=>`service_${tMe(e.fernFilepath)}`,generateServiceIdFromFernFilepath:e=>`service_${tMe(e)}`,generateSubpackageId:e=>`subpackage_${tMe(e)}`,generateEndpointId:(e,t)=>{let r=tMe(e.fernFilepath),i=t.name.originalName;return`endpoint_${r}.${i}`},generateWebhookGroupId:e=>`webhooks_${tMe(e)}`,generateWebhookId:(e,t)=>`webhooks_${tMe(e)}.${t}`,generateWebSocketChannelId:e=>`channel_${tMe(e)}`};function X6n(e){return e.type!=null}var fLo=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:l,subpackages:d,queryParameters:s,requestProperties:o,webhookPayloadProperties:c,channels:b}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=l,this.webhookPayloadProperties=c,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=jm.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=jm.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=jm.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)}};function RGi(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}var NGi=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=sLD(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=jm.generateTypeId(t),l={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=l,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=jm.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=jm.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&cx(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=jm.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,d=new Set;for(let s of[...t.headers,...r.headers])cx(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])cx(s.valueType,u,d);for(let s of r.queryParameters)cx(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=RGi(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&tA._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)dLo(o,u,d);for(let o of s.properties)cx(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&JC(i.request.body)){let o=RGi(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{cx(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)w6._visit(o,{file:Go,bodyProperty:({valueType:c})=>{cx(c,u,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&xw._visit(r.response.body,{fileDownload:Go,json:s=>{cx(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>cx(o.payload,u,d),json:o=>cx(o.payload,u,d),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>cx(o.payload,u,d),json:o=>cx(o.payload,u,d),text:Go,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&cx(s.nonStreamResponse.value.responseBodyType,u,d)},text:Go,bytes:Go,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(jm.generateErrorId(s.error)),d.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:l,referencedSubpackages:d}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=jm.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(l=>{this.addSubpackages(l)})}),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&&fW._visit(r.payload,{inlinedPayload:l=>{for(let d of l.extends)dLo(d,a,u);for(let d of l.properties)cx(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!X6n(i.payload)){let d=RGi(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:l})=>{cx(l,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 l of i.messages)D9._visit(l.body,{reference:({bodyType:d})=>{cx(d,a,u)},inlinedBody:d=>{for(let s of d.extends)dLo(s,a,u);for(let s of d.properties)cx(s.valueType,a,u)},_other:()=>{}});for(let l of i.queryParameters)cx(l.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 l of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(l);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 l of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(l);this.addReferencedTypes(t,d.referencedTypes)}for(let l of this.channelsNeededForAudience.keys()){let d=this.getChannelNode(l);this.addReferencedTypes(t,d.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[l,d]of Object.entries(this.properties)){if(!t.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}s.size>0&&(i[l]=s),i[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}n[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.parametersByAudience[o];c?.forEach(b=>{s.add(b)})}a[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}u[l]=s.size>0?s:void 0}}return new fLo({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(l=>{t.add(l)});else{n.allDescendants.forEach(l=>{t.add(l)});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:jo(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(jm.generateSubpackageId(i))}}};function sLD(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:jo(e)}}function cx(e,t,r){Kc._visit(e,{container:i=>{cLD(i,t,r)},named:i=>{dLo(i,t,r)},primitive:Go,unknown:Go,_other:Go})}function dLo(e,t,r){t.add(jm.generateTypeId(e)),r.add(e.fernFilepath)}function cLD(e,t,r){Py._visit(e,{list:i=>{cx(i,t,r)},map:i=>{cx(i.keyType,t,r),cx(i.valueType,t,r)},optional:i=>{cx(i,t,r)},nullable:i=>{cx(i,t,r)},set:i=>{cx(i,t,r)},literal:Go,_other:Go})}var Toc=class{errors;constructor(){this.errors=[]}add(t){this.errors.push({message:t})}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}},NTa=class{errors;constructor(){this.errors=new Toc}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)){let a=r[i];if(!a){this.errors.add(`Type "${i}" was removed.`);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)){let a=r[i];if(!a){this.errors.add(`Service "${i}" was removed.`);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,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Endpoint "${u}" was removed.`);continue}this.checkEndpointBreakingChanges({id:u,from:l,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,l]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:l.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,l])=>[u,l.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,l])=>[u,l.valueType]))});for(let[u,l]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:l.valueType,to:d.valueType})||this.errors.add(`Query parameter "${u}" type changed in endpoint "${t}".`),l.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,l])=>[u,l.valueType])),to:Object.fromEntries(Object.entries(a).map(([u,l])=>[u,l.valueType]))});for(let[u,l]of Object.entries(n)){let d=a[u];if(!d){this.errors.add(`Header "${u}" was removed from ${t}.`);continue}this.areTypeReferencesCompatible({from:l.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:jo(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 l=n[a];return l?this.areTypeReferencesCompatible({from:u,to:l}):(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 l=n[a];if(!l)return this.errors.add(`File upload property "${a}" was removed.`),!1;if(u==="file"&&l!=="file")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u==="fileArray"&&l!=="fileArray")return this.errors.add(`File upload property "${a}" type changed.`),!1;if(u!=="file"&&u!=="fileArray"&&l!=="file"&&l!=="fileArray"&&!this.areTypeReferencesCompatible({from:u,to:l}))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:jo(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:jo(t)}return this.errors.add(`Streaming response type "${t.type}" is not compatible with type "${r.type}".`),!1}areTypeDeclarationsCompatible({from:t,to:r}){return 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:jo(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 l=Object.fromEntries(t.types.map(s=>[s.discriminantValue.wireValue,s])),d=Object.fromEntries(r.types.map(s=>[s.discriminantValue.wireValue,s]));return Object.values(l).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:jo(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:jo(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:jo(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:jo(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:jo(i)}return r}getKeyForDeclaration({name:t,fernFilepath:r}){return`${r.allParts.map(n=>n.camelCase.unsafeName).join(".")}.${t.pascalCase.unsafeName}`}};function aJp({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:sR({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?r3.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=sR({filteredIr:e,exampleTypeReference:r});return i!==void 0?r3.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function sR({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:Vh.container(mm.list({...i,list:i.list.map(n=>sR({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:Vh.container(mm.set({...i,set:i.set.map(n=>sR({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?sR({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:Vh.container(mm.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?sR({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:Vh.container(mm.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:Vh.container(mm.map({...i,map:i.map.map(n=>{let a=sR({filteredIr:e,exampleTypeReference:n.key}),u=sR({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=sR({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:Vh.named({...r,shape:Rw.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:Vh.named({...r,shape:Rw.enum(i)})}),object:i=>({...t,shape:Vh.named({...r,shape:Rw.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:sR({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=aJp({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:Vh.named({...r,shape:Rw.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=sR({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:Vh.named({...r,shape:Rw.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function Coc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=sR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function lLD({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=sR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function nJp({filteredIr:e,headers:t}){return t.map(r=>{let i=sR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function fLD({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=sR({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=sR({filteredIr:e,exampleTypeReference:r});return i!==void 0?yQ.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function dLD({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>IT.ok(YC.body(i!=null?sR({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>IT.ok(YC.stream(i.map(n=>sR({filteredIr:e,exampleTypeReference:n})).filter(yv))),sse:i=>IT.ok(YC.sse(i.map(({event:n,data:a})=>{let u=sR({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(yv))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>IT.error({error:r,body:i!=null?sR({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function Boc({filteredIr:e,example:t}){return{...t,rootPathParameters:Coc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:Coc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:Coc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:nJp({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:nJp({filteredIr:e,headers:t.endpointHeaders}),queryParameters:lLD({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?fLD({filteredIr:e,requestBody:t.request}):void 0,response:dLD({filteredIr:e,response:t.response})}}function oJp({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=sR({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:Rw.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:Rw.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:sR({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=aJp({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:Rw.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=sR({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:Rw.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function Ioc(e,t){if(t==null)return e;let r=nUi(e.types,l=>t.hasType(l)),i=Object.fromEntries(Object.entries(r).map(([l,d])=>{let s=[];if(d.userProvidedExamples=d.userProvidedExamples.map(o=>oJp({filteredIr:t,exampleType:o})).filter(o=>o!==void 0),d.shape.type==="object"){for(let o of d.shape.properties)t.hasProperty(l,o.name.wireValue)&&s.push(o);return[l,{...d,shape:Sb.object({...d.shape,properties:s})}]}return[l,d]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([l,d])=>{let s=d.filter(o=>t.hasWebhook(o)).map(o=>{let c=o.id;return o.payload.type==="inlinedPayload"&&c!=null&&(o.payload={...o.payload,properties:o.payload.properties.filter(b=>t.hasWebhookPayloadProperty(c,b.name.wireValue))}),o});return[l,s]})),a=e.websocketChannels!=null?Object.fromEntries(Object.entries(e.websocketChannels).filter(([l])=>t.hasChannel(l)).map(([l,d])=>[l,{...d}])):{},u=e.environments;if(u){switch(u.environments.type){case"singleBaseUrl":{u.environments.environments=u.environments.environments.filter(l=>t.hasEnvironmentId(l.id));break}case"multipleBaseUrls":{u.environments.environments=u.environments.environments.filter(l=>t.hasEnvironmentId(l.id));break}}u.defaultEnvironment&&(t.hasEnvironmentId(u.defaultEnvironment)||(u.defaultEnvironment=void 0))}return{...e,environments:u,types:i,errors:nUi(e.errors,l=>t.hasError(l)),services:fd(nUi(e.services,l=>t.hasService(l)),l=>({...l,endpoints:l.endpoints.filter(d=>t.hasEndpoint(d)).map(d=>(d.autogeneratedExamples=d.autogeneratedExamples.map(s=>({...s,example:Boc({filteredIr:t,example:s.example})})),d.userSpecifiedExamples=d.userSpecifiedExamples.map(s=>({...s,example:s.example!=null?Boc({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:pLD(e.serviceTypeReferenceInfo,t)}}function pLD(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}}var __=class e{breadcrumbs=[];context;static STRING=Gs.TypeReference.primitive({v1:"STRING",v2:Gs.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Gs.TypeReference.container(Gs.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var sJp=require("fs/promises");var zoc=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:l,lineStart:d}=r;this._path.length===0?this._map["."+i]={line:u,position:l,lineStart:d}:this._fragments.push({path:this._path.join(".")+"."+i,line:u,position:l,lineStart:d})}else if(n==="mapping"){let u={path:a,children:[],line:0,position:0,lineStart:0},l=0;this.iterFragments(a,d=>{l++,!((!d.children||d.children.length===0)&&l%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},l=new Set,d=i.length;this.iterFragments(a,s=>{l.has(s.position)||(d--,l.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}}},uJp=zoc;var Gfi;(function(e){e.WARNING="warning",e.ERROR="error"})(Gfi||(Gfi={}));var cEi=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new xoc({logger:t,relativePathToFile:Na.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||Gfi.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===Gfi.ERROR?t++:r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors)if(!(r.level===Gfi.WARNING&&!t))switch(r.level){case Gfi.ERROR:if(this.logger.log(Yv.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(Yv.Error,` - at location (${n})`)}break}}},xoc=class{logger;relativePathToFile;map=new uJp;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,sJp.readFile)(this.relativePathToFile,"utf-8");md.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Yv.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 g3=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=BZ({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=d_(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:Gfi.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[u]}return n==null?(i||this.errorCollector.collect({level:Gfi.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 c=await fetch(o);if(!c.ok)return{resolved:!1};try{let b=await c.text();try{a=JSON.parse(b),r=a}catch{a=md.load(b),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let l=i??t.$ref;if(l==null||typeof l!="string")return{resolved:!1};let d=l.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 l of t)u.push(await this.resolveNestedExternalReferences(l,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 l=await this.resolveMaybeExternalReference({$ref:u});if(i.delete(u),l.resolved)return l.value}else{let l=`${n}${u}`;if(i.has(l))return t;i.add(l);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,l]of Object.entries(t))typeof l=="object"&&l!==null?a[u]=await this.resolveNestedExternalReferences(l,r,i,n):a[u]=l;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 i=this.resolveReference({reference:r});if(!i.resolved)return;r=i.value}if(!(r.readOnly&&r.writeOnly)){if(r.readOnly)return ikt.ReadOnly;if(r.writeOnly)return ikt.WriteOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new RW.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 RW.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:O9.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return Kc.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 Mg=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 RW={};Po(RW,{AudienceExtension:()=>pLo,FernAvailabilityExtension:()=>_Lo,FernEnumExtension:()=>hLo,FernIgnoreExtension:()=>FGi,FernOptionalExtension:()=>yLo,FernTypeExtension:()=>gLo,FernTypeNameExtension:()=>OLo,SdkGroupNameExtension:()=>vLo,SdkMethodNameExtension:()=>bLo});var pLo=class extends Mg{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 _Lo=class extends Mg{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 O9.InDevelopment;case"PRE_RELEASE":case"BETA":return O9.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return O9.GeneralAvailability;case"DEPRECATED":return O9.Deprecated;default:return}}};var _LD=du.object({snake:du.string().optional(),camel:du.string().optional(),screamingSnake:du.string().optional(),pascal:du.string().optional()}),hLD=du.object({description:du.string().optional(),name:du.string().optional(),casing:_LD.optional()}),cJp=du.record(hLD);var hLo=class extends Mg{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=cJp.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 FGi=class extends Mg{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 yLo=class extends Mg{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 vLo=class extends Mg{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 bLo=class extends Mg{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 gLo=class extends Mg{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 OLo=class extends Mg{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 IWt=class extends __{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new NGi(i),this.ir={auth:{docs:void 0,requirement:Gs.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:Gs.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 FGi({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 FGi({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=Eoc({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=xTa({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 l of a.endpoints)r.has(l.id)&&u.push(l);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}),l=this.getOrCreatePackage({group:i}),d=[...u].map(c=>this.context.casingsGenerator.generateName(c)),s=d[d.length-1];l.service==null&&(l.service=a??`service_${u.map(c=>d_(c)).join("/")}`),this.ir.services[l.service]==null&&(this.ir.services[l.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[l.service]?.endpoints.push(t);let o=this.ir.services[l.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 l=this.context.createFernFilepath();this.irGraph.addWebhook(l,t),i!=null&&this.irGraph.markWebhookForAudiences(l,t,i)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:i,websocketGroup:n}){let a=d_(n?.join(".")),u=d_(r),l=this.context.namespace?`${d_(this.context.namespace)}/`:"",d=a?`channel_${l}${a}`:`channel_${l}${u}`,s=n?this.getOrCreatePackage({group:n}):this.getOrCreatePackage({group:[u]});this.ir.websocketChannels={...this.ir.websocketChannels,[d]:t},d!==""?s.websocket==null&&(s.websocket=d):this.ir.rootPackage.websocket="";let o=this.context.createFernFilepath();this.irGraph.addChannel(o,d,t),i!=null&&this.irGraph.markChannelForAudiences(o,d,i)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[i,n]of Object.entries(t??{}))r[i]!=null&&this.irGraph.markEnvironmentForAudiences(n,r[i])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,i])=>[r,i.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let i of r.endpoints)i.baseUrl==null&&(i.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:i}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:i,basePath:JN(""),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=>d_(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]??"",l=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[l]==null&&(this.ir.subpackages[l]={name:this.context.casingsGenerator.generateName(a),...this.createPackage({name:a})});let d=this.ir.subpackages[l];i.subpackages.includes(l)||i.subpackages.push(l),i=d}return i}};var wM={};Po(wM,{AbstractConverters:()=>Noc,ExampleConverter:()=>VNe,SchemaConverters:()=>Roc,ServersConverter:()=>rMe});var Noc={};Po(Noc,{AbstractMediaTypeObjectConverter:()=>jLo,AbstractParameterConverter:()=>wLo});var VNe=class e extends __{MAX_DEPTH=12;EXAMPLE_STRING="foo";EXAMPLE_NUMBER=42;EXAMPLE_BOOLEAN=!0;EXAMPLE_INTEGER=42;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:u,generateOptionalProperties:l=!1,seenRefs:d=new Set}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=u,this.generateOptionalProperties=l,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;return typeof t=="string"?{isValid:!0,coerced:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_STRING,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(l=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:l,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),u=a.every(l=>l?.isValid??!1)&&!r;return{isValid:u,coerced:!1,validExample:a.map(l=>l.validExample),errors:u?[]:a.flatMap(l=>l.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,c=!t.required?.includes(d);if(o&&c){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,c])=>c!==void 0))}}let l=[];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(c=>!s.has(c)).forEach(c=>{let g=new e({breadcrumbs:[...this.breadcrumbs,c],context:this.context,schema:d,example:r[c],depth:this.depth+1,generateOptionalProperties:!1,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();l.push({key:c,result:g})})}for(let{key:d,result:s}of l)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,l)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${l}]`],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,l)=>new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${l}]`],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(l=>!l.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,l)=>new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${l}]`],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(l=>!l.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 Roc={};Po(Roc,{ArraySchemaConverter:()=>r4n,EnumSchemaConverter:()=>Z6n,ObjectSchemaConverter:()=>k6n,OneOfSchemaConverter:()=>e4n,PrimitiveSchemaConverter:()=>t4n,SchemaConverter:()=>lEi,SchemaOrReferenceConverter:()=>VQ});function lJp(e){return q2({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Kc.primitive({v1:"BASE_64",v2:Ed.base64({})});case"BOOLEAN":return Kc.primitive({v1:"BOOLEAN",v2:Ed.boolean({default:void 0})});case"DATE":return Kc.primitive({v1:"DATE",v2:Ed.date({})});case"DATE_TIME":return Kc.primitive({v1:"DATE_TIME",v2:Ed.dateTime({})});case"FLOAT":return Kc.primitive({v1:"FLOAT",v2:Ed.float({})});case"DOUBLE":return Kc.primitive({v1:"DOUBLE",v2:Ed.double({default:void 0,validation:void 0})});case"UINT":return Kc.primitive({v1:"UINT",v2:Ed.uint({})});case"UINT_64":return Kc.primitive({v1:"UINT_64",v2:Ed.uint64({})});case"INTEGER":return Kc.primitive({v1:"INTEGER",v2:Ed.integer({default:void 0,validation:void 0})});case"LONG":return Kc.primitive({v1:"LONG",v2:Ed.long({default:void 0})});case"STRING":return Kc.primitive({v1:"STRING",v2:Ed.string({default:void 0,validation:void 0})});case"UUID":return Kc.primitive({v1:"UUID",v2:Ed.uuid({})});case"BIG_INTEGER":return Kc.primitive({v1:"BIG_INTEGER",v2:Ed.bigInteger({default:void 0})});default:return}},unknown:()=>Kc.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Kc.container(Py.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Kc.container(Py.list(t))},optional:t=>{if(t!=null)return Kc.container(Py.optional(t))},nullable:t=>{if(t!=null)return Kc.container(Py.nullable(t))},set:t=>{if(t!=null)return Kc.container(Py.set(t))},literal:t=>Kc.container(Py.literal(t._visit({string:r=>S9.string(r),boolean:r=>S9.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var Z6n=class extends __{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],l=u?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:l,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:Sb.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var mLo=class extends __{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=Kc.container(Py.map({keyType:__.STRING,valueType:Kc.unknown()}));return{type:Sb.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new VQ({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=Kc.container(Py.map({keyType:__.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:Sb.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function FTa({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],u={},l={},d=new Set;for(let[s,o]of Object.entries(e??{})){let c=[...r,"properties",s];if(typeof o!="object"){n.collect({message:`Schema property ${s} should be an object`,path:c});continue}let b=yLD(r,o,i)??i.convertBreadcrumbsToName(c),g="nullable"in o?o.nullable:!1,m=new VQ({context:i,breadcrumbs:c,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(w=>{d.add(w)});for(let w of m.schema?.audiences??[])l[w]==null&&(l[w]=new Set),l[w].add(s)}}for(let s of Object.keys(u))d.add(s);return{convertedProperties:a,propertiesByAudience:l,inlinedTypesFromProperties:u,referencedTypes:d}}function yLD(e,t,r){return r.isReferenceObject(t)?void 0:new RW.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var k6n=class extends __{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:Sb.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=FTa({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),u=[],l=n,d=this.schema.required!=null&&this.schema.required.length>0,s=i,o=a;for(let[c,b]of(this.schema.allOf??[]).entries()){let g=[...this.breadcrumbs,"allOf",c.toString()],O;if(this.context.isReferenceObject(b)){if(!d){this.addTypeReferenceToExtends({reference:b,breadcrumbs:g,extends_:u,referencedTypes:l});continue}let A=this.context.resolveMaybeReference({schemaOrReference:b,breadcrumbs:g});if(A==null)continue;if(O=A,Object.keys(O.properties??{}).every(D=>!this.schema.required?.includes(D))){this.addTypeReferenceToExtends({reference:b,breadcrumbs:g,extends_:u,referencedTypes:l});continue}}else O=b;let{convertedProperties:m,inlinedTypesFromProperties:w,referencedTypes:E,propertiesByAudience:q}=FTa({properties:O.properties??{},required:[...this.schema.required??[],...O.required??[]],breadcrumbs:g,context:this.context,errorCollector:this.context.errorCollector});r.push(...m),s={...s,...w},o={...o,...q},E.forEach(A=>{l.add(A)})}for(let c of Object.keys(s))l.add(c);return{type:Sb.object({properties:r,extends:u.map(c=>this.context.typeReferenceToDeclaredTypeName(c)).filter(yv),extendedProperties:[],extraProperties:t}),propertiesByAudience:o,referencedTypes:l,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 PLo=class extends Mg{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 e4n=class extends __{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 PLo({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 VQ({context:this.context,schemaOrReference:{$ref:s},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]}),c=this.context.getTypeIdFromSchemaReference({$ref:s});c!=null&&r.add(c);let b=o.convert();if(b?.type!=null&&c!=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:w9.samePropertiesAsObject({typeId:c,name:this.context.casingsGenerator.generateName(c),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:d})}),i={...i,...b.inlinedTypes}}}let{convertedProperties:n,referencedTypes:a,inlinedTypesFromProperties:u}=FTa({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});r=new Set([...r,...a]);let l=[];for(let[d,s]of(this.schema.allOf??[]).entries()){let o=[...this.breadcrumbs,"allOf",d.toString()];if(this.context.isReferenceObject(s)){let c=this.context.convertReferenceToTypeReference({reference:s,breadcrumbs:o});if(c.ok){let g=this.context.typeReferenceToDeclaredTypeName(c.reference);g!=null&&l.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:Sb.union({baseProperties:n,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:l,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={};for(let[n,a]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(a)){let c;if(this.context.isReferenceObjectWithIdentifier(a))c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverride:a.title??a.name??a.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(a)!=null){let g=this.getDiscriminatorKeyForRef(a);c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverride:g,displayNameOverrideSource:"discriminator_key"})}else c=this.context.convertReferenceToTypeReference({reference:a,displayNameOverrideSource:"schema_identifier"});c.ok&&t.push({type:c.reference,docs:a.description});let b=this.context.getTypeIdFromSchemaReference(a);b!=null&&r.add(b);continue}let u=this.extendSubSchema(a),l=this.context.convertBreadcrumbsToName([`${this.id}_${n}`]),d=a.title,o=new lEi({context:this.context,id:l,nameOverride:d,breadcrumbs:[...this.breadcrumbs,`oneOf[${n}]`],schema:u??a}).convert();if(o!=null){let c=o.convertedSchema.typeDeclaration.shape;c.type==="alias"&&this.typeReferenceIsWrappedPrimitive(c.aliasOf)?t.push({type:c.aliasOf,docs:a.description}):c.type==="object"&&c.properties.length===0?t.push({type:Kc.container(Py.map({keyType:__.STRING,valueType:Kc.unknown()})),docs:a.description}):(t.push({type:this.context.createNamedTypeReference(l,d),docs:a.description}),i={...i,...o.inlinedTypes,[l]:o.convertedSchema}),o.convertedSchema.typeDeclaration.referencedTypes.forEach(b=>{r.add(b)})}}return{type:Sb.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 VQ({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:Sb.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 Kc.container(Py.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 t4n=class extends __{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 Kc.container(Py.literal(S9.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return Kc.primitive({v1:Uh.Date,v2:Ed.date({})});if(this.schema.format==="date-time")return Kc.primitive({v1:Uh.DateTime,v2:Ed.dateTime({})})}return Kc.primitive({v1:"STRING",v2:Ed.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return Kc.primitive({v1:"DOUBLE",v2:Ed.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Kc.primitive({v1:"FLOAT",v2:Ed.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Kc.primitive({v1:"INTEGER",v2:Ed.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Kc.primitive({v1:"LONG",v2:Ed.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Kc.primitive({v1:"UINT",v2:Ed.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Kc.primitive({v1:"UINT_64",v2:Ed.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Kc.primitive({v1:"DOUBLE",v2:Ed.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return Kc.primitive({v1:"DOUBLE",v2:Ed.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Kc.primitive({v1:"FLOAT",v2:Ed.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Kc.primitive({v1:"INTEGER",v2:Ed.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Kc.primitive({v1:"LONG",v2:Ed.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Kc.primitive({v1:"UINT",v2:Ed.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Kc.primitive({v1:"UINT_64",v2:Ed.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Kc.primitive({v1:"INTEGER",v2:Ed.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?Kc.container(Py.literal(S9.boolean(t))):Kc.primitive({v1:"BOOLEAN",v2:Ed.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 vLD=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],lEi=class e extends __{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 l=this.tryConvertOneOfAnyOfSchema();if(l!=null)return l;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 RW.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new Z6n({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=jCn(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 t4n({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Sb.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new r4n({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Sb.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 e4n({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 mLo({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 k6n({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:Sb.alias({aliasOf:Kc.unknown(),resolvedType:Kc.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new RW.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=lJp(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Sb.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=[...vLD,...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 VNe({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 VQ=class extends __{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 lEi({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 Kc.container(Py.optional(t))}wrapInNullable(t){return Kc.container(Py.nullable(t))}};var r4n=class e extends __{static LIST_UNKNOWN=Kc.container(Py.list(Kc.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 VQ({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:Kc.container(Py.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var jLo=class extends __{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 VQ({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",i,"schema"],schemaOrReference:t.schema,schemaIdOverride:n}).convert();if(u==null)return;let l=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]:null}return[d,s]}).filter(d=>d!=null)):void 0;return{...u,examples:l}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let n=new VQ({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[l,d]of u){let s=this.context.resolveExampleWithValue(d),o=this.context.isExampleWithSummary(d)?d.summary:l;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 l=d_(`${[...this.group,this.method].join("_")}_example`);n.autogeneratedExamples[l]=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 l=this.context.getExamplesFromSchema({schema:u,breadcrumbs:this.breadcrumbs}),d=new VNe({breadcrumbs:this.breadcrumbs,context:this.context,schema:u,example:r??l[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:a}),{validExample:s,errors:o}=d.convert();return i||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),s}};var wLo=class extends __{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??__.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??__.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??__.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 l=this.context.resolveExampleWithValue(u);l!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:l}))}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 VNe({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:u}=n.convert();return r||u.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),a}};var SLo=class extends Mg{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 fJp="Base",rMe=class e extends __{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(l=>{let d=e.getServerName({server:l,context:this.context});return{id:d,name:this.context.casingsGenerator.generateName(d)}}).filter((l,d,s)=>s.findIndex(o=>o.id===l.id)===d),a=[i,...n],u=this.servers.map(l=>{let d=e.getServerName({server:l,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(l),...Object.fromEntries(s??[])},docs:l.description}});return{value:{defaultEnvironment:u[0]?.id,environments:ex.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(yv);return{value:{defaultEnvironment:t[0]?.id,environments:ex.singleBaseUrl({environments:t})},defaultUrl:t[0]?.id}}static getServerExtensionName({server:t,context:r}){return new SLo({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(([l,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(l=>{let d=r.url.replace(`{${a}}`,encodeURIComponent(l)),s={};for(let[c,b]of Object.entries(r.variables??{}))c!==a&&(s[c]=b);let o={...r,url:d,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${l}`:`${l}`,description:r.description};return this.withExplodedServers([o])[0]})}).filter(yv)}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?fJp:e.getServerExtensionName({server:this.servers[0],context:this.context})??fJp}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}};var LTa={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"},bLD=new Set(Object.values(LTa));var DLo=class{enabled=!0;write(t,...r){this.enabled&&process.stderr.write(`[${t}] ${r.join(" ")}
|
|
1916
|
-
`)}disable(){this.enabled=!1}enable(){this.enabled=!0}trace(...t){this.write(Yv.Trace,...t)}debug(...t){this.write(Yv.Debug,...t)}info(...t){this.write(Yv.Info,...t)}warn(...t){this.write(Yv.Warn,...t)}error(...t){this.write(Yv.Error,...t)}log(t,...r){this.write(t,...r)}};var fEi={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}},ELo={MESSAGE:4,ENUM:5,SERVICE:6};var MLo=class extends __{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,fEi.ENUM.VALUE,i]),availability:void 0}});return{type:Sb.enum({default:void 0,values:t})}}};function dJp(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var pJp=new Set([UC.DOUBLE,UC.FLOAT,UC.INT64,UC.UINT64,UC.INT32,UC.FIXED64,UC.FIXED32,UC.BOOL,UC.STRING,UC.BYTES,UC.UINT32,UC.SFIXED32,UC.SFIXED64,UC.SINT32,UC.SINT64]);var ALo=class e extends __{static LIST_UNKNOWN=Kc.container(Py.list(Kc.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 dEi({context:this.context,breadcrumbs:this.breadcrumbs,field:{...this.field,label:Mho.OPTIONAL},sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null){let i=new Set;return{typeReference:Kc.container(Py.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var qLo=class extends __{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 UC.STRING:return Kc.primitive({v1:Uh.String,v2:Ed.string({default:void 0,validation:void 0})});case UC.DOUBLE:return Kc.primitive({v1:Uh.Double,v2:Ed.double({default:void 0,validation:void 0})});case UC.FLOAT:return Kc.primitive({v1:Uh.Float,v2:Ed.float({})});case UC.INT32:return Kc.primitive({v1:Uh.Integer,v2:Ed.integer({default:void 0,validation:void 0})});case UC.INT64:return Kc.primitive({v1:Uh.Long,v2:Ed.long({default:void 0})});case UC.UINT32:return Kc.primitive({v1:Uh.Uint,v2:Ed.uint({default:void 0})});case UC.UINT64:return Kc.primitive({v1:Uh.Uint64,v2:Ed.uint64({default:void 0})});case UC.BOOL:return Kc.primitive({v1:Uh.Boolean,v2:Ed.boolean({default:void 0})});default:return Kc.unknown()}}};var dEi=class extends __{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 ALo({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(pJp.has(this.field.type)){let i=new qLo({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===11&&this.field.typeName!=null){let r=this.context.convertGrpcReferenceToTypeReference({typeName:this.context.maybeRemoveGrpcPackagePrefix(this.field.typeName),displayNameOverride:this.field.name});if(r.ok)return{type:this.wrapAsOptional?this.wrapInOptional(r.reference):r.reference,inlinedTypes:{}}}}wrapInOptional(t){return Kc.container(Py.optional(t))}};function _Jp({fields:e,breadcrumbs:t,context:r,sourceCodeInfoPath:i}){let n=[],a={},u=new Set,l={};for(let d of e){let o=new dEi({context:r,breadcrumbs:[...t,"fields",d.name],field:d,sourceCodeInfoPath:i}).convert();if(o!=null){let c={name:r.casingsGenerator.generateNameAndWireValue({name:d.name,wireValue:d.name}),valueType:o.type,docs:void 0,availability:void 0,propertyAccess:void 0,v2Examples:void 0};if(Object.prototype.hasOwnProperty.call(d,"oneofIndex")&&d.oneofIndex!=null){l[d.oneofIndex]==null&&(l[d.oneofIndex]=[]),l[d.oneofIndex].push(d);continue}n.push(c)}}return{convertedFields:n,referencedTypes:u,propertiesByAudience:a,oneOfFields:l}}var TLo=class extends __{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 dEi({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:Sb.undiscriminatedUnion({members:t}),referencedTypes:new Set,inlinedTypes:{}}}};var CLo=class extends __{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}=_Jp({fields:this.message.field,breadcrumbs:this.breadcrumbs,context:this.context,sourceCodeInfoPath:this.sourceCodeInfoPath});for(let l of n)r.add(l);for(let[l,d]of this.message.nestedType.entries()){let o=new pEi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,fEi.MESSAGE.NESTED_TYPE,l],schemaIndex:l}).convert();if(o!=null){for(let c of o.convertedSchema.typeDeclaration.referencedTypes)r.add(c);t={...t,...Object.fromEntries(Object.entries(o.inlinedTypes).map(([c,b])=>[this.prependDelimitedParentMessageName(c),this.context.updateTypeId(b,this.prependDelimitedParentMessageName(c))])),[this.prependDelimitedParentMessageName(d.name)]:this.context.updateTypeId(o.convertedSchema,this.prependDelimitedParentMessageName(d.name))}}}for(let[l,d]of this.message.enumType.entries()){let o=new pEi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,fEi.MESSAGE.ENUM_TYPE,l],schemaIndex:l}).convert();if(o!=null){for(let c of o.convertedSchema.typeDeclaration.referencedTypes)r.add(c);t={...t,...Object.fromEntries(Object.entries(o.inlinedTypes).map(([c,b])=>[this.prependDelimitedParentMessageName(c),this.context.updateTypeId(b,this.prependDelimitedParentMessageName(c))])),[this.prependDelimitedParentMessageName(d.name)]:this.context.updateTypeId(o.convertedSchema,this.prependDelimitedParentMessageName(d.name))}}}for(let[l,d]of this.message.oneofDecl.entries()){let o=new TLo({context:this.context,breadcrumbs:this.breadcrumbs,oneOfFields:u[l]??[],sourceCodeInfoPath:[...this.sourceCodeInfoPath,fEi.MESSAGE.ONEOF_DECL,l]}).convert();if(o!=null){for(let g of o.referencedTypes)r.add(g);let c={typeDeclaration:this.createTypeDeclaration({shape:o.type,referencedTypes:o.referencedTypes,typeName:this.prependParentMessageName(dJp(d.name))}),audiences:[],propertiesByAudience:{}},b=this.context.convertGrpcReferenceToTypeReference({typeName:c.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,[c.typeDeclaration.name.typeId]:c})}}return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Sb.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,omitV2Examples:n,docs:a}){return{name:this.convertDeclaredTypeName(i),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:void 0,docs:a,referencedTypes:r,source:void 0,inline:!1,v2Examples:void 0}}convertDeclaredTypeName(t){return{typeId:t,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(t),displayName:void 0}}prependDelimitedParentMessageName(t,r="."){return`${this.message.name}${r}${t}`}prependParentMessageName(t){return`${this.message.name}${t}`}};var pEi=class extends __{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 MLo({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 CLo({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,omitV2Examples:i,docs:n}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:void 0,docs:n,referencedTypes:r,source:void 0,inline:void 0,v2Examples:void 0}}convertDeclaredTypeName(){return{typeId:this.schema.name,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.schema.name),displayName:void 0}}};var BLo=class extends __{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.operation.name),requestBody:r,response:i,displayName:void 0,method:KC.Post,baseUrl:void 0,v2BaseUrls:void 0,v2Examples:void 0,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:_Q.proto(),audiences:[]}}}getMethodType(){return this.operation.clientStreaming&&this.operation.serverStreaming?"BIDI_STREAM":this.operation.clientStreaming?"CLIENT_STREAM":this.operation.serverStreaming?"SERVER_STREAM":"UNARY"}convertRequestBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.context.maybeRemoveGrpcPackagePrefix(this.operation.inputType)});if(t.ok)return tA.reference({contentType:"application/proto",docs:void 0,requestBodyType:t.reference,v2Examples:void 0})}convertResponseBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.context.maybeRemoveGrpcPackagePrefix(this.operation.outputType)});if(t.ok)return{body:xw.json(P9.response({responseBodyType:t.reference,docs:void 0,v2Examples:void 0})),statusCode:void 0}}};var ILo=class extends __{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 BLo({context:this.context,breadcrumbs:this.breadcrumbs,operation:i,serviceName:this.service.name,sourceCodeInfoPath:[...this.sourceCodeInfoPath,fEi.SERVICE.METHOD,r]}).convert();a!=null&&t.push(a)}return{endpoints:t,serviceName:this.service.name,inlinedTypes:{}}}};var zLo=class extends IWt{constructor({breadcrumbs:t,context:r,audiences:i}){super({breadcrumbs:t,context:r,audiences:i})}convert(){return this.convertOptions(),this.convertEnumsAndMessages(),this.convertServices(),this.finalizeIr()}convertOptions(){}convertEnumsAndMessages(){for(let[t,r]of this.context.spec.enumType.entries()){let n=new pEi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[ELo.ENUM,t],schemaIndex:t}).convert();n!=null&&this.addTypesToIr({...n.inlinedTypes,[r.name]:n.convertedSchema})}for(let[t,r]of this.context.spec.messageType.entries()){let n=new pEi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[ELo.MESSAGE,t],schemaIndex:t}).convert();n!=null&&this.addTypesToIr({...n.inlinedTypes,[r.name]:n.convertedSchema})}}convertServices(){for(let[t,r]of this.context.spec.service.entries()){let n=new ILo({context:this.context,breadcrumbs:this.breadcrumbs,service:r,sourceCodeInfoPath:[ELo.SERVICE,t]}).convert();if(n!=null)for(let a of n.endpoints)this.addEndpointToIr({endpointGroup:a.group,endpoint:a.endpoint,audiences:[],serviceName:n.serviceName})}}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let u=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),l=this.getOrCreatePackage({group:i}),d=[...u].map(c=>this.context.casingsGenerator.generateName(c)),s=d[d.length-1];l.service==null&&(l.service=a??`service_${u.map(c=>d_(c)).join("/")}`),this.ir.services[l.service]==null&&(this.ir.services[l.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[l.service]?.endpoints.push(t);let o=this.ir.services[l.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]??"",l=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[l]==null&&(this.ir.subpackages[l]={name:this.context.casingsGenerator.generateName(a),...this.createPackage({name:a})});let d=this.ir.subpackages[l];i.subpackages.includes(l)||i.subpackages.push(l),i=d}return i}};var xLo=class extends g3{comments;constructor({comments:t,...r}){super(r),this.comments=t}convertReferenceToTypeReference({reference:t}){return{ok:!1}}convertGrpcReferenceToTypeReference({typeName:t,displayNameOverride:r}){return{ok:!0,reference:Kc.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:t,default:void 0,inline:!1,displayName:r})}}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 hJp(e){let t={4:{},5:{},6:{}};return 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 l=1;l<i.length;l++){let d=i[l];d!=null&&(d in u||(u[d]={}),u=u[d])}u._comment=a.trim()}),t}function yJp({req:e,options:t}){let r,i=BZ({generationLanguage:void 0,keywords:void 0,smartCasing:!1});for(let a of e.protoFile){let l=new zLo({context:new xLo({spec:a,settings:{},errorCollector:new cEi({logger:{log:(d,...s)=>{}},relativeFilepathToSpec:void 0}),logger:new DLo,generationLanguage:void 0,smartCasing:!1,exampleGenerationArgs:{disabled:!0},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,comments:hJp(a)}),breadcrumbs:[],audiences:{type:"all"}}).convert();l!=null&&(r=r===void 0?l:xGi(r,l,i))}let n=Pp.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 vJp(e){return{}}var Foc=gLD({name:"protoc-gen-fern",version:`v${String(HQp)}`,run:yJp});function gLD({name:e,version:t,run:r}){return{name:e,version:t,run(i){let n=vJp(i.parameter),a=r({req:i,options:n});return OLD([a],Tcd,Ccd)}}}function OLD(e,t,r){return Nma(Tho,{supportedFeatures:qT.parse(Gma.PROTO3_OPTIONAL|Gma.SUPPORTS_EDITIONS),minimumEdition:t,maximumEdition:r,file:e})}var bJp=require("fs/promises");var gJp=require("path"),OJp=ui(QX(),1);async function mJp({url:e,logger:t}){try{let r=await mLD({url:e,logger:t}),i=await OJp.default.dir(),n=(0,gJp.join)(i.path,e.endsWith(".json")?"openapi.json":"openapi.yaml");return t.debug("tmpDir",i.path),t.debug("filePath",n),await(0,bJp.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 mLD({url:e,logger:t}){let r=await VN.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:Kgo(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)`),Kgo(r.data))}var _Ei=e=>e.name==="up"||e.name==="k"||e.ctrl&&e.name==="p",i4n=e=>e.name==="down"||e.name==="j"||e.ctrl&&e.name==="n",PJp=e=>e.name==="space",n4n=e=>e.name==="backspace",RLo=e=>"1234567890".includes(e.name),V6=e=>e.name==="enter"||e.name==="return";var NLo=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(t){super(),this.cause=t?.cause}},FLo=class extends Error{name="CancelPromptError";message="Prompt was canceled"},UTa=class extends Error{name="ExitPromptError"},LLo=class extends Error{name="HookError"},Mrr=class extends Error{name="ValidationError"};var DJp=require("async_hooks");var ULo=require("async_hooks");var jJp=new ULo.AsyncLocalStorage;function PLD(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function wJp(e,t){let r=PLD(e);return jJp.run(r,()=>{function i(n){r.handleChange=()=>{r.index=0,n()},r.handleChange()}return t(i)})}function LGi(){let e=jJp.getStore();if(!e)throw new LLo("[Inquirer] Hook functions can only be called from within a prompt");return e}function Loc(){return LGi().rl}function Uoc(e){let t=(...r)=>{let i=LGi(),n=!1,a=i.handleChange;i.handleChange=()=>{n=!0};let u=e(...r);return n&&a(),i.handleChange=a,u};return ULo.AsyncResource.bind(t)}function a4n(e){let t=LGi(),{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 SJp(){LGi().handleChange()}var UGi={queue(e){let t=LGi(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(Loc());if(i!=null&&typeof i!="function")throw new Mrr("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=LGi();Uoc(()=>{e.hooksEffect.forEach(t=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=LGi();e.hooksCleanup.forEach(t=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function D0(e){return a4n(t=>{let r=DJp.AsyncResource.bind(function(a){t.get()!==a&&(t.set(a),SJp())});if(t.initialized)return[t.get(),r];let i=typeof e=="function"?e():e;return t.set(i),[i,r]})}function zWt(e,t){a4n(r=>{let i=r.get();(!Array.isArray(i)||t.some((a,u)=>!Object.is(a,i[u])))&&UGi.queue(e),r.set(t)})}var WNe=ui(z2(),1);var EJp={prefix:{idle:WNe.default.blue("?"),done:WNe.default.green(A6.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(e=>WNe.default.yellow(e))},style:{answer:WNe.default.cyan,message:WNe.default.bold,error:e=>WNe.default.red(`> ${e}`),defaultAnswer:e=>WNe.default.dim(`(${e})`),help:WNe.default.dim,highlight:WNe.default.cyan,key:e=>WNe.default.cyan(WNe.default.bold(`<${e}>`))}};function MJp(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 AJp(...e){let t={};for(let r of e)for(let[i,n]of Object.entries(r)){let a=t[i];t[i]=MJp(a)&&MJp(n)?AJp(a,n):n}return t}function cR(...e){let t=[EJp,...e.filter(r=>r!=null)];return AJp(...t)}function O3({status:e="idle",theme:t}){let[r,i]=D0(!1),[n,a]=D0(0),{prefix:u,spinner:l}=cR(t);return zWt(()=>{if(e==="loading"){let s,o=-1,c=setTimeout(()=>{i(!0),s=setInterval(()=>{o=o+1,a(o%l.frames.length)},l.interval)},300);return()=>{clearTimeout(c),clearInterval(s)}}else i(!1)},[e]),r?l.frames[n]:typeof u=="string"?u:u[e==="loading"?"idle":e]??u.idle}function jae(e,t){return a4n(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 HNe(e){return D0({current:e})[0]}function m3(e){let t=HNe(e);t.current=e,zWt(r=>{let i=!1,n=Uoc((a,u)=>{i||t.current(u,r)});return r.input.on("keypress",n),()=>{i=!0,r.input.removeListener("keypress",n)}},[])}var qJp=ui(CGs(),1),TJp=ui(zGs(),1);function VTa(e,t){return e.split(`
|
|
1916
|
+
`)}disable(){this.enabled=!1}enable(){this.enabled=!0}trace(...t){this.write(Yv.Trace,...t)}debug(...t){this.write(Yv.Debug,...t)}info(...t){this.write(Yv.Info,...t)}warn(...t){this.write(Yv.Warn,...t)}error(...t){this.write(Yv.Error,...t)}log(t,...r){this.write(t,...r)}};var fEi={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}},ELo={MESSAGE:4,ENUM:5,SERVICE:6};var MLo=class extends __{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,fEi.ENUM.VALUE,i]),availability:void 0}});return{type:Sb.enum({default:void 0,values:t})}}};function dJp(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var pJp=new Set([UC.DOUBLE,UC.FLOAT,UC.INT64,UC.UINT64,UC.INT32,UC.FIXED64,UC.FIXED32,UC.BOOL,UC.STRING,UC.BYTES,UC.UINT32,UC.SFIXED32,UC.SFIXED64,UC.SINT32,UC.SINT64]);var ALo=class e extends __{static LIST_UNKNOWN=Kc.container(Py.list(Kc.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 dEi({context:this.context,breadcrumbs:this.breadcrumbs,field:{...this.field,label:Mho.OPTIONAL},sourceCodeInfoPath:this.sourceCodeInfoPath}).convert();if(r!=null){let i=new Set;return{typeReference:Kc.container(Py.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var qLo=class extends __{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 UC.STRING:return Kc.primitive({v1:Uh.String,v2:Ed.string({default:void 0,validation:void 0})});case UC.DOUBLE:return Kc.primitive({v1:Uh.Double,v2:Ed.double({default:void 0,validation:void 0})});case UC.FLOAT:return Kc.primitive({v1:Uh.Float,v2:Ed.float({})});case UC.INT32:return Kc.primitive({v1:Uh.Integer,v2:Ed.integer({default:void 0,validation:void 0})});case UC.INT64:return Kc.primitive({v1:Uh.Long,v2:Ed.long({default:void 0})});case UC.UINT32:return Kc.primitive({v1:Uh.Uint,v2:Ed.uint({default:void 0})});case UC.UINT64:return Kc.primitive({v1:Uh.Uint64,v2:Ed.uint64({default:void 0})});case UC.BOOL:return Kc.primitive({v1:Uh.Boolean,v2:Ed.boolean({default:void 0})});default:return Kc.unknown()}}};var dEi=class extends __{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 ALo({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(pJp.has(this.field.type)){let i=new qLo({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===11&&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 Kc.container(Py.optional(t))}};function _Jp({fields:e,breadcrumbs:t,context:r,sourceCodeInfoPath:i}){let n=[],a={},u=new Set,l={};for(let d of e){let o=new dEi({context:r,breadcrumbs:[...t,"fields",d.name],field:d,sourceCodeInfoPath:i}).convert();if(o!=null){let c={name:r.casingsGenerator.generateNameAndWireValue({name:d.name,wireValue:d.name}),valueType:o.type,docs:void 0,availability:void 0,propertyAccess:void 0,v2Examples:void 0};if(Object.prototype.hasOwnProperty.call(d,"oneofIndex")&&d.oneofIndex!=null){l[d.oneofIndex]==null&&(l[d.oneofIndex]=[]),l[d.oneofIndex].push(d);continue}n.push(c)}}return{convertedFields:n,referencedTypes:u,propertiesByAudience:a,oneOfFields:l}}var TLo=class extends __{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 dEi({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:Sb.undiscriminatedUnion({members:t}),referencedTypes:new Set,inlinedTypes:{}}}};var CLo=class extends __{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}=_Jp({fields:this.message.field,breadcrumbs:this.breadcrumbs,context:this.context,sourceCodeInfoPath:this.sourceCodeInfoPath});for(let l of n)r.add(l);for(let[l,d]of this.message.nestedType.entries()){let o=new pEi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,fEi.MESSAGE.NESTED_TYPE,l],schemaIndex:l}).convert();if(o!=null){for(let c of o.convertedSchema.typeDeclaration.referencedTypes)r.add(c);t={...t,...Object.fromEntries(Object.entries(o.inlinedTypes).map(([c,b])=>[this.prependDelimitedParentMessageName(c),this.context.updateTypeId(b,this.prependDelimitedParentMessageName(c))])),[this.prependDelimitedParentMessageName(d.name)]:this.context.updateTypeId(o.convertedSchema,this.prependDelimitedParentMessageName(d.name))}}}for(let[l,d]of this.message.enumType.entries()){let o=new pEi({context:this.context,breadcrumbs:this.breadcrumbs,schema:d,sourceCodeInfoPath:[...this.sourceCodeInfoPath,fEi.MESSAGE.ENUM_TYPE,l],schemaIndex:l}).convert();if(o!=null){for(let c of o.convertedSchema.typeDeclaration.referencedTypes)r.add(c);t={...t,...Object.fromEntries(Object.entries(o.inlinedTypes).map(([c,b])=>[this.prependDelimitedParentMessageName(c),this.context.updateTypeId(b,this.prependDelimitedParentMessageName(c))])),[this.prependDelimitedParentMessageName(d.name)]:this.context.updateTypeId(o.convertedSchema,this.prependDelimitedParentMessageName(d.name))}}}for(let[l,d]of this.message.oneofDecl.entries()){let o=new TLo({context:this.context,breadcrumbs:this.breadcrumbs,oneOfFields:u[l]??[],sourceCodeInfoPath:[...this.sourceCodeInfoPath,fEi.MESSAGE.ONEOF_DECL,l]}).convert();if(o!=null){for(let g of o.referencedTypes)r.add(g);let c={typeDeclaration:this.createTypeDeclaration({shape:o.type,referencedTypes:o.referencedTypes,typeName:this.prependParentMessageName(dJp(d.name))}),audiences:[],propertiesByAudience:{}},b=this.context.convertGrpcReferenceToTypeReference({typeName:this.context.maybePrependPackageName(c.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,[c.typeDeclaration.name.typeId]:c})}}return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Sb.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,omitV2Examples:n,docs:a}){return{name:this.convertDeclaredTypeName(i),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:void 0,docs:a,referencedTypes:r,source:void 0,inline:!1,v2Examples:void 0}}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 pEi=class extends __{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 MLo({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 CLo({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,omitV2Examples:i,docs:n}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:void 0,docs:n,referencedTypes:r,source:void 0,inline:void 0,v2Examples:void 0}}convertDeclaredTypeName(){let t=this.context.maybePrependPackageName(this.schema.name);return{typeId:t,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(t),displayName:this.schema.name}}};var BLo=class extends __{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,response:i,displayName:this.context.maybeRemoveGrpcPackagePrefix(this.operation.name),method:KC.Post,baseUrl:void 0,v2BaseUrls:void 0,v2Examples:void 0,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:_Q.proto(),audiences:[]}}}getMethodType(){return this.operation.clientStreaming&&this.operation.serverStreaming?"BIDI_STREAM":this.operation.clientStreaming?"CLIENT_STREAM":this.operation.serverStreaming?"SERVER_STREAM":"UNARY"}convertRequestBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.operation.inputType,displayNameOverride:this.context.maybeRemoveGrpcPackagePrefix(this.operation.inputType)});if(t.ok)return tA.reference({contentType:"application/proto",docs:void 0,requestBodyType:t.reference,v2Examples:void 0})}convertResponseBody(){let t=this.context.convertGrpcReferenceToTypeReference({typeName:this.operation.outputType,displayNameOverride:this.context.maybeRemoveGrpcPackagePrefix(this.operation.outputType)});if(t.ok)return{body:xw.json(P9.response({responseBodyType:t.reference,docs:void 0,v2Examples:void 0})),statusCode:void 0}}};var ILo=class extends __{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 BLo({context:this.context,breadcrumbs:this.breadcrumbs,operation:i,serviceName:this.service.name,sourceCodeInfoPath:[...this.sourceCodeInfoPath,fEi.SERVICE.METHOD,r]}).convert();a!=null&&t.push(a)}return{endpoints:t,serviceName:this.context.maybePrependPackageName(this.service.name),inlinedTypes:{}}}};var zLo=class extends IWt{constructor({breadcrumbs:t,context:r,audiences:i}){super({breadcrumbs:t,context:r,audiences:i})}convert(){return this.convertOptions(),this.convertEnumsAndMessages(),this.convertServices(),this.finalizeIr()}convertOptions(){}convertEnumsAndMessages(){for(let[t,r]of this.context.spec.enumType.entries()){let n=new pEi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[ELo.ENUM,t],schemaIndex:t}).convert();n!=null&&this.addTypesToIr({...n.inlinedTypes,[this.context.maybePrependPackageName(r.name)]:n.convertedSchema})}for(let[t,r]of this.context.spec.messageType.entries()){let n=new pEi({context:this.context,breadcrumbs:[...this.breadcrumbs,this.context.spec.package],schema:r,sourceCodeInfoPath:[ELo.MESSAGE,t],schemaIndex:t}).convert();n!=null&&this.addTypesToIr({...n.inlinedTypes,[this.context.maybePrependPackageName(r.name)]:n.convertedSchema})}}convertServices(){for(let[t,r]of this.context.spec.service.entries()){let n=new ILo({context:this.context,breadcrumbs:this.breadcrumbs,service:r,sourceCodeInfoPath:[ELo.SERVICE,t]}).convert();if(n!=null)for(let a of n.endpoints)this.addEndpointToIr({endpointGroup:a.group,endpoint:a.endpoint,audiences:[],serviceName:n.serviceName})}}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let u=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),l=this.getOrCreatePackage({group:i}),d=[...u].map(c=>this.context.casingsGenerator.generateName(c)),s=d[d.length-1];l.service==null&&(l.service=a??`service_${u.map(c=>d_(c)).join("/")}`),this.ir.services[l.service]==null&&(this.ir.services[l.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[l.service]?.endpoints.push(t);let o=this.ir.services[l.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]??"",l=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[l]==null&&(this.ir.subpackages[l]={name:this.context.casingsGenerator.generateName(a),...this.createPackage({name:a})});let d=this.ir.subpackages[l];i.subpackages.includes(l)||i.subpackages.push(l),i=d}return i}};var xLo=class extends g3{comments;constructor({comments:t,...r}){super(r),this.comments=t}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:Kc.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 hJp(e){let t={4:{},5:{},6:{}};return 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 l=1;l<i.length;l++){let d=i[l];d!=null&&(d in u||(u[d]={}),u=u[d])}u._comment=a.trim()}),t}function yJp({req:e,options:t}){let r,i=BZ({generationLanguage:void 0,keywords:void 0,smartCasing:!1});for(let a of e.protoFile){let l=new zLo({context:new xLo({spec:a,settings:{},errorCollector:new cEi({logger:{log:(d,...s)=>{}},relativeFilepathToSpec:void 0}),logger:new DLo,generationLanguage:void 0,smartCasing:!1,exampleGenerationArgs:{disabled:!0},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,comments:hJp(a)}),breadcrumbs:[],audiences:{type:"all"}}).convert();l!=null&&(r=r===void 0?l:xGi(r,l,i))}let n=Pp.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 vJp(e){return{}}var Foc=gLD({name:"protoc-gen-fern",version:`v${String(HQp)}`,run:yJp});function gLD({name:e,version:t,run:r}){return{name:e,version:t,run(i){let n=vJp(i.parameter),a=r({req:i,options:n});return OLD([a],Tcd,Ccd)}}}function OLD(e,t,r){return Nma(Tho,{supportedFeatures:qT.parse(Gma.PROTO3_OPTIONAL|Gma.SUPPORTS_EDITIONS),minimumEdition:t,maximumEdition:r,file:e})}var bJp=require("fs/promises");var gJp=require("path"),OJp=ui(QX(),1);async function mJp({url:e,logger:t}){try{let r=await mLD({url:e,logger:t}),i=await OJp.default.dir(),n=(0,gJp.join)(i.path,e.endsWith(".json")?"openapi.json":"openapi.yaml");return t.debug("tmpDir",i.path),t.debug("filePath",n),await(0,bJp.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 mLD({url:e,logger:t}){let r=await VN.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:Kgo(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)`),Kgo(r.data))}var _Ei=e=>e.name==="up"||e.name==="k"||e.ctrl&&e.name==="p",i4n=e=>e.name==="down"||e.name==="j"||e.ctrl&&e.name==="n",PJp=e=>e.name==="space",n4n=e=>e.name==="backspace",RLo=e=>"1234567890".includes(e.name),V6=e=>e.name==="enter"||e.name==="return";var NLo=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(t){super(),this.cause=t?.cause}},FLo=class extends Error{name="CancelPromptError";message="Prompt was canceled"},UTa=class extends Error{name="ExitPromptError"},LLo=class extends Error{name="HookError"},Mrr=class extends Error{name="ValidationError"};var DJp=require("async_hooks");var ULo=require("async_hooks");var jJp=new ULo.AsyncLocalStorage;function PLD(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function wJp(e,t){let r=PLD(e);return jJp.run(r,()=>{function i(n){r.handleChange=()=>{r.index=0,n()},r.handleChange()}return t(i)})}function LGi(){let e=jJp.getStore();if(!e)throw new LLo("[Inquirer] Hook functions can only be called from within a prompt");return e}function Loc(){return LGi().rl}function Uoc(e){let t=(...r)=>{let i=LGi(),n=!1,a=i.handleChange;i.handleChange=()=>{n=!0};let u=e(...r);return n&&a(),i.handleChange=a,u};return ULo.AsyncResource.bind(t)}function a4n(e){let t=LGi(),{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 SJp(){LGi().handleChange()}var UGi={queue(e){let t=LGi(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(Loc());if(i!=null&&typeof i!="function")throw new Mrr("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=LGi();Uoc(()=>{e.hooksEffect.forEach(t=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=LGi();e.hooksCleanup.forEach(t=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function D0(e){return a4n(t=>{let r=DJp.AsyncResource.bind(function(a){t.get()!==a&&(t.set(a),SJp())});if(t.initialized)return[t.get(),r];let i=typeof e=="function"?e():e;return t.set(i),[i,r]})}function zWt(e,t){a4n(r=>{let i=r.get();(!Array.isArray(i)||t.some((a,u)=>!Object.is(a,i[u])))&&UGi.queue(e),r.set(t)})}var WNe=ui(z2(),1);var EJp={prefix:{idle:WNe.default.blue("?"),done:WNe.default.green(A6.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(e=>WNe.default.yellow(e))},style:{answer:WNe.default.cyan,message:WNe.default.bold,error:e=>WNe.default.red(`> ${e}`),defaultAnswer:e=>WNe.default.dim(`(${e})`),help:WNe.default.dim,highlight:WNe.default.cyan,key:e=>WNe.default.cyan(WNe.default.bold(`<${e}>`))}};function MJp(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 AJp(...e){let t={};for(let r of e)for(let[i,n]of Object.entries(r)){let a=t[i];t[i]=MJp(a)&&MJp(n)?AJp(a,n):n}return t}function cR(...e){let t=[EJp,...e.filter(r=>r!=null)];return AJp(...t)}function O3({status:e="idle",theme:t}){let[r,i]=D0(!1),[n,a]=D0(0),{prefix:u,spinner:l}=cR(t);return zWt(()=>{if(e==="loading"){let s,o=-1,c=setTimeout(()=>{i(!0),s=setInterval(()=>{o=o+1,a(o%l.frames.length)},l.interval)},300);return()=>{clearTimeout(c),clearInterval(s)}}else i(!1)},[e]),r?l.frames[n]:typeof u=="string"?u:u[e==="loading"?"idle":e]??u.idle}function jae(e,t){return a4n(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 HNe(e){return D0({current:e})[0]}function m3(e){let t=HNe(e);t.current=e,zWt(r=>{let i=!1,n=Uoc((a,u)=>{i||t.current(u,r)});return r.input.on("keypress",n),()=>{i=!0,r.input.removeListener("keypress",n)}},[])}var qJp=ui(CGs(),1),TJp=ui(zGs(),1);function VTa(e,t){return e.split(`
|
|
1917
1917
|
`).flatMap(r=>(0,TJp.default)(r,t,{trim:!1,hard:!0}).split(`
|
|
1918
1918
|
`).map(i=>i.trimEnd())).join(`
|
|
1919
1919
|
`)}function VLo(){return(0,qJp.default)({defaultWidth:80,output:Loc().output})}function jLD({active:e,renderedItems:t,pageSize:r,loop:i}){let n=HNe({lastPointer:e,lastActive:void 0}),{lastPointer:a,lastActive:u}=n.current,l=Math.floor(r/2),d=t.reduce((c,b)=>c+b.length,0),s=t.slice(0,e).reduce((c,b)=>c+b.length,0),o=s;if(d>r)if(i)o=a,u!=null&&u<e&&e-u<r&&(o=Math.min(l,Math.abs(e-u)===1?Math.min(a+(t[u]?.length??0),Math.max(s,a)):a+e-u));else{let c=t.slice(e).reduce((b,g)=>b+g.length,0);o=c<r-l?r-c:Math.min(s,l)}return n.current.lastPointer=o,n.current.lastActive=e,o}function VGi({items:e,active:t,renderItem:r,pageSize:i,loop:n=!0}){let a=VLo(),u=E=>(E%e.length+e.length)%e.length,l=e.map((E,q)=>E==null?[]:VTa(r({item:E,index:q,isActive:q===t}),a).split(`
|
|
@@ -1954,7 +1954,7 @@ ${A}${q}${D}${YJp.default.cursorHide}`});var HTa=ui(Dwi(),1);function ruc(e,t){i
|
|
|
1954
1954
|
Run ${Ss.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
1955
1955
|
Run ${Ss.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),PFn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function puc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!OKp(e))return;let n=t??"",a=e.filter(l=>l.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((l,d)=>l.generatorName.localeCompare(d.generatorName)||l.currentVersion.localeCompare(d.currentVersion));for(let l of u)n+=`
|
|
1956
1956
|
${await gUD(l.generatorName)} (${l.apiName!=null?"API: "+l.apiName+", ":""}Group: ${l.generatorGroup}) `+Ss.dim(l.currentVersion)+Ss.reset(" \u2192 ")+Ss.green(l.latestVersion);return n+=`
|
|
1957
|
-
`,i?PFn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function gUD(e){let r=await new gKp.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 OUD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await PKp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=Swi(o.name,c),g=await KZt({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await PKp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=Swi(s.name,o),b=await KZt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function PKp({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await AVt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.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 jKp(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=wae(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function kLo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await OUD({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...jKp(s,d,t.logger));else u.push(...jKp(l.versions,void 0,t.logger))}return u}var ZTa=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(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var l4n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var _uc=(()=>{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})(),wKp=typeof globalThis.AbortController=="function",SKp=typeof globalThis.ReadableStream=="function",DKp=typeof globalThis.FormData=="function",eUo=["get","post","put","patch","head","delete"],mUD=()=>{};mUD();var EKp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},tUo=2147483647,MKp=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,rUo=Symbol("stop"),AKp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},qKp={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 PUD=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=MKp,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},TKp=(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:l,value:d}=await a.read();if(l){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})},CKp=(e,t)=>{let r=PUD(e.body),i=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(n){let a=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function u(){let{done:l,value:d}=await a.read();if(l){t&&t({percent:1,transferredBytes:i,totalBytes:Math.max(r,i)},new Uint8Array),n.close();return}i+=d.byteLength;let s=r===0?0:i/r;(r<i||s===1)&&(s=.99),t&&t({percent:Number(s.toFixed(2)),transferredBytes:i,totalBytes:r},d),n.enqueue(d),await u()}await u()}})})};var f4n=e=>e!==null&&typeof e=="object";var kTa=(...e)=>{for(let t of e)if((!f4n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return vuc({},...e)},huc=(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 iUo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:vuc(e[r]??[],t[r]??[])}var yuc=(e={},t={})=>({beforeRequest:iUo(e,t,"beforeRequest"),beforeRetry:iUo(e,t,"beforeRetry"),afterResponse:iUo(e,t,"afterResponse"),beforeError:iUo(e,t,"beforeError")}),vuc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(f4n(n)){for(let[a,u]of Object.entries(n))f4n(u)&&a in t&&(u=vuc(t[a],u)),t={...t,[a]:u};f4n(n.hooks)&&(i=yuc(i,n.hooks),t.hooks=i),f4n(n.headers)&&(r=huc(r,n.headers),t.headers=r)}return t};var IKp=e=>eUo.includes(e)?e.toUpperCase():e,jUD=["get","put","head","delete","options","trace"],wUD=[408,413,429,500,502,503,504],SUD=[413,429,503],BKp={limit:2,methods:jUD,statusCodes:wUD,afterStatusCodes:SUD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},zKp=(e={})=>{if(typeof e=="number")return{...BKp,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{...BKp,...e}};async function buc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new l4n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function guc(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 xKp=(e,t)=>{let r={};for(let i in t)!(i in qKp)&&!(i in AKp)&&!(i in e)&&(r[i]=t[i]);return r};var eCa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>tUo)throw new RangeError(`The \`timeout\` option cannot be greater than ${tUo}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new ZTa(l,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(!SKp)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return TKp(l.clone(),i._options.onDownloadProgress)}return l},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[l,d]of Object.entries(EKp))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await u;if(l==="json"){if(s.status===204||(await s.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await s.text())}return s[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:huc(this._input.headers,r.headers),hooks:yuc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:IKp(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:zKp(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(wKp){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(_uc&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(DKp&&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(!_uc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=CKp(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof l4n)throw t;if(t instanceof ZTa){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),tUo);if(this._retryCount<1)throw r;await guc(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})===rUo)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=xKp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):buc(r,t,this.abortController,this._options)}};var Ouc=e=>{let t=(r,i)=>eCa.create(r,kTa(e,i));for(let r of eUo)t[r]=(i,n)=>eCa.create(i,kTa(e,n,{method:r}));return t.create=r=>Ouc(kTa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Ouc(kTa(e,r))),t.stop=rUo,t},DUD=Ouc(),RKp=DUD;var oYp=ui(aYp(),1);function Suc(e){let t=(0,oYp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var eXp=ui(kYp(),1),tXp=ui(Dwi(),1),Nuc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Fuc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Luc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Suc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,eXp.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,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await RKp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new Nuc(e):c}if(t.allVersions)return s;let o=new Fuc(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=tXp.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 oCa(e,t){let{version:r}=await Luc(e.toLowerCase(),t);return r}async function bEi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:oCa(e.packageName,{version:t?"prerelease":"latest"})}var rXp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],hUo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Yv.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new ZLo(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.64.35"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ss.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new c9}failWithoutThrowing(t,r){this.didSucceed=!1,JLo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await pFn()).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 mKp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1957
|
+
`,i?PFn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function gUD(e){let r=await new gKp.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 OUD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await PKp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=Swi(o.name,c),g=await KZt({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await PKp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=Swi(s.name,o),b=await KZt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function PKp({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await AVt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.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 jKp(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=wae(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function kLo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await OUD({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...jKp(s,d,t.logger));else u.push(...jKp(l.versions,void 0,t.logger))}return u}var ZTa=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(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var l4n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var _uc=(()=>{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})(),wKp=typeof globalThis.AbortController=="function",SKp=typeof globalThis.ReadableStream=="function",DKp=typeof globalThis.FormData=="function",eUo=["get","post","put","patch","head","delete"],mUD=()=>{};mUD();var EKp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},tUo=2147483647,MKp=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,rUo=Symbol("stop"),AKp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},qKp={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 PUD=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=MKp,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},TKp=(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:l,value:d}=await a.read();if(l){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})},CKp=(e,t)=>{let r=PUD(e.body),i=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(n){let a=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();async function u(){let{done:l,value:d}=await a.read();if(l){t&&t({percent:1,transferredBytes:i,totalBytes:Math.max(r,i)},new Uint8Array),n.close();return}i+=d.byteLength;let s=r===0?0:i/r;(r<i||s===1)&&(s=.99),t&&t({percent:Number(s.toFixed(2)),transferredBytes:i,totalBytes:r},d),n.enqueue(d),await u()}await u()}})})};var f4n=e=>e!==null&&typeof e=="object";var kTa=(...e)=>{for(let t of e)if((!f4n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return vuc({},...e)},huc=(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 iUo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:vuc(e[r]??[],t[r]??[])}var yuc=(e={},t={})=>({beforeRequest:iUo(e,t,"beforeRequest"),beforeRetry:iUo(e,t,"beforeRetry"),afterResponse:iUo(e,t,"afterResponse"),beforeError:iUo(e,t,"beforeError")}),vuc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(f4n(n)){for(let[a,u]of Object.entries(n))f4n(u)&&a in t&&(u=vuc(t[a],u)),t={...t,[a]:u};f4n(n.hooks)&&(i=yuc(i,n.hooks),t.hooks=i),f4n(n.headers)&&(r=huc(r,n.headers),t.headers=r)}return t};var IKp=e=>eUo.includes(e)?e.toUpperCase():e,jUD=["get","put","head","delete","options","trace"],wUD=[408,413,429,500,502,503,504],SUD=[413,429,503],BKp={limit:2,methods:jUD,statusCodes:wUD,afterStatusCodes:SUD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},zKp=(e={})=>{if(typeof e=="number")return{...BKp,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{...BKp,...e}};async function buc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new l4n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function guc(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 xKp=(e,t)=>{let r={};for(let i in t)!(i in qKp)&&!(i in AKp)&&!(i in e)&&(r[i]=t[i]);return r};var eCa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>tUo)throw new RangeError(`The \`timeout\` option cannot be greater than ${tUo}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new ZTa(l,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(!SKp)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return TKp(l.clone(),i._options.onDownloadProgress)}return l},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[l,d]of Object.entries(EKp))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let s=await u;if(l==="json"){if(s.status===204||(await s.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await s.text())}return s[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:huc(this._input.headers,r.headers),hooks:yuc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:IKp(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:zKp(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(wKp){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(_uc&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(DKp&&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(!_uc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=CKp(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof l4n)throw t;if(t instanceof ZTa){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),tUo);if(this._retryCount<1)throw r;await guc(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})===rUo)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=xKp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):buc(r,t,this.abortController,this._options)}};var Ouc=e=>{let t=(r,i)=>eCa.create(r,kTa(e,i));for(let r of eUo)t[r]=(i,n)=>eCa.create(i,kTa(e,n,{method:r}));return t.create=r=>Ouc(kTa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Ouc(kTa(e,r))),t.stop=rUo,t},DUD=Ouc(),RKp=DUD;var oYp=ui(aYp(),1);function Suc(e){let t=(0,oYp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var eXp=ui(kYp(),1),tXp=ui(Dwi(),1),Nuc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Fuc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Luc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Suc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,eXp.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,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await RKp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new Nuc(e):c}if(t.allVersions)return s;let o=new Fuc(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=tXp.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 oCa(e,t){let{version:r}=await Luc(e.toLowerCase(),t);return r}async function bEi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:oCa(e.packageName,{version:t?"prerelease":"latest"})}var rXp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],hUo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Yv.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new ZLo(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.64.36"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ss.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new c9}failWithoutThrowing(t,r){this.didSucceed=!1,JLo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await pFn()).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 mKp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1958
1958
|
`)||(r+=`
|
|
1959
1959
|
`),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=ZBs(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 $Ta(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 c9}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await pFn()).sendEvent(t)}logger=cXt((t,...r)=>this.log(t,...r));stderr=cXt((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=iXp(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?iXp(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=rXp[this.numTasks++%rXp.length],u=Ss.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===EB.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=>xji.indexOf(n.level)>=xji.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===Yv.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 bEi({cliEnvironment:this.environment,includePreReleases:t}),i=wae(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await kLo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await Xoc({message:t,default:r})}async getInput(t){return await Zoc({message:t.message,default:t.default})}};function iXp(e){return`[${e}]:`}var A0_=require("fs/promises");function QNe({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Ss.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Ss.dim(r)),i.join(`
|
|
1960
1960
|
`)}var Cp_=require("fs/promises");var RWt=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 nMe=class extends RWt{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 uCa=class{context;constructor(t){this.context=t}};var yUo=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let d=n!=null?Oy.of(`${n}${GUt}${u}`):Oy.of(u);t[d]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${GUt}${u}`:u,d=i.directories[u];r(d,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(GUt))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[Oy.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 eQi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new yUo,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 fkt(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"]))nXp(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(nXp(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??d_((axe(r)+"/"+NUi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===Oy.of(UF))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=bgo(axe(gBn.of(`/${t}`)),gBn.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=bgo(axe(gBn.of(`/${t}`)),gBn.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===Oy.of(UF))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(l=>b2(l,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=EN(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:EN(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:EN(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===TS?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 nXp(e){return e?.header!=null}var Sae={openapi:e=>({...e,type:"openapi",_visit:function(t){return Sae._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return Sae._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 b4n={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return b4n._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var Q9={basic:e=>({...e,type:"basic",_visit:function(t){return Q9._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return Q9._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return Q9._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return Q9._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return Q9._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 Ag={primitive:e=>({value:e,type:"primitive",_visit:function(t){return Ag._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Ag._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return Ag._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return Ag._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return Ag._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return Ag._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Ag._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return Ag._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 r_={int:e=>({value:e,type:"int",_visit:function(t){return r_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return r_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return r_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return r_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return r_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return r_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return r_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return r_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return r_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return r_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return r_._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 g4n={boolean:e=>({value:e,type:"boolean",_visit:function(t){return g4n._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return g4n._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 gEi={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return gEi._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return gEi._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 FW={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case FW.GenerallyAvailable:return t.generallyAvailable();case FW.Beta:return t.beta();case FW.Deprecated:return t.deprecated();default:return t._other()}}};var JNe={cursor:e=>({...e,type:"cursor",_visit:function(t){return JNe._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return JNe._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return JNe._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 Kfi={language:e=>({...e,type:"language",_visit:function(t){return Kfi._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return Kfi._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 LW={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 LW.Curl:return t.curl();case LW.Python:return t.python();case LW.Javascript:return t.javascript();case LW.Typescript:return t.typescript();case LW.Go:return t.go();case LW.Ruby:return t.ruby();case LW.Csharp:return t.csharp();case LW.Java:return t.java();case LW.Js:return t.js();case LW.Node:return t.node();case LW.Ts:return t.ts();case LW.Nodets:return t.nodets();case LW.Golang:return t.golang();case LW.Dotnet:return t.dotnet();case LW.Jvm:return t.jvm();default:return t._other()}}};var NWt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return NWt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return NWt._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 FWt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return FWt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return FWt._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 UW={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case UW.Get:return t.get();case UW.Post:return t.post();case UW.Put:return t.put();case UW.Patch:return t.patch();case UW.Delete:return t.delete();case UW.Head:return t.head();case UW.Options:return t.options();case UW.Trace:return t.trace();default:return t._other()}}};var OEi={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return OEi._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return OEi._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return OEi._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);default:return t._other(e)}}};var Yfi={file:e=>({...e,type:"file",_visit:function(t){return Yfi._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return Yfi._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 $Q={file:e=>({...e,type:"file",_visit:function(t){return $Q._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return $Q._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return $Q._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return $Q._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return $Q._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return $Q._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return $Q._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 Gy={primitive:e=>({...e,type:"primitive",_visit:function(t){return Gy._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Gy._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Gy._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Gy._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Gy._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Gy._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Gy._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Gy._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Gy._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Gy._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Gy._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 Yj={int:e=>({...e,type:"int",_visit:function(t){return Yj._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return Yj._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return Yj._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return Yj._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return Yj._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return Yj._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return Yj._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return Yj._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return Yj._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return Yj._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return Yj._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 sz={boolean:e=>({value:e,type:"boolean",_visit:function(t){return sz._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return sz._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 Xfi={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Xfi._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Xfi._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 aMe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return aMe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return aMe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return aMe._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);default:return t._other(e)}}};var hC={file:e=>({...e,type:"file",_visit:function(t){return hC._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return hC._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return hC._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return hC._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return hC._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return hC._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return hC._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 Tl={primitive:e=>({...e,type:"primitive",_visit:function(t){return Tl._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Tl._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Tl._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Tl._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Tl._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Tl._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Tl._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Tl._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Tl._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Tl._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Tl._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 IZ={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return IZ._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return IZ._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 tp={int:e=>({...e,type:"int",_visit:function(t){return tp._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return tp._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return tp._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return tp._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return tp._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return tp._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return tp._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return tp._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return tp._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return tp._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return tp._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 Cv={};Po(Cv,{AllOfPropertyConflict:()=>V4n,ArraySchema:()=>CVo,ArraySchemaWithExample:()=>oWo,Availability:()=>DUo,Base64WithExample:()=>tWo,BasicSecurityScheme:()=>AUo,BearerSecurityScheme:()=>qUo,BooleanSchema:()=>DVo,BooleanWithExample:()=>rWo,BytesResponse:()=>B4n,CasingOverrides:()=>BUo,CommonProperty:()=>LVo,CommonPropertyWithExample:()=>hWo,CursorPagination:()=>cVo,CustomCodeSample:()=>uVo,CustomCodeSampleLanguage:()=>nVo,CustomCodeSampleSdk:()=>oVo,CustomPagination:()=>fVo,DateWithExample:()=>eWo,DatetimeWithExample:()=>kVo,DiscriminatedOneOfSchema:()=>NVo,DiscriminatedOneOfSchemaWithExample:()=>pWo,DoubleSchema:()=>wVo,DoubleWithExample:()=>XVo,Encoding:()=>SUo,Endpoint:()=>dVo,EndpointExample:()=>R4n,EndpointResponseExample:()=>iVo,EndpointSdkName:()=>qrr,EndpointWithExample:()=>IXp,EnumSchema:()=>j4n,EnumSchemaWithExample:()=>nWo,EnumValue:()=>jEi,ErrorExample:()=>ZUo,FernExample:()=>eVo,FileResponse:()=>T4n,FileSchema:()=>$Uo,FloatWithExample:()=>YVo,FullEndpointExample:()=>sVo,FullExample:()=>Lq,FullObjectExample:()=>LUo,FullOneOfExample:()=>VUo,GlobalHeader:()=>MVo,Header:()=>SEi,HeaderExample:()=>x4n,HeaderSecurityScheme:()=>TUo,HeaderWithExample:()=>MEi,HttpEndpointServer:()=>I4n,HttpError:()=>kUo,HttpErrorWithExample:()=>$Vo,HttpMethod:()=>D4n,IdempotencyHeader:()=>AVo,Int64WithExample:()=>QVo,IntSchema:()=>PVo,IntWithExample:()=>GVo,JsonRequest:()=>KUo,JsonRequestWithExample:()=>VVo,JsonResponse:()=>C4n,JsonResponseWithExample:()=>$4n,KeyValuePair:()=>UUo,LiteralExample:()=>FUo,LiteralSchema:()=>U4n,LiteralSchemaValue:()=>qVo,LongSchema:()=>jVo,MapSchema:()=>BVo,MapSchemaWithExample:()=>uWo,MultipartRequest:()=>q4n,MultipartRequestProperty:()=>JUo,MultipartRequestPropertyEncoding:()=>QUo,MultipartSchema:()=>GUo,NamedFullExample:()=>Crr,Namespace:()=>IUo,NamespaceId:()=>NUo,NullableSchema:()=>zVo,NullableSchemaWithExample:()=>cWo,OauthSecurityScheme:()=>xUo,ObjectProperty:()=>RVo,ObjectPropertyConflictInfo:()=>W4n,ObjectPropertyWithExample:()=>dWo,ObjectSchema:()=>TVo,ObjectSchemaWithExample:()=>lWo,OctetStreamRequest:()=>A4n,OffsetPagination:()=>lVo,OneOfSchema:()=>xVo,OneOfSchemaWithExample:()=>fWo,OpenApiIntermediateRepresentation:()=>CXp,OpenApiSource:()=>mUo,OptionalSchema:()=>IVo,OptionalSchemaWithExample:()=>sWo,Pagination:()=>N4n,PathParameter:()=>E4n,PathParameterExample:()=>tVo,PathParameterWithExample:()=>UVo,PrimitiveExample:()=>S4n,PrimitiveSchema:()=>EEi,PrimitiveSchemaValue:()=>EVo,PrimitiveSchemaValueWithExample:()=>iWo,PrimitiveSchemaWithExample:()=>G4n,PropertyKey:()=>w4n,ProtobufEncoding:()=>wUo,ProtobufSource:()=>PUo,QueryParameter:()=>M4n,QueryParameterExample:()=>z4n,QueryParameterWithExample:()=>H4n,QuerySecurityScheme:()=>CUo,ReferencedSchema:()=>Trr,Request:()=>YUo,RequestWithExample:()=>WVo,Response:()=>XUo,ResponseWithExample:()=>HVo,Schema:()=>wm,SchemaId:()=>zZ,SchemaWithExample:()=>lA,Schemas:()=>mVo,SdkGroup:()=>zUo,SdkGroupInfo:()=>WUo,SdkGroupName:()=>wEi,SecurityScheme:()=>RUo,SecuritySchemeId:()=>MUo,Server:()=>fCa,Source:()=>jUo,StatusCode:()=>Arr,StreamingResponseExample:()=>rVo,StringSchema:()=>SVo,StringSchemaWithExample:()=>ZVo,SupportedSdkLanguage:()=>aVo,Tag:()=>EUo,TagId:()=>xZ,Tags:()=>HUo,TextResponse:()=>DEi,Uint64WithExample:()=>KVo,UintWithExample:()=>JVo,UnDiscriminatedOneOfSchema:()=>FVo,UnDiscriminatedOneOfSchemaWithExample:()=>_Wo,UnknownSchemaWithExample:()=>aWo,Webhook:()=>pVo,WebhookExampleCall:()=>L4n,WebhookHttpMethod:()=>F4n,WebhookWithExample:()=>zXp,WebsocketChannel:()=>OVo,WebsocketHandshake:()=>_Vo,WebsocketHandshakeWithExample:()=>BXp,WebsocketMessageExample:()=>bVo,WebsocketMessageOrigin:()=>hVo,WebsocketMessageSchema:()=>yVo,WebsocketServer:()=>vVo,WebsocketSessionExample:()=>gVo,WithAvailability:()=>Ch,WithDescription:()=>gf,WithEncoding:()=>Dae,WithInline:()=>VE,WithName:()=>z0,WithNamespace:()=>n0,WithSdkGroupName:()=>um,WithSource:()=>Zh,WithStatusCode:()=>KNe,WithTitle:()=>om,commons:()=>$uc,example:()=>Guc,finalIr:()=>Quc,parseIr:()=>Juc});var $uc={};Po($uc,{BasicSecurityScheme:()=>AUo,BearerSecurityScheme:()=>qUo,Encoding:()=>SUo,HeaderSecurityScheme:()=>TUo,Namespace:()=>IUo,NamespaceId:()=>NUo,OauthSecurityScheme:()=>xUo,OpenApiSource:()=>mUo,ProtobufEncoding:()=>wUo,ProtobufSource:()=>PUo,QuerySecurityScheme:()=>CUo,SchemaId:()=>zZ,SdkGroup:()=>zUo,SdkGroupName:()=>wEi,SecurityScheme:()=>RUo,SecuritySchemeId:()=>MUo,Server:()=>fCa,Source:()=>jUo,StatusCode:()=>Arr,Tag:()=>EUo,TagId:()=>xZ,WithAvailability:()=>Ch,WithDescription:()=>gf,WithEncoding:()=>Dae,WithInline:()=>VE,WithName:()=>z0,WithNamespace:()=>n0,WithSdkGroupName:()=>um,WithSource:()=>Zh,WithStatusCode:()=>KNe,WithTitle:()=>om});var Mt={};Po(Mt,{JsonError:()=>O4n,ParseError:()=>m4n,any:()=>gXp,bigint:()=>oXp,boolean:()=>OXp,booleanLiteral:()=>bXp,date:()=>uXp,discriminant:()=>AXp,enum_:()=>bUo,getObjectLikeUtils:()=>LWt,getObjectUtils:()=>tQi,getSchemaUtils:()=>Fq,isProperty:()=>PEi,lazy:()=>sXp,lazyObject:()=>hXp,list:()=>OUo,number:()=>mXp,object:()=>gUo,objectWithoutOptionalProperties:()=>_Xp,optional:()=>Uuc,property:()=>lXp,record:()=>SXp,set:()=>DXp,string:()=>PXp,stringLiteral:()=>vXp,transform:()=>Vuc,undiscriminatedUnion:()=>MXp,union:()=>TXp,unknown:()=>jXp,withParsedProperties:()=>Huc});var Ej={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 cA(e,t){return`Expected ${t}. Received ${CVD(e)}.`}function CVD(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 J9(e){return{...e,json:aXp(e.json),parse:aXp(e.parse)}}function aXp(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(`
|
|
@@ -1973,6 +1973,8 @@ plugins:
|
|
|
1973
1973
|
- local: ["bash", "./protoc-gen-fern"]
|
|
1974
1974
|
out: output
|
|
1975
1975
|
strategy: all
|
|
1976
|
+
include_imports: true
|
|
1977
|
+
include_wkt: true
|
|
1976
1978
|
`,Ub_=`{
|
|
1977
1979
|
"name": "temp-protoc-gen-fern",
|
|
1978
1980
|
"version": "1.0.0",
|
|
@@ -1984,7 +1986,7 @@ plugins:
|
|
|
1984
1986
|
}
|
|
1985
1987
|
`,Vb_=`#!/usr/bin/env bash
|
|
1986
1988
|
fern protoc-gen-fern "$@"
|
|
1987
|
-
`,ubc=()=>({disable:()=>{},enable:()=>{},trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},log:()=>{}});var VYo=class{context;constructor({context:t}){this.context=t}async generate({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:r,local:i}){return i?this.generateLocal({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:r}):this.generateRemote()}async generateLocal({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:r}){let i=await this.setupProtobufGeneratorConfig({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:r});return this.doGenerateLocal({cwd:i})}async setupProtobufGeneratorConfig({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:r}){let i=ll.of((await Wb_.default.dir()).path);await(0,$Mi.cp)(t,i,{recursive:!0}),await(0,$Mi.writeFile)(Ru(i,Na.of("package.json")),Ub_),await WQi(this.context.logger,"npm",["install"],{cwd:i,stdio:"ignore"}),await WQi(this.context.logger,"npm",["install","-g","fern-api@0.64.32-rc0"],{cwd:i,stdio:"ignore"}),await(0,$Mi.writeFile)(Ru(i,Na.of(Rb_)),Lb_);let n=Ru(i,Na.of(Fb_));return await(0,$Mi.writeFile)(n,Vb_),await(0,$Mi.chmod)(n,493),i}async doGenerateLocal({cwd:t}){let r=HQi("which",{cwd:t,logger:ubc()});try{await r(["buf"])}catch{this.context.failAndThrow("Missing required dependency; please install 'buf' to continue (e.g. 'brew install buf').")}let i=HQi("buf",{cwd:t,logger:ubc()});return await i(["config","init"]),await i(["generate"]),Ru(t,Na.of(Nb_))}async generateRemote(){this.context.failAndThrow("Remote Protobuf generation is unimplemented.")}};var fR=class extends bCa{type="oss";allSpecs;specs;sources;loader;constructor({allSpecs:t,specs:r,...i}){super({...i,respectReadonlySchemas:r.every(n=>n.settings?.respectReadonlySchemas),respectNullableSchemas:r.every(n=>n.settings?.respectNullableSchemas),onlyIncludeReferencedSchemas:r.every(n=>n.settings?.onlyIncludeReferencedSchemas),inlinePathParameters:r.every(n=>n.settings?.inlinePathParameters),objectQueryParameters:r.every(n=>n.settings?.objectQueryParameters),useBytesForBinaryResponse:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.useBytesForBinaryResponse),respectForwardCompatibleEnums:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.respectForwardCompatibleEnums),exampleGeneration:r[0]?.settings?.exampleGeneration}),this.specs=r,this.allSpecs=t,this.sources=this.convertSpecsToIdentifiableSources(r),this.loader=new eHt(this.absoluteFilePath)}async getOpenAPIIr({context:t,relativePathToDependency:r},i){let n=await sFe({context:t,specs:this.specs,relativePathToDependency:r});return aQi({context:t,documents:await this.loader.loadDocuments({context:t,specs:n}),options:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.objectQueryParameters,exampleGeneration:i?.exampleGeneration??this.exampleGeneration,useBytesForBinaryResponse:i?.useBytesForBinaryResponse??this.useBytesForBinaryResponse}})}async getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:i,generateV1Examples:n}){let a=await sFe({context:t,specs:this.specs}),u=await this.loader.loadDocuments({context:t,specs:a}),l=this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0;l&&t.logger.trace("Using auth overrides from generators configuration");let d=this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0;d&&t.logger.trace("Using environment overrides from generators configuration");let s=this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0;s&&t.logger.trace("Using global header overrides from generators configuration");let o,c=[];for(let b of u){let g=Ru(this.absoluteFilePath,Na.of(b.source?.file??"")),O=Cie(Xz(),g),m=new cEi({logger:t.logger,relativeFilepathToSpec:O});c.push(m);let w;switch(b.type){case"openapi":{let q=new iza({namespace:b.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:b.value,exampleGenerationArgs:{disabled:!1},errorCollector:m,authOverrides:l,environmentOverrides:d,globalHeaderOverrides:s,enableUniqueErrorsPerEndpoint:i,generateV1Examples:n,settings:SCa({options:b.settings})});w=await new rza({context:q,audiences:r}).convert();break}case"asyncapi":{let q=new tza({namespace:b.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:b.value,exampleGenerationArgs:{disabled:!1},errorCollector:m,enableUniqueErrorsPerEndpoint:i,settings:SCa({options:b.settings}),generateV1Examples:n});w=await new eza({context:q,audiences:r}).convert();break}default:m.collect({message:`Unsupported document type: ${b}`,path:[]});break}let E=UYo({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});w!=null&&(o=o===void 0?w:xGi(o,w,E))}for(let b of this.allSpecs)if(b.type==="openrpc"){let g=b.absoluteFilepath,O=Cie(Xz(),g),m=new cEi({logger:t.logger,relativeFilepathToSpec:O});c.push(m);let w=new aza({namespace:b.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:await obc({context:t,absoluteFilePath:b.absoluteFilepath,absoluteFilePathToOverrides:b.absoluteFilepathToOverrides}),exampleGenerationArgs:{disabled:!1},errorCollector:m,enableUniqueErrorsPerEndpoint:i,generateV1Examples:n,settings:SCa()}),q=await new nza({context:w,audiences:r}).convert(),A=UYo({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});q!=null&&(o=o===void 0?q:xGi(o,q,A))}else if(b.type==="protobuf")try{let O=await new VYo({context:t}).generate({absoluteFilepathToProtobufRoot:b.absoluteFilepathToProtobufRoot,relativeFilepathToProtobufRoot:b.relativeFilepathToProtobufRoot,local:!0}),m=await(0,Hb_.readFile)(O,"utf-8"),w=UYo({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});if(m!=null){let E;try{if(E=Pp.IntermediateRepresentation.parse(JSON.parse(m),{allowUnrecognizedEnumValues:!0,skipValidation:!0}),E.ok)o=o===void 0?E.value:xGi(o,E.value,w);else throw new Error}catch{t.logger.log("error","Failed to parse protobuf IR: ")}}}catch(g){t.logger.log("warn","Failed to parse protobuf IR: "+g)}for(let b of c)if(b.hasErrors()){let g=b.getErrorStats(),O=b.relativeFilepathToSpec?` for ${b.relativeFilepathToSpec}`:"";g.numErrors>0?t.logger.log("error",`API validation${O} completed with ${g.numErrors} errors and ${g.numWarnings} warnings.`):g.numWarnings>0?t.logger.log("warn",`API validation${O} completed with ${g.numWarnings} warnings.`):t.logger.log("info",`All checks passed when parsing OpenAPI${O}.`),t.logger.log("info",""),await b.logErrors({logWarnings:!1})}if(o===void 0)throw new Error("Failed to generate intermediate representation");return o}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new nMe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion,sources:this.sources})}getAbsoluteFilePaths(){return[this.absoluteFilePath,...this.allSpecs.flatMap(t=>[t.type==="protobuf"?t.absoluteFilepathToProtobufTarget:t.absoluteFilepath,t.absoluteFilepathToOverrides]).filter(yv)]}getSources(){return this.sources}convertSpecsToIdentifiableSources(t){let r=new Set,i=[];return t.reduce((n,a)=>{let u=a.type==="protobuf"?a.absoluteFilepathToProtobufRoot:a.absoluteFilepath;return r.has(u)||(r.add(u),n.push({type:a.type,id:lae(),absoluteFilePath:u})),n},i)}};var $b_={None:"none",Header:"header"};var fXo={};Po(fXo,{ConjureAliasDeclaration:()=>KYo,ConjureArgument:()=>sXo,ConjureArgumentWithParamType:()=>uXo,ConjureAuthDefinition:()=>l5n,ConjureAuthDefinitionType:()=>aXo,ConjureDefinitions:()=>iXo,ConjureEndpointDefinition:()=>cXo,ConjureEnumDeclaration:()=>tXo,ConjureEnumVariant:()=>eXo,ConjureEnumWithDocs:()=>kYo,ConjureObjectDeclaration:()=>ZYo,ConjureParamType:()=>oXo,ConjurePrimitive:()=>JYo,ConjureService:()=>lXo,ConjureServiceName:()=>QYo,ConjureType:()=>JMi,ConjureTypeDeclaration:()=>rXo,ConjureTypeReference:()=>KMi,ConjureTypeWithDocs:()=>YYo,ConjureTypes:()=>nXo,ConjureUnionDeclaration:()=>XYo,DefinitionFile:()=>g0_,WithDocs:()=>air,commons:()=>dbc,conjure:()=>pbc,services:()=>_bc,types:()=>hbc});var dbc={};Po(dbc,{WithDocs:()=>air});var up={};Po(up,{JsonError:()=>u5n,ParseError:()=>s5n,any:()=>o0_,bigint:()=>Qb_,boolean:()=>u0_,booleanLiteral:()=>a0_,date:()=>Jb_,discriminant:()=>y0_,enum_:()=>HYo,getObjectLikeUtils:()=>iHt,getObjectUtils:()=>iJi,getSchemaUtils:()=>Vq,isProperty:()=>QMi,lazy:()=>Kb_,lazyObject:()=>r0_,list:()=>GYo,number:()=>s0_,object:()=>$Yo,objectWithoutOptionalProperties:()=>t0_,optional:()=>sbc,property:()=>Xb_,record:()=>d0_,set:()=>p0_,string:()=>c0_,stringLiteral:()=>n0_,transform:()=>cbc,undiscriminatedUnion:()=>h0_,union:()=>b0_,unknown:()=>l0_,withParsedProperties:()=>fbc});var Aj={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 pA(e,t){return`Expected ${t}. Received ${k1E(e)}.`}function k1E(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 tL(e){return{...e,json:Gb_(e.json),parse:Gb_(e.parse)}}function Gb_(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(`
|
|
1989
|
+
`,ubc=()=>({disable:()=>{},enable:()=>{},trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},log:()=>{}});var VYo=class{context;constructor({context:t}){this.context=t}async generate({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:r,local:i}){return i?this.generateLocal({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:r}):this.generateRemote()}async generateLocal({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:r}){let i=await this.setupProtobufGeneratorConfig({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:r});return this.doGenerateLocal({cwd:i})}async setupProtobufGeneratorConfig({absoluteFilepathToProtobufRoot:t,relativeFilepathToProtobufRoot:r}){let i=ll.of((await Wb_.default.dir()).path);await(0,$Mi.cp)(t,i,{recursive:!0}),await(0,$Mi.writeFile)(Ru(i,Na.of("package.json")),Ub_),await WQi(this.context.logger,"npm",["install"],{cwd:i,stdio:"ignore"}),await WQi(this.context.logger,"npm",["install","-g","fern-api"],{cwd:i,stdio:"ignore"}),await(0,$Mi.writeFile)(Ru(i,Na.of(Rb_)),Lb_);let n=Ru(i,Na.of(Fb_));return await(0,$Mi.writeFile)(n,Vb_),await(0,$Mi.chmod)(n,493),i}async doGenerateLocal({cwd:t}){let r=HQi("which",{cwd:t,logger:ubc()});try{await r(["buf"])}catch{this.context.failAndThrow("Missing required dependency; please install 'buf' to continue (e.g. 'brew install buf').")}let i=HQi("buf",{cwd:t,logger:ubc()});return await i(["config","init"]),await i(["generate"]),Ru(t,Na.of(Nb_))}async generateRemote(){this.context.failAndThrow("Remote Protobuf generation is unimplemented.")}};var fR=class extends bCa{type="oss";allSpecs;specs;sources;loader;constructor({allSpecs:t,specs:r,...i}){super({...i,respectReadonlySchemas:r.every(n=>n.settings?.respectReadonlySchemas),respectNullableSchemas:r.every(n=>n.settings?.respectNullableSchemas),onlyIncludeReferencedSchemas:r.every(n=>n.settings?.onlyIncludeReferencedSchemas),inlinePathParameters:r.every(n=>n.settings?.inlinePathParameters),objectQueryParameters:r.every(n=>n.settings?.objectQueryParameters),useBytesForBinaryResponse:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.useBytesForBinaryResponse),respectForwardCompatibleEnums:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.respectForwardCompatibleEnums),exampleGeneration:r[0]?.settings?.exampleGeneration}),this.specs=r,this.allSpecs=t,this.sources=this.convertSpecsToIdentifiableSources(r),this.loader=new eHt(this.absoluteFilePath)}async getOpenAPIIr({context:t,relativePathToDependency:r},i){let n=await sFe({context:t,specs:this.specs,relativePathToDependency:r});return aQi({context:t,documents:await this.loader.loadDocuments({context:t,specs:n}),options:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.objectQueryParameters,exampleGeneration:i?.exampleGeneration??this.exampleGeneration,useBytesForBinaryResponse:i?.useBytesForBinaryResponse??this.useBytesForBinaryResponse}})}async getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:i,generateV1Examples:n}){let a=await sFe({context:t,specs:this.specs}),u=await this.loader.loadDocuments({context:t,specs:a}),l=this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0;l&&t.logger.trace("Using auth overrides from generators configuration");let d=this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0;d&&t.logger.trace("Using environment overrides from generators configuration");let s=this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0;s&&t.logger.trace("Using global header overrides from generators configuration");let o,c=[];for(let b of u){let g=Ru(this.absoluteFilePath,Na.of(b.source?.file??"")),O=Cie(Xz(),g),m=new cEi({logger:t.logger,relativeFilepathToSpec:O});c.push(m);let w;switch(b.type){case"openapi":{let q=new iza({namespace:b.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:b.value,exampleGenerationArgs:{disabled:!1},errorCollector:m,authOverrides:l,environmentOverrides:d,globalHeaderOverrides:s,enableUniqueErrorsPerEndpoint:i,generateV1Examples:n,settings:SCa({options:b.settings})});w=await new rza({context:q,audiences:r}).convert();break}case"asyncapi":{let q=new tza({namespace:b.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:b.value,exampleGenerationArgs:{disabled:!1},errorCollector:m,enableUniqueErrorsPerEndpoint:i,settings:SCa({options:b.settings}),generateV1Examples:n});w=await new eza({context:q,audiences:r}).convert();break}default:m.collect({message:`Unsupported document type: ${b}`,path:[]});break}let E=UYo({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});w!=null&&(o=o===void 0?w:xGi(o,w,E))}for(let b of this.allSpecs)if(b.type==="openrpc"){let g=b.absoluteFilepath,O=Cie(Xz(),g),m=new cEi({logger:t.logger,relativeFilepathToSpec:O});c.push(m);let w=new aza({namespace:b.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:await obc({context:t,absoluteFilePath:b.absoluteFilepath,absoluteFilePathToOverrides:b.absoluteFilepathToOverrides}),exampleGenerationArgs:{disabled:!1},errorCollector:m,enableUniqueErrorsPerEndpoint:i,generateV1Examples:n,settings:SCa()}),q=await new nza({context:w,audiences:r}).convert(),A=UYo({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});q!=null&&(o=o===void 0?q:xGi(o,q,A))}else if(b.type==="protobuf")try{let O=await new VYo({context:t}).generate({absoluteFilepathToProtobufRoot:b.absoluteFilepathToProtobufRoot,relativeFilepathToProtobufRoot:b.relativeFilepathToProtobufRoot,local:!0}),m=await(0,Hb_.readFile)(O,"utf-8"),w=UYo({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});if(m!=null){let E;try{if(E=Pp.IntermediateRepresentation.parse(JSON.parse(m),{allowUnrecognizedEnumValues:!0,skipValidation:!0}),E.ok)o=o===void 0?E.value:xGi(o,E.value,w);else throw new Error}catch{t.logger.log("error","Failed to parse protobuf IR: ")}}}catch(g){t.logger.log("warn","Failed to parse protobuf IR: "+g)}for(let b of c)if(b.hasErrors()){let g=b.getErrorStats(),O=b.relativeFilepathToSpec?` for ${b.relativeFilepathToSpec}`:"";g.numErrors>0?t.logger.log("error",`API validation${O} completed with ${g.numErrors} errors and ${g.numWarnings} warnings.`):g.numWarnings>0?t.logger.log("warn",`API validation${O} completed with ${g.numWarnings} warnings.`):t.logger.log("info",`All checks passed when parsing OpenAPI${O}.`),t.logger.log("info",""),await b.logErrors({logWarnings:!1})}if(o===void 0)throw new Error("Failed to generate intermediate representation");return o}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new nMe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion,sources:this.sources})}getAbsoluteFilePaths(){return[this.absoluteFilePath,...this.allSpecs.flatMap(t=>[t.type==="protobuf"?t.absoluteFilepathToProtobufTarget:t.absoluteFilepath,t.absoluteFilepathToOverrides]).filter(yv)]}getSources(){return this.sources}convertSpecsToIdentifiableSources(t){let r=new Set,i=[];return t.reduce((n,a)=>{let u=a.type==="protobuf"?a.absoluteFilepathToProtobufRoot:a.absoluteFilepath;return r.has(u)||(r.add(u),n.push({type:a.type,id:lae(),absoluteFilePath:u})),n},i)}};var $b_={None:"none",Header:"header"};var fXo={};Po(fXo,{ConjureAliasDeclaration:()=>KYo,ConjureArgument:()=>sXo,ConjureArgumentWithParamType:()=>uXo,ConjureAuthDefinition:()=>l5n,ConjureAuthDefinitionType:()=>aXo,ConjureDefinitions:()=>iXo,ConjureEndpointDefinition:()=>cXo,ConjureEnumDeclaration:()=>tXo,ConjureEnumVariant:()=>eXo,ConjureEnumWithDocs:()=>kYo,ConjureObjectDeclaration:()=>ZYo,ConjureParamType:()=>oXo,ConjurePrimitive:()=>JYo,ConjureService:()=>lXo,ConjureServiceName:()=>QYo,ConjureType:()=>JMi,ConjureTypeDeclaration:()=>rXo,ConjureTypeReference:()=>KMi,ConjureTypeWithDocs:()=>YYo,ConjureTypes:()=>nXo,ConjureUnionDeclaration:()=>XYo,DefinitionFile:()=>g0_,WithDocs:()=>air,commons:()=>dbc,conjure:()=>pbc,services:()=>_bc,types:()=>hbc});var dbc={};Po(dbc,{WithDocs:()=>air});var up={};Po(up,{JsonError:()=>u5n,ParseError:()=>s5n,any:()=>o0_,bigint:()=>Qb_,boolean:()=>u0_,booleanLiteral:()=>a0_,date:()=>Jb_,discriminant:()=>y0_,enum_:()=>HYo,getObjectLikeUtils:()=>iHt,getObjectUtils:()=>iJi,getSchemaUtils:()=>Vq,isProperty:()=>QMi,lazy:()=>Kb_,lazyObject:()=>r0_,list:()=>GYo,number:()=>s0_,object:()=>$Yo,objectWithoutOptionalProperties:()=>t0_,optional:()=>sbc,property:()=>Xb_,record:()=>d0_,set:()=>p0_,string:()=>c0_,stringLiteral:()=>n0_,transform:()=>cbc,undiscriminatedUnion:()=>h0_,union:()=>b0_,unknown:()=>l0_,withParsedProperties:()=>fbc});var Aj={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 pA(e,t){return`Expected ${t}. Received ${k1E(e)}.`}function k1E(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 tL(e){return{...e,json:Gb_(e.json),parse:Gb_(e.parse)}}function Gb_(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(`
|
|
1988
1990
|
`)),{ok:!0,value:t}):i}}function WYo(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var u5n=class e extends Error{errors;constructor(t){super(t.map(WYo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var s5n=class e extends Error{errors;constructor(t){super(t.map(WYo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function Vq(e){return{optional:()=>sbc(e),transform:t=>cbc(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new s5n(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new u5n(i.errors)}}}function sbc(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:()=>Aj.OPTIONAL};return{...t,...Vq(t)}}function cbc(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,...Vq(r)}}function Qb_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:pA(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:pA(t,"bigint")}]},getType:()=>Aj.BIGINT};return{...tL(e),...Vq(e)}}var eSE=/^([+-]?\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 Jb_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:pA(t,"string")}]}:eSE.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:pA(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:pA(t,"Date object")}]},getType:()=>Aj.DATE};return{...tL(e),...Vq(e)}}function oJ(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...tL(r),...Vq(r)}}}function HYo(e){let t=new Set(e);return oJ(Aj.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:pA(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:pA(i,"enum")}]}:{ok:!0,value:i})()}function Kb_(e){let t=lbc(e);return{...t,...Vq(t)}}function lbc(e){return{parse:(t,r)=>c5n(e).parse(t,r),json:(t,r)=>c5n(e).json(t,r),getType:()=>c5n(e).getType()}}function c5n(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function oza(e){return Object.entries(e)}function uza(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function GMi(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 sza(e){return Object.keys(e)}function Yb_(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function iHt(e){return{withParsedProperties:t=>fbc(e,t)}}function fbc(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let u=Object.entries(t).reduce((l,[d,s])=>({...l,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...u}}},json:(i,n)=>{if(!GMi(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:pA(i,"object")}]};let a=new Set(Object.keys(t)),u=uza(i,Object.keys(i).filter(l=>!a.has(l)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...Vq(r),...iHt(r)}}function Xb_(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function QMi(e){return e.isProperty}function $Yo(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>QMi(i)?i.rawKey:r),_getParsedProperties:()=>sza(e),parse:(r,i)=>{let n={},a=[];for(let[u,l]of oza(e)){let d=QMi(l)?l.rawKey:u,s=QMi(l)?l.valueSchema:l,o={rawKey:d,parsedKey:u,valueSchema:s};n[d]=o,e0_(s)&&a.push(d)}return Zb_({value:r,requiredKeys:a,getProperty:u=>{let l=n[u];if(l!=null)return{transformedKey:l.parsedKey,transform:d=>l.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 oza(e)){let l=QMi(u)?u.valueSchema:u;e0_(l)&&n.push(a)}return Zb_({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return QMi(u)?{transformedKey:u.rawKey,transform:l=>u.valueSchema.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:l=>u.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>Aj.OBJECT};return{...tL(t),...Vq(t),...iHt(t),...iJi(t)}}function Zb_({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!GMi(e))return{ok:!1,errors:[{path:a,message:pA(e,"object")}]};let u=new Set(t),l=[],d={};for(let[s,o]of Object.entries(e)){let c=r(s);if(c!=null){u.delete(s);let b=c.transform(o);b.ok?d[c.transformedKey]=b.value:(d[s]=o,l.push(...b.errors))}else switch(i){case"fail":l.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=o;break}}return l.push(...t.filter(s=>u.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),l.length===0||n?{ok:!0,value:d}:{ok:!1,errors:l}}function iJi(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>kb_({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>kb_({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>Aj.OBJECT};return{...r,...Vq(r),...iHt(r),...iJi(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:()=>Aj.OBJECT};return{...t,...Vq(t),...iHt(t),...iJi(t)}}}}function kb_({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=Yb_(sza(t),s=>n.has(s)),l=r(uza(t,u)),d=i(uza(t,a));return l.ok&&d.ok?{ok:!0,value:{...l.value,...d.value}}:{ok:!1,errors:[...l.ok?[]:l.errors,...d.ok?[]:d.errors]}}function e0_(e){return!tSE(e)}function tSE(e){switch(e.getType()){case Aj.ANY:case Aj.UNKNOWN:case Aj.OPTIONAL:return!0;default:return!1}}function t0_(e){return $Yo(e)}function r0_(e){let t={...lbc(e),_getRawProperties:()=>c5n(e)._getRawProperties(),_getParsedProperties:()=>c5n(e)._getParsedProperties()};return{...t,...Vq(t),...iHt(t),...iJi(t)}}function GYo(e){let t={parse:(r,i)=>i0_(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>i0_(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>Aj.LIST};return{...tL(t),...Vq(t)}}function i0_(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:pA(e,"list"),path:[]}]}}function n0_(e){return oJ(Aj.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:pA(r,`"${e}"`)}]})()}function a0_(e){return oJ(Aj.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:pA(r,`${e.toString()}`)}]})()}var o0_=oJ(Aj.ANY,e=>({ok:!0,value:e}));var u0_=oJ(Aj.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:pA(e,"boolean")}]});var s0_=oJ(Aj.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:pA(e,"number")}]});var c0_=oJ(Aj.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:pA(e,"string")}]});var l0_=oJ(Aj.UNKNOWN,e=>({ok:!0,value:e}));function d0_(e,t){let r={parse:(i,n)=>f0_({value:i,isKeyNumeric:e.getType()===Aj.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)=>f0_({value:i,isKeyNumeric:e.getType()===Aj.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:()=>Aj.RECORD};return{...tL(r),...Vq(r)}}function f0_({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return GMi(e)?oza(e).reduce((a,[u,l])=>{if(l==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),c=i(l,s);if(d.ok&&o.ok&&c.ok)return{ok:!0,value:{...d.value,[o.value]:c.value}};let b=[];return d.ok||b.push(...d.errors),o.ok||b.push(...o.errors),c.ok||b.push(...c.errors),{ok:!1,errors:b}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:pA(e,"object")}]}}function p0_(e){let t=GYo(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:pA(i,"Set")}]},getType:()=>Aj.SET};return{...tL(r),...Vq(r)}}function h0_(e){let t={parse:(r,i)=>_0_((n,a)=>n.parse(r,a),e,i),json:(r,i)=>_0_((n,a)=>n.json(r,a),e,i),getType:()=>Aj.UNDISCRIMINATED_UNION};return{...tL(t),...Vq(t)}}function _0_(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 l of u.errors)i.push({path:l.path,message:`[Variant ${n}] ${l.message}`})}return{ok:!1,errors:i}}function y0_(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function b0_(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=HYo(sza(t)),a={parse:(u,l)=>v0_({value:u,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),json:(u,l)=>v0_({value:u,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),getType:()=>Aj.UNION};return{...tL(a),...Vq(a),...iHt(a)}}function v0_({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:l=[]}){if(!GMi(e))return{ok:!1,errors:[{path:l,message:pA(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:l,message:`Missing discriminant ("${t}")`}]};let o=i(d);if(!o.ok)return{ok:!1,errors:o.errors};let c=n(o.value);if(c==null)return a?{ok:!0,value:{[r]:o.value,...s}}:{ok:!1,errors:[{path:[...l,t],message:"Unexpected discriminant value"}]};let b=u(s,c);return b.ok?{ok:!0,value:{[r]:d,...b.value}}:b}var air=up.objectWithoutOptionalProperties({docs:up.string().optional()});var pbc={};Po(pbc,{ConjureServiceName:()=>QYo,DefinitionFile:()=>g0_});var QYo=up.string();var JYo=up.enum_(["rid","string","safelong","integer","double","boolean"]);var JMi=up.undiscriminatedUnion([JYo,up.string()]);var KYo=up.objectWithoutOptionalProperties({alias:JMi,docs:up.string().optional()});var YYo=up.objectWithoutOptionalProperties({type:JMi,docs:up.string().optional()});var KMi=up.undiscriminatedUnion([JMi,YYo]);var XYo=up.objectWithoutOptionalProperties({union:up.record(up.string(),KMi)});var ZYo=up.objectWithoutOptionalProperties({fields:up.record(up.string(),KMi)});var kYo=up.objectWithoutOptionalProperties({value:up.string()}).extend(air);var eXo=up.undiscriminatedUnion([up.string(),kYo]);var tXo=up.objectWithoutOptionalProperties({values:up.list(eXo)});var rXo=up.undiscriminatedUnion([KYo,XYo,ZYo,tXo]);var iXo=up.objectWithoutOptionalProperties({objects:up.record(up.string(),rXo).optional()});var nXo=up.objectWithoutOptionalProperties({conjureImports:up.property("conjure-imports",up.record(up.string(),up.string()).optional()),definitions:iXo.optional()});var aXo=up.enum_(["none","header"]);var l5n=up.undiscriminatedUnion([aXo,up.string()]);var oXo=up.enum_(["path","query","body"]);var uXo=up.objectWithoutOptionalProperties({paramType:up.property("param-type",oXo),type:up.string()}).extend(air);var sXo=up.undiscriminatedUnion([up.string(),uXo]);var cXo=up.objectWithoutOptionalProperties({http:up.string(),auth:l5n.optional(),args:up.record(up.string(),sXo).optional(),returns:KMi.optional()}).extend(air);var lXo=up.objectWithoutOptionalProperties({name:up.string().optional(),package:up.string().optional(),basePath:up.property("base-path",up.string().optional()),defaultAuth:up.property("default-auth",l5n.optional()),endpoints:up.record(up.string(),cXo).optional()}).extend(air);var g0_=up.objectWithoutOptionalProperties({types:nXo.optional(),services:up.record(QYo,lXo).optional()});var _bc={};Po(_bc,{ConjureArgument:()=>sXo,ConjureArgumentWithParamType:()=>uXo,ConjureAuthDefinition:()=>l5n,ConjureAuthDefinitionType:()=>aXo,ConjureEndpointDefinition:()=>cXo,ConjureParamType:()=>oXo,ConjureService:()=>lXo});var hbc={};Po(hbc,{ConjureAliasDeclaration:()=>KYo,ConjureDefinitions:()=>iXo,ConjureEnumDeclaration:()=>tXo,ConjureEnumVariant:()=>eXo,ConjureEnumWithDocs:()=>kYo,ConjureObjectDeclaration:()=>ZYo,ConjurePrimitive:()=>JYo,ConjureType:()=>JMi,ConjureTypeDeclaration:()=>rXo,ConjureTypeReference:()=>KMi,ConjureTypeWithDocs:()=>YYo,ConjureTypes:()=>nXo,ConjureUnionDeclaration:()=>XYo});var O0_=require("fs/promises");async function m0_(e,t){let r=[];for(let i of await cxe(e,t))r.push(await rSE({relativeFilepath:Bq(e,i),absoluteFilepath:i}));return r}async function rSE({relativeFilepath:e,absoluteFilepath:t}){let r=(await(0,O0_.readFile)(t)).toString().replaceAll(/: rid(?:$|\s)/g,`: string
|
|
1989
1991
|
`).replaceAll("<rid>","<string>").replaceAll("rid>","string>").replaceAll(": safelong",": long").replaceAll("<safelong>","<long>").replaceAll("safelong>","long>").replaceAll(": any",": unknown").replaceAll("<any>","<unknown>").replaceAll("any>","unknown>");return{relativeFilepath:e,absoluteFilepath:t,fileContents:fXo.DefinitionFile.parseOrThrow(md.load(r),{unrecognizedObjectKeys:"passthrough",allowUnrecognizedEnumValues:!0,allowUnrecognizedUnionMembers:!0})}}function P0_(e,t){if(iSE(e))return t.alias(e);if(nSE(e))return t.enum(e);if(aSE(e))return t.object(e);if(oSE(e))return t.union(e);jo(e)}function iSE(e){return e?.alias!=null}function nSE(e){return e?.values!=null}function aSE(e){return e?.fields!=null}function oSE(e){return e?.union!=null}var cza=class extends uCa{fernDefinitionBuilder=new eQi(!1);conjureFilepathToFernFilepath={};async import({absolutePathToConjureFolder:t,authOverrides:r,environmentOverrides:i,globalHeaderOverrides:n}){if(r!=null){for(let[a,u]of Object.entries(r["auth-schemes"]??{}))this.fernDefinitionBuilder.addAuthScheme({name:a,schema:u});r.auth!=null&&this.fernDefinitionBuilder.setAuth(r.auth)}if(i!=null){for(let[a,u]of Object.entries(i.environments??{}))this.fernDefinitionBuilder.addEnvironment({name:a,schema:u});i["default-environment"]!=null&&this.fernDefinitionBuilder.setDefaultEnvironment(i["default-environment"]),i["default-url"]!=null&&this.fernDefinitionBuilder.setDefaultUrl(i["default-url"])}return await j0_(t,(a,u,l)=>{for(let[o,c]of Object.entries(l.services??{})){let b=Lyo({value:o,suffix:"Service"});this.conjureFilepathToFernFilepath[u]=Na.of(`${b}/__package__.yml`);return}let s=ORs(u)?.split(".")[0];s!=null&&(this.conjureFilepathToFernFilepath[u]=Na.of(`${s}/__package__.yml`))}),await j0_(t,(a,u,l)=>{if(l.services==null||Object.keys(l.services??{}).length===0){let d=this.conjureFilepathToFernFilepath[u];if(d==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${u}`);for(let[s,o]of Object.entries(l.types?.conjureImports??{})){let c=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Na.of(o)});this.fernDefinitionBuilder.addImport({file:d,fileToImport:Na.of(c),alias:s})}this.importAllTypes({conjureFile:l,fernFilePath:d});return}for(let[d,s]of Object.entries(l.services)){let o=Lyo({value:d,suffix:"Service"}),c=Na.of(`${o}/__package__.yml`),b={};s.basePath!=null&&(b["base-path"]=s.basePath),s.docs!=null&&(b.docs=s.docs),this.fernDefinitionBuilder.setServiceInfo(c,b),this.importAllTypes({conjureFile:l,fernFilePath:c});for(let[g,O]of Object.entries(l.types?.conjureImports??{})){let m=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:Na.of(O)});this.fernDefinitionBuilder.addImport({file:c,fileToImport:Na.of(m),alias:g})}for(let[g,O]of Object.entries(s.endpoints??{})){let m=aIs(O.http);if(m.type==="failure"){this.context?.logger.error(`Failed to parse ${O.http}. Skipping.`);continue}let E={auth:(O.auth??s.defaultAuth)!==$b_.None,path:m.path,method:m.method,response:O.returns==="binary"?"file":O.returns};O.docs!=null&&(E.docs=O.docs);let q={};if(O.args!=null)for(let A of m.pathParameters){let D=O.args[A];if(D==null)throw new Error(`Failed to find path parameter ${A} in ${O.http}`);q[A]=typeof D=="string"?D:{type:D.type}}Object.entries(q).length>0&&(E["path-parameters"]=q);for(let[A,D]of Object.entries(O.args??{}))if(q[A]==null)if(typeof D=="string")E.request?typeof E.request=="string"&&(E.request={body:E.request}):E.request={},E.request.body=D==="binary"?"bytes":D;else switch(D.paramType){case"body":E.request={body:D.type==="binary"?"bytes":D.type};break;case"query":E.request==null?E.request={"query-parameters":{[A]:D.type}}:typeof E.request!="string"&&E.request?.["query-parameters"]==null?E.request["query-parameters"]={[A]:D.type}:typeof E.request!="string"&&E.request?.["query-parameters"]!=null&&(E.request["query-parameters"][A]=D.type)}E.request!=null&&typeof E.request!="string"&&E.request?.["query-parameters"]!=null&&(E.request.name=`${g}Request`),this.fernDefinitionBuilder.addEndpoint(c,{name:g,schema:E,source:void 0})}}}),this.fernDefinitionBuilder.build()}importAllTypes({conjureFile:t,fernFilePath:r}){for(let[i,n]of Object.entries(t.types?.definitions?.objects??{}))P0_(n,{alias:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{type:a.alias,docs:a.docs}})},object:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{properties:a.fields}})},enum:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{enum:a.values}})},union:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{union:Object.fromEntries(Object.entries(a.union).map(([u,l])=>[u,{type:typeof l=="string"?l:l.type,docs:typeof l=="string"?void 0:l.docs,key:u}]))}})}})}getFernFileToImport({absoluteFilePathToConjureFile:t,importFilePath:r,absoluteFilePathToConjureFolder:i}){let n=Ru(Cd(t),Na.of(r)),a=Cie(i,n),u=this.conjureFilepathToFernFilepath[a];if(u==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${a}`);return u}};async function j0_(e,t){for(let r of await m0_(e,"{yml,yaml}"))await t(r.absoluteFilepath,r.relativeFilepath,r.fileContents)}function w0_(e,t){return fd(e,t)}var dXo=class extends RWt{type="conjure";absolutePathToConjureFolder;constructor({relativePathToConjureDirectory:t,...r}){super(r),this.absolutePathToConjureFolder=Ru(r.absoluteFilePath,t)}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new nMe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion,sources:void 0})}async getDefinition({context:t},r){let n=await new cza(t).import({absolutePathToConjureFolder:this.absolutePathToConjureFolder,authOverrides:this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0,environmentOverrides:this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:ll.of("/DUMMY_PATH"),rootApiFile:{defaultUrl:n.rootApiFile["default-url"],contents:n.rootApiFile,rawContents:md.dump(n.rootApiFile)},namedDefinitionFiles:{...w0_(n.definitionFiles,a=>({absoluteFilepath:ll.of("/DUMMY_PATH"),rawContents:md.dump(a),contents:a})),[Na.of(TS)]:{absoluteFilepath:ll.of("/DUMMY_PATH"),rawContents:md.dump(n.packageMarkerFile),contents:n.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}getAbsoluteFilePaths(){return[this.absolutePathToConjureFolder]}};function ybc(e,t){for(let[r,i]of FF(e.failures))uSE({relativeFilepath:r,failure:i,logger:t})}function uSE({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case zP.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case zP.FILE_READ:r.error("Failed to open file: "+e);break;case zP.FILE_MISSING:r.error("Missing file: "+e);break;case zP.FILE_PARSE:t.error instanceof Ija?r.error(QNe({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case zP.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of sSE(i))r.error(QNe({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case zP.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case zP.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${Dvo}: `+t.dependencyName);break;case zP.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case zP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case zP.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(QNe({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(i=>i!=="")]}));break;default:jo(t)}}function sSE(e){switch(e.code){case ql.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Ss.underline(e.expected)} but received ${Ss.underline(e.received)}`}];case ql.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Ss.underline(t)}`}));case ql.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Ss.underline(t)).join(", ")}`}];case ql.invalid_union:case ql.invalid_arguments:case ql.invalid_return_type:case ql.invalid_date:case ql.invalid_string:case ql.too_small:case ql.too_big:case ql.invalid_intersection_types:case ql.not_multiple_of:case ql.custom:default:return[{title:e.message}]}}var S0_=require("fs/promises");async function D0_(e,t){let r=[];for(let i of await cxe(e,t))r.push(await cSE({relativeFilepath:Bq(e,i),absoluteFilepath:i}));return r}async function cSE({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,S0_.readFile)(t)).toString()}}async function E0_({absolutePathToWorkspace:e}){let t=Ru(e,Na.of(Dbd));if(!await mf(t))return;let i=await D0_(t,"{md,mdx}");return{files:await Promise.all(i.map(n=>({absoluteFilepath:n.absoluteFilepath,contents:n.fileContents})))}}async function vbc({absolutePathToWorkspace:e,namespace:t,definitions:r}){let i=[];for(let n of r){let a=n.overrides!=null?Ru(e,Na.of(n.overrides)):void 0;if(n.schema.type==="protobuf"){let l=Na.of(n.schema.root),d=Ru(e,l);if(!await mf(d))return{didSucceed:!1,failures:{[Na.of(n.schema.root)]:{type:zP.FILE_MISSING}}};let s=n.schema.target.length===0?void 0:Ru(e,Na.of(n.schema.target));if(s!=null&&!await mf(s))return{didSucceed:!1,failures:{[Na.of(n.schema.target)]:{type:zP.FILE_MISSING}}};i.push({type:"protobuf",absoluteFilepathToProtobufRoot:d,absoluteFilepathToProtobufTarget:s,absoluteFilepathToOverrides:a,relativeFilepathToProtobufRoot:l,generateLocally:n.schema.localGeneration,settings:{audiences:n.audiences??[],useTitlesAsName:n.settings?.shouldUseTitleAsName??!0,shouldUseUndiscriminatedUnionsWithLiterals:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,shouldUseIdiomaticRequestNames:n.settings?.shouldUseIdiomaticRequestNames??!1,optionalAdditionalProperties:n.settings?.shouldUseOptionalAdditionalProperties??!0,coerceEnumsToLiterals:n.settings?.coerceEnumsToLiterals??!0,objectQueryParameters:n.settings?.objectQueryParameters??!1,respectReadonlySchemas:n.settings?.respectReadonlySchemas??!1,respectNullableSchemas:n.settings?.respectNullableSchemas??!1,onlyIncludeReferencedSchemas:n.settings?.onlyIncludeReferencedSchemas??!1,inlinePathParameters:n.settings?.inlinePathParameters??!1,disableExamples:!1,discriminatedUnionV2:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,preserveSchemaIds:!1,asyncApiNaming:n.settings?.asyncApiMessageNaming??"v1",filter:n.settings?.filter,exampleGeneration:void 0,defaultFormParameterEncoding:n.settings?.defaultFormParameterEncoding,useBytesForBinaryResponse:n.settings?.useBytesForBinaryResponse??!1,respectForwardCompatibleEnums:n.settings?.respectForwardCompatibleEnums??!1,additionalPropertiesDefaultsTo:n.settings?.additionalPropertiesDefaultsTo??!1,typeDatesAsStrings:n.settings?.typeDatesAsStrings??!0,preserveSingleSchemaOneOf:n.settings?.preserveSingleSchemaOneOf??!1}});continue}if(n.schema.type==="openrpc"){let l=Na.of(n.schema.path),d=Ru(e,l);i.push({type:"openrpc",absoluteFilepath:d,absoluteFilepathToOverrides:a,namespace:t});continue}let u=Ru(e,Na.of(n.schema.path));if(!await mf(u))return{didSucceed:!1,failures:{[Na.of(n.schema.path)]:{type:zP.FILE_MISSING}}};if(n.overrides!=null&&a!=null&&!await mf(a))return{didSucceed:!1,failures:{[Na.of(n.overrides)]:{type:zP.FILE_MISSING}}};i.push({type:"openapi",absoluteFilepath:u,absoluteFilepathToOverrides:a,settings:{audiences:n.audiences??[],useTitlesAsName:n.settings?.shouldUseTitleAsName??!0,shouldUseUndiscriminatedUnionsWithLiterals:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,shouldUseIdiomaticRequestNames:n.settings?.shouldUseIdiomaticRequestNames??!1,optionalAdditionalProperties:n.settings?.shouldUseOptionalAdditionalProperties??!0,coerceEnumsToLiterals:n.settings?.coerceEnumsToLiterals??!0,objectQueryParameters:n.settings?.objectQueryParameters??!1,respectReadonlySchemas:n.settings?.respectReadonlySchemas??!1,respectNullableSchemas:n.settings?.respectNullableSchemas??!1,onlyIncludeReferencedSchemas:n.settings?.onlyIncludeReferencedSchemas??!1,inlinePathParameters:n.settings?.inlinePathParameters??!1,disableExamples:!1,discriminatedUnionV2:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,preserveSchemaIds:!1,asyncApiNaming:n.settings?.asyncApiMessageNaming??"v1",filter:n.settings?.filter,exampleGeneration:n.settings?.exampleGeneration,defaultFormParameterEncoding:n.settings?.defaultFormParameterEncoding,useBytesForBinaryResponse:n.settings?.useBytesForBinaryResponse??!1,respectForwardCompatibleEnums:n.settings?.respectForwardCompatibleEnums??!1,additionalPropertiesDefaultsTo:n.settings?.additionalPropertiesDefaultsTo??!1,typeDatesAsStrings:n.settings?.typeDatesAsStrings??!0,preserveSingleSchemaOneOf:n.settings?.preserveSingleSchemaOneOf??!1},source:{type:"openapi",file:u},namespace:t})}return i}async function lza({absolutePathToWorkspace:e,context:t,cliVersion:r,workspaceName:i}){let n=await AVt({absolutePathToWorkspace:e,context:t}),a;try{a=await E0_({absolutePathToWorkspace:e})}catch{}if(n?.api!=null&&n?.api.type==="conjure")return{didSucceed:!0,workspace:new dXo({workspaceName:i,absoluteFilePath:e,generatorsConfiguration:n,changelog:a,cliVersion:r,context:t,relativePathToConjureDirectory:Na.of(n.api.pathToConjureDefinition)})};if(n?.api!=null&&(n.api.type==="singleNamespace"&&n.api.definitions.length>0||n.api.type==="multiNamespace")){let u=[];if(n.api.type==="singleNamespace"){let l=await vbc({absolutePathToWorkspace:e,namespace:void 0,definitions:n.api.definitions});if(!Array.isArray(l))return l;u.push(...l)}else{for(let[l,d]of Object.entries(n.api.definitions)){let s=await vbc({absolutePathToWorkspace:e,namespace:l,definitions:d});if(!Array.isArray(s))return s;u.push(...s)}if(n.api.rootDefinitions!=null){let l=await vbc({absolutePathToWorkspace:e,namespace:void 0,definitions:n.api.rootDefinitions});if(!Array.isArray(l))return l;u.push(...l)}}return{didSucceed:!0,workspace:new fR({specs:u.filter(l=>!(l.type==="openrpc"||l.type==="protobuf")),allSpecs:u,workspaceName:i,absoluteFilePath:e,generatorsConfiguration:n,changelog:a,cliVersion:r})}}return await mf(Ru(e,Na.of(i9)))?{didSucceed:!0,workspace:new nir({absoluteFilePath:e,generatorsConfiguration:n,workspaceName:i,changelog:a,context:t,cliVersion:r,loadAPIWorkspace:lza})}:{didSucceed:!1,failures:{[Na.of(Svo)]:{type:zP.MISCONFIGURED_DIRECTORY}}}}var M0_=require("fs/promises");var bbc={};Po(bbc,{additionalProperties:()=>pSE,default:()=>hSE,definitions:()=>_SE,properties:()=>fSE,required:()=>dSE,type:()=>lSE});var lSE="object",fSE={instances:{type:"array",items:{$ref:"#/definitions/docs.DocsInstance"}},title:{oneOf:[{type:"string"},{type:"null"}]},analytics:{oneOf:[{$ref:"#/definitions/docs.AnalyticsConfig"},{type:"null"}]},announcement:{oneOf:[{$ref:"#/definitions/docs.AnnouncementConfig"},{type:"null"}]},roles:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.RoleId"}},{type:"null"}]},tabs:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/docs.TabConfig"}},{type:"null"}]},versions:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.VersionConfig"}},{type:"null"}]},products:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ProductConfig"}},{type:"null"}]},"landing-page":{oneOf:[{$ref:"#/definitions/docs.PageConfiguration"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/docs.NavigationConfig"},{type:"null"}]},"navbar-links":{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.NavbarLink"}},{type:"null"}]},"footer-links":{oneOf:[{$ref:"#/definitions/docs.FooterLinksConfig"},{type:"null"}]},experimental:{oneOf:[{$ref:"#/definitions/docs.ExperimentalConfig"},{type:"null"}]},"default-language":{oneOf:[{$ref:"#/definitions/docs.ProgrammingLanguage"},{type:"null"}]},"ai-chat":{oneOf:[{$ref:"#/definitions/docs.AIChatConfig"},{type:"null"}]},"ai-search":{oneOf:[{$ref:"#/definitions/docs.AIChatConfig"},{type:"null"}]},metadata:{oneOf:[{$ref:"#/definitions/docs.MetadataConfig"},{type:"null"}]},redirects:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.RedirectConfig"}},{type:"null"}]},logo:{oneOf:[{$ref:"#/definitions/docs.LogoConfiguration"},{type:"null"}]},favicon:{oneOf:[{type:"string"},{type:"null"}]},"background-image":{oneOf:[{$ref:"#/definitions/docs.BackgroundImageConfiguration"},{type:"null"}]},colors:{oneOf:[{$ref:"#/definitions/docs.ColorsConfiguration"},{type:"null"}]},typography:{oneOf:[{$ref:"#/definitions/docs.DocsTypographyConfig"},{type:"null"}]},layout:{oneOf:[{$ref:"#/definitions/docs.LayoutConfig"},{type:"null"}]},integrations:{oneOf:[{$ref:"#/definitions/docs.IntegrationsConfig"},{type:"null"}]},css:{oneOf:[{$ref:"#/definitions/docs.CssConfig"},{type:"null"}]},js:{oneOf:[{$ref:"#/definitions/docs.JsConfig"},{type:"null"}]}},dSE=["instances"],pSE=!1,_SE={"docs.CustomDomain":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"docs.GithubEditThisPageConfig":{type:"object",properties:{host:{oneOf:[{type:"string"},{type:"null"}]},owner:{type:"string"},repo:{type:"string"},branch:{oneOf:[{type:"string"},{type:"null"}]}},required:["owner","repo"],additionalProperties:!1},"docs.EditThisPageConfig":{type:"object",properties:{github:{oneOf:[{$ref:"#/definitions/docs.GithubEditThisPageConfig"},{type:"null"}]}},additionalProperties:!1},"docs.DocsInstance":{type:"object",properties:{url:{type:"string"},"custom-domain":{oneOf:[{$ref:"#/definitions/docs.CustomDomain"},{type:"null"}]},private:{oneOf:[{type:"boolean"},{type:"null"}]},"edit-this-page":{oneOf:[{$ref:"#/definitions/docs.EditThisPageConfig"},{type:"null"}]}},required:["url"],additionalProperties:!1},"docs.SegmentConfig":{type:"object",properties:{"write-key":{type:"string"}},required:["write-key"],additionalProperties:!1},"docs.FullStoryAnalyticsConfig":{type:"object",properties:{"org-id":{type:"string"}},required:["org-id"],additionalProperties:!1},"docs.IntercomConfig":{type:"object",properties:{"app-id":{type:"string"},"api-base":{oneOf:[{type:"string"},{type:"null"}]}},required:["app-id"],additionalProperties:!1},"docs.PostHogConfig":{type:"object",properties:{"api-key":{type:"string"},endpoint:{oneOf:[{type:"string"},{type:"null"}]}},required:["api-key"],additionalProperties:!1},"docs.GTMConfig":{type:"object",properties:{"container-id":{type:"string"}},required:["container-id"],additionalProperties:!1},"docs.GoogleAnalytics4Config":{type:"object",properties:{"measurement-id":{type:"string"}},required:["measurement-id"],additionalProperties:!1},"docs.AnalyticsConfig":{type:"object",properties:{segment:{oneOf:[{$ref:"#/definitions/docs.SegmentConfig"},{type:"null"}]},fullstory:{oneOf:[{$ref:"#/definitions/docs.FullStoryAnalyticsConfig"},{type:"null"}]},intercom:{oneOf:[{$ref:"#/definitions/docs.IntercomConfig"},{type:"null"}]},posthog:{oneOf:[{$ref:"#/definitions/docs.PostHogConfig"},{type:"null"}]},gtm:{oneOf:[{$ref:"#/definitions/docs.GTMConfig"},{type:"null"}]},ga4:{oneOf:[{$ref:"#/definitions/docs.GoogleAnalytics4Config"},{type:"null"}]}},additionalProperties:!1},"docs.AnnouncementConfig":{type:"object",properties:{message:{type:"string"}},required:["message"],additionalProperties:!1},"docs.RoleId":{type:"string"},"docs.Role":{anyOf:[{$ref:"#/definitions/docs.RoleId"},{type:"array",items:{$ref:"#/definitions/docs.RoleId"}}]},"docs.FeatureFlag":{type:"object",properties:{flag:{type:"string"},"fallback-value":{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},match:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]}},required:["flag"],additionalProperties:!1},"docs.FeatureFlagConfiguration":{anyOf:[{type:"string",description:"The name of the feature flag, We assume that it is a boolean feature flag that needs to be evaluated to true."},{$ref:"#/definitions/docs.FeatureFlag",description:"A single feature flag with a configurable name, fallback value, and match value. Especially useful for non boolean feature flags."},{type:"array",items:{$ref:"#/definitions/docs.FeatureFlag"},description:"A list of feature flags. If any of the feature flags are satisfied, we will show all content."}]},"docs.ChangelogFolderRelativePath":{type:"string"},"docs.TabConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},href:{oneOf:[{type:"string"},{type:"null"}]},changelog:{oneOf:[{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},{type:"null"}]}},required:["display-name"],additionalProperties:!1},"docs.VersionAvailability":{type:"string",enum:["deprecated","ga","stable","beta"]},"docs.VersionConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},path:{type:"string"},slug:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.VersionAvailability"},{type:"null"}]}},required:["display-name","path"],additionalProperties:!1},"docs.ProductConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},path:{type:"string"},subtitle:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},image:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},versions:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.VersionConfig"}},{type:"null"}]}},required:["display-name","path"],additionalProperties:!1},"docs.PageConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},page:{type:"string"},path:{type:"string"},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},noindex:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["page","path"],additionalProperties:!1},"docs.SectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},path:{oneOf:[{type:"string"},{type:"null"}]},contents:{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},collapsed:{oneOf:[{type:"boolean"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["section","contents"],additionalProperties:!1},"docs.AudienceId":{type:"string"},"docs.VersionedSnippetLanguageConfiguration":{type:"object",properties:{version:{type:"string"},package:{type:"string"}},required:["version","package"],additionalProperties:!1},"docs.SnippetLanguageConfiguration":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.VersionedSnippetLanguageConfiguration"}]},"docs.SnippetsConfiguration":{type:"object",properties:{python:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},typescript:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},go:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},java:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},ruby:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},csharp:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundButtonSettings":{type:"object",properties:{href:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundSettings":{type:"object",properties:{environments:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},button:{oneOf:[{$ref:"#/definitions/docs.PlaygroundButtonSettings"},{type:"null"}]},oauth:{oneOf:[{type:"boolean"},{type:"null"}]},"limit-websocket-messages-per-connection":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfigurationWithOptions":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},title:{oneOf:[{type:"string"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfiguration":{anyOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{$ref:"#/definitions/docs.ApiReferencePackageConfigurationWithOptions"}]},"docs.ApiReferenceSectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},"referenced-packages":{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["section"],additionalProperties:!1},"docs.ApiReferenceEndpointConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},endpoint:{type:"string"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"docs.LinkConfiguration":{type:"object",properties:{link:{type:"string"},href:{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]}},required:["link","href"],additionalProperties:!1},"docs.ApiReferenceLayoutItem":{anyOf:[{type:"string",description:"This should be either an endpoint, websocket, webhook, or subpackage ID"},{type:"object",additionalProperties:{$ref:"#/definitions/docs.ApiReferencePackageConfiguration"},description:"Keyed by subpackage name, this object allows you to group endpoints and pages together."},{$ref:"#/definitions/docs.ApiReferenceSectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceEndpointConfiguration"},{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"}]},"docs.ApiReferenceConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},api:{type:"string"},"api-name":{oneOf:[{type:"string"},{type:"null"}]},openrpc:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.AudienceId"}},{type:"null"}]},"display-errors":{oneOf:[{type:"boolean"},{type:"null"}]},snippets:{oneOf:[{$ref:"#/definitions/docs.SnippetsConfiguration"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},alphabetized:{oneOf:[{type:"boolean"},{type:"null"}]},flattened:{oneOf:[{type:"boolean"},{type:"null"}]},paginated:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["api"],additionalProperties:!1},"docs.ChangelogConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},changelog:{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["changelog"],additionalProperties:!1},"docs.NavigationItem":{anyOf:[{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.SectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"},{$ref:"#/definitions/docs.ChangelogConfiguration"}]},"docs.UntabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},"docs.TabId":{type:"string"},"docs.TabbedNavigationItem":{type:"object",properties:{tab:{$ref:"#/definitions/docs.TabId"},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},{type:"null"}]}},required:["tab"],additionalProperties:!1},"docs.TabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.TabbedNavigationItem"}},"docs.NavigationConfig":{anyOf:[{$ref:"#/definitions/docs.UntabbedNavigationConfig"},{$ref:"#/definitions/docs.TabbedNavigationConfig"}]},"docs.NavbarGithubConfig":{type:"string"},"docs.NavbarLink":{type:"object",properties:{type:{type:"string",enum:["filled","outlined","minimal","github","primary","secondary"]}},oneOf:[{properties:{type:{const:"filled"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"outlined"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"minimal"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"github"},value:{$ref:"#/definitions/docs.NavbarGithubConfig"}},required:["type"]},{properties:{type:{const:"primary"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"secondary"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]}]},"docs.FooterLinksConfig":{type:"object",properties:{github:{oneOf:[{type:"string"},{type:"null"}]},twitter:{oneOf:[{type:"string"},{type:"null"}]},x:{oneOf:[{type:"string"},{type:"null"}]},linkedin:{oneOf:[{type:"string"},{type:"null"}]},youtube:{oneOf:[{type:"string"},{type:"null"}]},instagram:{oneOf:[{type:"string"},{type:"null"}]},facebook:{oneOf:[{type:"string"},{type:"null"}]},discord:{oneOf:[{type:"string"},{type:"null"}]},slack:{oneOf:[{type:"string"},{type:"null"}]},hackernews:{oneOf:[{type:"string"},{type:"null"}]},medium:{oneOf:[{type:"string"},{type:"null"}]},website:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.ExperimentalConfig":{type:"object",properties:{"mdx-components":{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"disable-stream-toggle":{oneOf:[{type:"boolean"},{type:"null"}]},"openapi-parser-v2":{oneOf:[{type:"boolean"},{type:"null"}]},"openapi-parser-v3":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"docs.ProgrammingLanguage":{type:"string",enum:["typescript","javascript","python","java","go","ruby","csharp","nodets","nodejs","dotnet","curl","jvm","ts","js"]},"docs.AIChatModel":{type:"string",enum:["claude-3.5","claude-3.7","claude-4","command-a"]},"docs.AIChatConfig":{type:"object",properties:{model:{oneOf:[{$ref:"#/definitions/docs.AIChatModel"},{type:"null"}]},"system-prompt":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.TwitterCardSetting":{type:"string",enum:["summary","summary_large_image","app","player"]},"docs.MetadataConfig":{type:"object",properties:{"og:site_name":{oneOf:[{type:"string"},{type:"null"}]},"og:title":{oneOf:[{type:"string"},{type:"null"}]},"og:description":{oneOf:[{type:"string"},{type:"null"}]},"og:url":{oneOf:[{type:"string"},{type:"null"}]},"og:image":{oneOf:[{type:"string"},{type:"null"}]},"og:image:width":{oneOf:[{type:"number"},{type:"null"}]},"og:image:height":{oneOf:[{type:"number"},{type:"null"}]},"og:locale":{oneOf:[{type:"string"},{type:"null"}]},"og:logo":{oneOf:[{type:"string"},{type:"null"}]},"twitter:title":{oneOf:[{type:"string"},{type:"null"}]},"twitter:description":{oneOf:[{type:"string"},{type:"null"}]},"twitter:handle":{oneOf:[{type:"string"},{type:"null"}]},"twitter:image":{oneOf:[{type:"string"},{type:"null"}]},"twitter:site":{oneOf:[{type:"string"},{type:"null"}]},"twitter:url":{oneOf:[{type:"string"},{type:"null"}]},"twitter:card":{oneOf:[{$ref:"#/definitions/docs.TwitterCardSetting"},{type:"null"}]}},additionalProperties:!1},"docs.RedirectConfig":{type:"object",properties:{source:{type:"string"},destination:{type:"string"},permanent:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["source","destination"],additionalProperties:!1},"docs.LogoConfiguration":{type:"object",properties:{dark:{oneOf:[{type:"string"},{type:"null"}]},light:{oneOf:[{type:"string"},{type:"null"}]},height:{oneOf:[{type:"number"},{type:"null"}]},href:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.BackgroundImageThemedConfig":{type:"object",properties:{dark:{oneOf:[{type:"string"},{type:"null"}]},light:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.BackgroundImageConfiguration":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.BackgroundImageThemedConfig"}]},"docs.ColorThemedConfig":{type:"object",properties:{dark:{oneOf:[{type:"string"},{type:"null"}]},light:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.ColorConfig":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.ColorThemedConfig"}]},"docs.ColorsConfiguration":{type:"object",properties:{"accent-primary":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},accentPrimary:{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},background:{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},border:{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},"sidebar-background":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},"header-background":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},"card-background":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]}},additionalProperties:!1},"docs.FontWeight":{anyOf:[{type:"string"},{type:"integer"}]},"docs.FontStyle":{type:"string",enum:["normal","italic"]},"docs.FontConfigVariant":{type:"object",properties:{path:{type:"string"},weight:{oneOf:[{$ref:"#/definitions/docs.FontWeight"},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/docs.FontStyle"},{type:"null"}]}},required:["path"],additionalProperties:!1},"docs.FontConfigPath":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.FontConfigVariant"}]},"docs.FontDisplay":{type:"string",enum:["auto","block","swap","fallback","optional"]},"docs.FontConfig":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},path:{oneOf:[{type:"string"},{type:"null"}]},weight:{oneOf:[{$ref:"#/definitions/docs.FontWeight"},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/docs.FontStyle"},{type:"null"}]},paths:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.FontConfigPath"}},{type:"null"}]},display:{oneOf:[{$ref:"#/definitions/docs.FontDisplay"},{type:"null"}]},fallback:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"font-variation-settings":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.DocsTypographyConfig":{type:"object",properties:{headingsFont:{oneOf:[{$ref:"#/definitions/docs.FontConfig"},{type:"null"}]},bodyFont:{oneOf:[{$ref:"#/definitions/docs.FontConfig"},{type:"null"}]},codeFont:{oneOf:[{$ref:"#/definitions/docs.FontConfig"},{type:"null"}]}},additionalProperties:!1},"docs.SearchbarPlacement":{type:"string",enum:["header","header-tabs","sidebar"]},"docs.TabsPlacement":{type:"string",enum:["header","sidebar"]},"docs.ContentAlignment":{type:"string",enum:["center","left"]},"docs.HeaderPosition":{type:"string",enum:["fixed","static"]},"docs.LayoutConfig":{type:"object",properties:{"page-width":{oneOf:[{type:"string"},{type:"null"}]},"content-width":{oneOf:[{type:"string"},{type:"null"}]},"sidebar-width":{oneOf:[{type:"string"},{type:"null"}]},"header-height":{oneOf:[{type:"string"},{type:"null"}]},"searchbar-placement":{oneOf:[{$ref:"#/definitions/docs.SearchbarPlacement"},{type:"null"}]},"tabs-placement":{oneOf:[{$ref:"#/definitions/docs.TabsPlacement"},{type:"null"}]},"content-alignment":{oneOf:[{$ref:"#/definitions/docs.ContentAlignment"},{type:"null"}]},"header-position":{oneOf:[{$ref:"#/definitions/docs.HeaderPosition"},{type:"null"}]},"disable-header":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"docs.IntegrationsConfig":{type:"object",properties:{intercom:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.CssConfig":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"docs.JsScriptStrategy":{type:"string",enum:["beforeInteractive","afterInteractive","lazyOnload"]},"docs.JsRemoteConfig":{type:"object",properties:{url:{type:"string"},strategy:{oneOf:[{$ref:"#/definitions/docs.JsScriptStrategy"},{type:"null"}]}},required:["url"],additionalProperties:!1},"docs.JsFileConfigSettings":{type:"object",properties:{path:{type:"string"},strategy:{oneOf:[{$ref:"#/definitions/docs.JsScriptStrategy"},{type:"null"}]}},required:["path"],additionalProperties:!1},"docs.JsFileConfig":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.JsFileConfigSettings"}]},"docs.JsConfigOptions":{anyOf:[{$ref:"#/definitions/docs.JsRemoteConfig"},{$ref:"#/definitions/docs.JsFileConfig"}]},"docs.JsConfig":{anyOf:[{$ref:"#/definitions/docs.JsConfigOptions"},{type:"array",items:{$ref:"#/definitions/docs.JsConfigOptions"}}]}},hSE={type:lSE,properties:fSE,required:dSE,additionalProperties:pSE,definitions:_SE};async function gbc({fernDirectory:e,context:t}){let r=Ru(e,Na.of(VUt));if(!await mf(r))return;let i=await ySE({absolutePathToDocsDefinition:e,context:t});if(i!=null)return{type:"docs",absoluteFilePath:e,config:i,workspaceName:void 0,absoluteFilepathToDocsConfig:Ru(e,Na.of(VUt))}}async function ySE({absolutePathToDocsDefinition:e,context:t}){if(!await mf(e))return;let r=Ru(e,Na.of(VUt));return await vSE({absolutePathOfConfiguration:r,context:t})}async function vSE({absolutePathOfConfiguration:e,context:t}){let r=await(0,M0_.readFile)(e),i=md.load(r.toString()),n=UUt(i,bbc);if(n.success)return Tie.RawSchemas.Serializer.DocsConfiguration.parseOrThrow(i);throw new Error(`Failed to parse docs.yml because of ${n.error?.message??"Unknown error"}`)}async function Obc({context:e,nameOverride:t,...r}){let i=await ZUt(t);return i==null?e.failAndThrow(`Directory "${t??HV}" not found.`):await q0_({absolutePathToFernDirectory:i,context:e,nameOverride:t,...r})}async function q0_({absolutePathToFernDirectory:e,cliName:t,cliVersion:r,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n,context:a}){let u=[];return(await mf(Ru(e,Na.of(dji)))||await mf(Ru(e,Na.of(i9)))||await mf(Ru(e,Na.of(VF)))||await mf(Ru(e,Na.of(Svo)))||await mf(Ru(e,Na.of(Ebd))))&&(u=await T0_({cliName:t,fernDirectory:e,cliVersion:r,context:a,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n})),{config:await ali({directory:e,context:a}),apiWorkspaces:u,docsWorkspaces:await gbc({fernDirectory:e,context:a}),loadAPIWorkspace:l=>l==null?u[0]:u.find(d=>d.workspaceName===l)}}async function T0_({cliName:e,fernDirectory:t,context:r,cliVersion:i,commandLineApiWorkspace:n,defaultToAllApiWorkspaces:a}){let u=Ru(t,Na.of(dji));if(await mf(u)){let o=(await(0,A0_.readdir)(u,{withFileTypes:!0})).reduce((g,O)=>(O.isDirectory()&&g.push(O.name),g),[]);if(n!=null){if(!o.includes(n))return r.failAndThrow("API does not exist: "+n)}else{if(o.length===0)return r.failAndThrow("No APIs found.");if(o.length>1&&!a){let g=`There are multiple workspaces. You must specify one with --api:
|
|
1990
1992
|
`,O=Math.max(...o.map(m=>m.length));return g+=o.map(m=>{let w=`${e} ${process.argv.slice(2).join(" ")} --api ${m}`;return` \u203A ${Ss.bold(m.padEnd(O))} ${Ss.dim(w)}`}).join(`
|
|
@@ -2039,7 +2041,7 @@ ${a}]`:`[${e.join(u)}]`},bko=(e,t,r)=>`let ${e} = ${ROc(t,r)}`,ROc=(e,t,r)=>{swi
|
|
|
2039
2041
|
`)}];if(t["base-properties"]!=null){let A=Object.fromEntries(Object.entries(c).filter(([C])=>t["base-properties"]?.[C]!=null)),D=sKi({typeName:e,typeNameForBreadcrumb:e,rawObject:{properties:t["base-properties"]},file:a,example:A,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d+1});if(D.length>0)return D}let g=typeof b=="string"?b:b.type;if(typeof g!="string")return nI_(c);let O=i.resolveType({type:g,file:a});if(O==null)return[];if(O._type==="named"&&xS(O.declaration)){let A=Object.fromEntries(Object.entries(c).filter(([D])=>t["base-properties"]?.[D]==null));return sKi({typeName:e,typeNameForBreadcrumb:e,rawObject:O.declaration,file:O.file,example:A,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d+1})}let m=typeof b!="string"&&typeof b.key=="string"?b.key:void 0;if(m==null)return[];let{[m]:w,...E}=c,q=[];return w==null?q.push({message:`Missing property "${m}"`}):q.push(...sL({rawTypeReference:g,example:w,typeResolver:i,exampleResolver:n,file:a,workspace:u,breadcrumbs:l,depth:d+1})),q.push(...nI_(E)),q}function nI_(e){return Object.keys(e).map(t=>({severity:"fatal",message:`Unexpected property "${t}"`}))}function leu({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:d}){return n3(t,{alias:s=>XB_({rawAlias:s,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:d}),enum:s=>ZB_({rawEnum:s,example:a,breadcrumbs:l}),object:s=>sKi({typeName:e,typeNameForBreadcrumb:e,rawObject:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d}),discriminatedUnion:s=>aI_({typeName:e,rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d}),undiscriminatedUnion:s=>kB_({rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d})})}var _I_=/^([+-]?\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)?)?)?)?$/,r6E=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,i6E=/^\d{4}-\d{2}-\d{2}$/,n6E=128;function sL({rawTypeReference:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l}){if(l>n6E)return[{message:"Example is too deeply nested. This may indicate a circular reference."}];if(typeof t=="string"&&t.startsWith(YZt)){let d=r.resolveType({type:e,file:n});if(d==null)return[];let s=i.parseExampleReference(t);if(s==null)return[];let o=r.resolveNamedType({referenceToNamedType:s.rawTypeReference,file:n});return o==null?[]:o9n({expected:d,actual:o})?[]:[{message:`Expected example to be: ${e}. Example is ${t}.`}]}return oWi({type:e,_default:void 0,validation:void 0,visitor:{primitive:d=>a6E({primitiveType:d,example:t}),named:d=>{let s=r.getDeclarationOfNamedType({referenceToNamedType:d,file:n});return s==null?[]:leu({typeName:s.typeName,typeDeclaration:s.declaration,file:s.file,example:t,typeResolver:r,exampleResolver:i,workspace:a,breadcrumbs:u,depth:l+1})},map:({keyType:d,valueType:s})=>Gj(t)?Object.entries(t).flatMap(([o,c])=>[...sL({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1}),...sL({rawTypeReference:s,example:c,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1})]):gFe(t,"a map"),list:d=>Array.isArray(t)?t.flatMap((s,o)=>sL({rawTypeReference:d,example:s,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${o}`],depth:l+1})):gFe(t,"a list"),set:d=>{if(!Array.isArray(t))return gFe(t,"a list");let s=IBs(t);return s.length>0?[{severity:"fatal",message:`Set has duplicate elements:
|
|
2040
2042
|
`+s.map(o=>` - ${JSON.stringify(o)}`).join(`
|
|
2041
2043
|
`)}]:t.flatMap((o,c)=>sL({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${c}`],depth:l+1}))},optional:d=>t==null?[]:sL({rawTypeReference:d,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l+1}),nullable:d=>t==null?[]:sL({rawTypeReference:d,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l+1}),unknown:()=>[],literal:d=>{switch(d.type){case"boolean":return OMe(s=>s===d.boolean,d.boolean.toString())(t);case"string":return OMe(s=>s===d.string,`"${d.string}"`)(t);default:jo(d)}}}})}function a6E({primitiveType:e,example:t}){return e.v2!=null?Ed._visit(e.v2,{integer:r=>o6E({example:t,rules:r.validation}),long:()=>cI_(t),uint:()=>oI_(t),uint64:()=>uI_(t),double:r=>u6E({example:t,rules:r.validation}),float:()=>sI_(t),boolean:()=>lI_(t),string:r=>s6E({example:t,rules:r.validation}),uuid:()=>fI_(t),date:()=>pI_(t),dateTime:()=>dI_(t),base64:()=>a9n(t),bigInteger:()=>a9n(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):Uh._visit(e.v1,{integer:()=>hI_(t),long:()=>cI_(t),uint:()=>oI_(t),uint64:()=>uI_(t),double:()=>yI_(t),float:()=>sI_(t),boolean:()=>lI_(t),string:()=>a9n(t),uuid:()=>fI_(t),dateTime:()=>dI_(t),date:()=>pI_(t),base64:()=>a9n(t),bigInteger:()=>a9n(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function o6E({example:e,rules:t}){let r=hI_(e);if(r.length>0||t==null)return r;let i=e;return t.min!=null&&(t.exclusiveMin&&i<=t.min||!t.exclusiveMin&&i<t.min)?[{message:`Expected integer to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&i>=t.max||!t.exclusiveMax&&i>t.max)?[{message:`Expected integer to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&i%t.multipleOf!==0?[{message:`Expected integer to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function u6E({example:e,rules:t}){let r=yI_(e);if(r.length>0||t==null)return r;let i=e;return t.min!=null&&(t.exclusiveMin&&i<=t.min||!t.exclusiveMin&&i<t.min)?[{message:`Expected double to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&i>=t.max||!t.exclusiveMax&&i>t.max)?[{message:`Expected double to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&i%t.multipleOf!==0?[{message:`Expected double to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function s6E({example:e,rules:t}){let r=a9n(e);if(r.length>0||t==null)return r;let i=e;return t.minLength!=null&&i.length<t.minLength?[{message:`Expected string length to be greater than or equal to ${t.minLength}. Example is ${e}, which is of length ${i.length}.`}]:t.maxLength!=null&&i.length>t.maxLength?[{message:`Expected string length to be less than or equal to ${t.maxLength}. Example is ${e}, which is of length ${i.length}.`}]:t.pattern!=null&&!new RegExp(t.pattern).test(i)?[{message:`Expected string to match pattern ${t.pattern}. Example is ${e}.`}]:[]}var a9n=OMe(e=>typeof e=="string","a string"),hI_=OMe(e=>Number.isInteger(e),"an integer"),oI_=OMe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),uI_=OMe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),sI_=OMe(e=>typeof e=="number","a float"),yI_=OMe(e=>typeof e=="number","a double"),cI_=OMe(e=>Number.isInteger(e),"an integer"),lI_=OMe(e=>typeof e=="boolean","a boolean"),fI_=OMe(e=>typeof e=="string"&&r6E.test(e),"a UUID"),dI_=OMe(e=>typeof e=="string"&&_I_.test(e),"an ISO 8601 timestamp"),pI_=OMe(e=>typeof e=="string"&&i6E.test(e)&&_I_.test(e),"a date");function OMe(e,t){return r=>e(r)?[]:gFe(r,t)}function o9n({expected:e,actual:t}){if(e._type==="unknown")return!0;if(e._type==="primitive")return t._type==="primitive"&&e.primitive.v1===t.primitive.v1;if(e._type==="container")switch(e.container._type){case"list":case"set":return t._type==="container"&&t.container._type===e.container._type&&o9n({expected:e.container.itemType,actual:t.container.itemType});case"optional":return o9n({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="optional"?t.container.itemType:t});case"nullable":return o9n({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="nullable"?t.container.itemType:t});case"map":return t._type==="container"&&t.container._type===e.container._type&&o9n({expected:e.container.keyType,actual:t.container.keyType})&&o9n({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:c6E({expected:e.container.literal,actual:t.container.literal});default:jo(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;jo(e)}function c6E({expected:e,actual:t}){switch(e.type){case"boolean":return t.type==="boolean"?e.boolean===t.boolean:!1;case"string":return t.type==="string"?e.string===t.string:!1;default:jo(e)}}function feu({_enum:e,file:t}){let r=e.enum.map(n=>({...lJ(n),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof n=="string"?n:n.value,name:u9n(n).name,opts:{casingOverrides:typeof n!="string"?n.casing:void 0}})})),i;if(e.default!=null&&(i=r.find(n=>n.name.wireValue===e.default),i==null))throw new Error(`Default value ${e.default} not found in enum values`);return{default:i,values:r}}function vI_(e,t){let r=t.enum.find(i=>typeof i=="string"?!1:i.value===e);return{name:typeof r=="string"?e:r?.name??e,wasExplicitlySet:!1}}function u9n(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function Cjc({typeName:e,typeDeclaration:t,example:r,typeResolver:i,exampleResolver:n,fileContainingType:a,fileContainingExample:u,workspace:l}){return n3(t,{alias:d=>Rw.alias({value:GE({example:r,rawTypeBeingExemplified:typeof d=="string"?d:d.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l})}),object:d=>bI_({typeName:e,rawObject:d,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l}),discriminatedUnion:d=>{let s=cKi(d);if(!Gj(r))throw new Error("Example is not an object");let o=r[s];if(o==null)throw new Error("Example is missing discriminant: "+s);if(typeof o!="string")throw new Error("Discriminant value is not a string");let c=d.union[o];if(c==null)throw new Error(`${o} is not one of the specified discriminant values.`);let b=typeof c=="string"?c:typeof c.type=="string"?c.type:void 0;return Rw.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:bAi(d).name,wireValue:s}),singleUnionType:f6E({rawValueType:b,rawSingleUnionType:c,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,example:r,discriminant:s,discriminantValueForExample:o,workspace:l})})},enum:d=>{if(typeof r!="string"){let s=d.enum.map(o=>typeof o=="string"?o:o.value).join(", ");throw new Error(`Expected one of ${s}. Received ${r}`)}return Rw.enum({value:u.casingsGenerator.generateNameAndWireValue({name:vI_(r,d).name,wireValue:r})})},undiscriminatedUnion:d=>{for(let[c,b]of d.union.entries())if(sL({rawTypeReference:typeof b=="string"?b:b.type,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:l,breadcrumbs:[],depth:0}).length===0)return Rw.undiscriminatedUnion({index:c,singleUnionType:GE({example:r,rawTypeBeingExemplified:typeof b=="string"?b:b.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l})});let o=d.union.map(c=>typeof c=="string"?c:c.type).join(", ");throw new Error(`Expected one of ${o}. Received ${r}`)}})}function GE({example:e,fileContainingExample:t,rawTypeBeingExemplified:r,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}){let{resolvedExample:l,file:d}=a.resolveExampleOrThrow({example:e,file:t}),s=a.resolveAllReferencesInExampleOrThrow({example:e,file:t}).resolvedExample;return{shape:oWi({type:r,_default:void 0,validation:void 0,visitor:{primitive:c=>l6E({example:l,typeBeingExemplified:c.v1}),map:({keyType:c,valueType:b})=>{if(!Gj(l))throw new Error("Example is not an object");return Vh.container(mm.map({map:Object.entries(l).map(([g,O])=>({key:GE({example:g,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}),value:GE({example:O,fileContainingExample:d,rawTypeBeingExemplified:b,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})})),keyType:i.parseTypeReference(c),valueType:i.parseTypeReference(b)}))},list:c=>{if(!Array.isArray(l))throw new Error("Example is not a list");return Vh.container(mm.list({list:l.map(b=>GE({example:b,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})),itemType:i.parseTypeReference(c)}))},set:c=>{if(!Array.isArray(l))throw new Error("Example is not a list");return Vh.container(mm.set({set:l.map(b=>GE({example:b,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})),itemType:i.parseTypeReference(c)}))},optional:c=>Vh.container(mm.optional({optional:l!=null?GE({example:l,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}):void 0,valueType:i.parseTypeReference(c)})),nullable:c=>Vh.container(mm.nullable({nullable:l!=null?GE({example:l,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}):void 0,valueType:i.parseTypeReference(c)})),literal:c=>{switch(c.type){case"boolean":return Vh.container(mm.literal({literal:Fd.boolean(c.boolean)}));case"string":return Vh.container(mm.literal({literal:Fd.string({original:c.string})}));default:jo(c)}},named:c=>{let b=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:r,file:i}),g=i.parseTypeReference(c);if(g.type!=="named")throw new Error("Type reference is not to a named type.");let O={typeId:g.typeId,fernFilepath:g.fernFilepath,name:g.name,displayName:g.displayName};return Vh.named({typeName:O,shape:Cjc({typeName:O,typeDeclaration:b.declaration,fileContainingType:b.file,fileContainingExample:d,example:l,typeResolver:n,exampleResolver:a,workspace:u})})},unknown:()=>Vh.unknown(s)}}),jsonExample:s}}function l6E({example:e,typeBeingExemplified:t}){return Uh._visit(t,{string:()=>typeof e!="string"?Vh.primitive(Fd.string({original:ky.STRING})):Vh.primitive(Fd.string({original:e})),dateTime:()=>typeof e!="string"?Vh.primitive(Fd.string({original:ky.DATE_TIME})):Vh.primitive(Fd.datetime({datetime:new Date(e),raw:e})),date:()=>typeof e!="string"?Vh.primitive(Fd.string({original:ky.DATE})):Vh.primitive(Fd.date(e)),base64:()=>typeof e!="string"?Vh.primitive(Fd.string({original:ky.BASE64})):Vh.primitive(Fd.string({original:e})),uint:()=>typeof e!="number"?Vh.primitive(Fd.uint(ky.UINT)):Vh.primitive(Fd.uint(e)),uint64:()=>typeof e!="number"?Vh.primitive(Fd.uint64(ky.UINT64)):Vh.primitive(Fd.uint64(e)),integer:()=>typeof e!="number"?Vh.primitive(Fd.integer(ky.INT)):Vh.primitive(Fd.integer(e)),float:()=>typeof e!="number"?Vh.primitive(Fd.float(ky.FLOAT)):Vh.primitive(Fd.float(e)),double:()=>typeof e!="number"?Vh.primitive(Fd.double(ky.DOUBLE)):Vh.primitive(Fd.double(e)),long:()=>typeof e!="number"?Vh.primitive(Fd.long(ky.UINT)):Vh.primitive(Fd.long(e)),boolean:()=>typeof e!="boolean"?Vh.primitive(Fd.boolean(ky.BOOLEAN)):Vh.primitive(Fd.boolean(e)),uuid:()=>typeof e!="string"?Vh.primitive(Fd.string({original:ky.UUID})):Vh.primitive(Fd.uuid(e)),bigInteger:()=>typeof e!="string"?Vh.primitive(Fd.string({original:ky.BIG_INTEGER})):Vh.primitive(Fd.string({original:e})),_other:()=>{throw new Error("Unknown primitive type: "+t)}})}function bI_({typeName:e,rawObject:t,example:r,fileContainingType:i,fileContainingExample:n,typeResolver:a,exampleResolver:u,workspace:l}){if(!Gj(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return Rw.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((d,[s,o])=>{let c=gI_({typeName:e,wirePropertyKey:s,rawObject:t,typeResolver:a,file:i});if(c==null)return d;let b=GE({example:o,fileContainingExample:n,rawTypeBeingExemplified:typeof c.rawPropertyType=="string"?c.rawPropertyType:c.rawPropertyType.type,fileContainingRawTypeReference:c.file,typeResolver:a,exampleResolver:u,workspace:l});return d.push({name:n.casingsGenerator.generateNameAndWireValue({name:uL({propertyKey:s,property:c.rawPropertyType}).name,wireValue:s}),value:b,originalTypeDeclaration:c.typeName}),d},[]):[]})}function gI_({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:i,file:n}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:n}:Qxa({wirePropertyKey:t,extends_:r.extends,typeResolver:i,file:n})}function Qxa({wirePropertyKey:e,extends_:t,typeResolver:r,file:i}){if(t!=null){let n=typeof t=="string"?[t]:t;for(let a of n){let u=r.resolveNamedTypeOrThrow({referenceToNamedType:a,file:i});if(u._type!=="named"||!xS(u.declaration))throw new Error("Extension is not of a named object");let l=gI_({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(l!=null)return l}}}function f6E({rawValueType:e,rawSingleUnionType:t,fileContainingType:r,fileContainingExample:i,typeResolver:n,exampleResolver:a,example:u,discriminant:l,discriminantValueForExample:d,workspace:s}){let o=i.casingsGenerator.generateNameAndWireValue({name:n9n({unionKey:d,rawSingleUnionType:t}).name,wireValue:d});if(e==null)return{wireDiscriminantValue:o,shape:r3.noProperties()};let c=Tjc({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:n});switch(c.propertiesType){case"singleProperty":{if(!Gj(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:r3.singleProperty(GE({example:u[c.name.wireValue],rawTypeBeingExemplified:e,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:i,workspace:s}))}}case"samePropertiesAsObject":{if(!Gj(u))throw new Error("Example is not an object");let{[l]:b,...g}=u,O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});for(;s1i(O.declaration);)O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:typeof O.declaration=="string"?O.declaration:O.declaration.type,file:r});if(!xS(O.declaration))throw new Error(`${e} is not an object`);let m={typeId:c.typeId,fernFilepath:c.fernFilepath,name:c.name,displayName:c.displayName};return{wireDiscriminantValue:o,shape:r3.samePropertiesAsObject({typeId:jm.generateTypeId(m),object:bI_({rawObject:O.declaration,example:g,fileContainingType:O.file,fileContainingExample:i,typeResolver:n,exampleResolver:a,typeName:m,workspace:s})})}}default:jo(c)}}function deu({file:e,queryParameterKey:t,queryParameter:r}){let{name:i}=lpi({queryParameterKey:t,queryParameter:r}),n=e.parseTypeReference(r);return{...lJ(r),name:e.casingsGenerator.generateNameAndWireValue({wireValue:t,name:i}),valueType:n,allowMultiple:typeof r!="string"&&r["allow-multiple"]!=null?r["allow-multiple"]:!1,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function lpi({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function OI_({service:e,endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,variableResolver:u,file:l,workspace:d}){let s=p6E({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,variableResolver:u,file:l,workspace:d});return{id:r.name??BTa(r),name:r.name!=null?l.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:b6E({file:l,service:e,endpoint:t,example:r,pathParams:s}),...s,..._6E({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:l,workspace:d}),queryParameters:r["query-parameters"]!=null?Object.entries(r["query-parameters"]).map(([o,c])=>{let b=typeof t.request!="string"?t.request?.["query-parameters"]?.[o]:void 0;if(b==null)throw new Error(`Query parameter ${o} does not exist`);return{name:l.casingsGenerator.generateNameAndWireValue({name:lpi({queryParameterKey:o,queryParameter:b}).name,wireValue:o}),value:GE({example:c,rawTypeBeingExemplified:typeof b=="string"?b:b.type,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:l,fileContainingExample:l,workspace:d}),shape:d6E({queryParameter:b})}}):[],request:h6E({endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:l,workspace:d}),response:y6E({endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,file:l,workspace:d})}}function d6E({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?A2.exploded():A2.single()}function p6E({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:n,variableResolver:a,file:u,workspace:l}){let d=[],s=[],o=[],c=({name:b,pathParameterDeclaration:g,examplePathParameter:O})=>{let m=Jxa({parameter:g,variableResolver:a,file:u});return{name:b,value:GE({example:O,rawTypeBeingExemplified:m.rawType,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:m.file,fileContainingExample:u,workspace:l})}};if(r["path-parameters"]!=null){let b=hHt(t);for(let[g,O]of Object.entries(r["path-parameters"])){let m=u.rootApiFile["path-parameters"]?.[g],w=e["path-parameters"]?.[g],E=b[g];if(m!=null)d.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:m,examplePathParameter:O}));else if(E!=null)o.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:E,examplePathParameter:O}));else if(w!=null)s.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:w,examplePathParameter:O}));else throw new Error(`Path parameter ${g} does not exist`)}}return{rootPathParameters:d,endpointPathParameters:o,servicePathParameters:s}}function _6E({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:u}){let l=[],d=[];if(r.headers!=null)for(let[s,o]of Object.entries(r.headers)){let c=typeof t.request!="string"?t.request?.headers?.[s]:void 0,b=e.headers?.[s];c!=null?d.push({name:a.casingsGenerator.generateNameAndWireValue({name:Eir({headerKey:s,header:c}).name,wireValue:s}),value:GE({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}):b!=null&&l.push({name:a.casingsGenerator.generateNameAndWireValue({name:Eir({headerKey:s,header:b}).name,wireValue:s}),value:GE({example:o,rawTypeBeingExemplified:typeof b=="string"?b:b.type,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})})}return{endpointHeaders:d,serviceHeaders:l}}function h6E({endpoint:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=typeof e.request!="string"?e.request?.body:e.request;if(u==null||typeof u=="string"&&l1a(u)!=null)return;if(!JC(u))return yQ.reference(GE({example:t.request,rawTypeBeingExemplified:typeof u!="string"?u.type:u,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!t.request)return;if(!Gj(t.request))throw new Error(`Example is not an object. Got: ${JSON.stringify(t.request)}`);let l=[];for(let[d,s]of Object.entries(t.request)){let o=u.properties?.[d],c=typeof o=="string"?o:o?.type;if(!(c!=null&&Xxe(c)!=null))if(o!=null)l.push({name:n.casingsGenerator.generateNameAndWireValue({name:uL({propertyKey:d,property:o}).name,wireValue:d}),value:GE({example:s,rawTypeBeingExemplified:typeof o!="string"?o.type:o,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),originalTypeDeclaration:void 0});else{let b=Qxa({extends_:u.extends,wirePropertyKey:d,typeResolver:r,file:n});if(b==null)throw new Error("Could not find original type declaration for property: "+d);l.push({name:n.casingsGenerator.generateNameAndWireValue({name:uL({propertyKey:d,property:b.rawPropertyType}).name,wireValue:d}),value:GE({example:s,rawTypeBeingExemplified:typeof b.rawPropertyType=="string"?b.rawPropertyType:b.rawPropertyType.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:n,workspace:a}),originalTypeDeclaration:b.typeName})}}return yQ.inlinedRequestBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t.request,file:n}).resolvedExample,properties:l})}function y6E({endpoint:e,example:t,typeResolver:r,errorResolver:i,exampleResolver:n,file:a,workspace:u}){return t.response==null?IT.ok(YC.body(void 0)):sWi(e,t.response,{body:l=>{if(l.error!=null){let d=i.getDeclarationOrThrow(l.error,a);return IT.error({error:yAi({errorName:l.error,file:a}),body:d.declaration.type!=null?GE({example:l.body,rawTypeBeingExemplified:d.declaration.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:d.file,fileContainingExample:a,workspace:u}):void 0})}return IT.ok(YC.body(v6E({endpoint:e,example:l,typeResolver:r,exampleResolver:n,file:a,workspace:u})))},stream:l=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return IT.ok(YC.stream(l.stream.map(s=>{if(d!=null)return GE({example:s,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter(yv)))},events:l=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return IT.ok(YC.sse(l.stream.map(({event:s,data:o})=>{if(d==null)return;let c=GE({example:o,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:s,data:c}}).filter(yv)))}})}function v6E({endpoint:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=typeof e.response!="string"?e.response?.type:e.response;if(u!=null&&t.body!=null)return GE({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})}function b6E({file:e,service:t,endpoint:r,example:i,pathParams:n}){let a=lb(e.rootApiFile["base-path"]??"",t["base-path"],r.path);if(i["path-parameters"]!=null)for(let u of[...n.endpointPathParameters,...n.servicePathParameters,...n.rootPathParameters])a=a.replaceAll(`{${u.name.originalName}}`,encodeURIComponent(`${u.value.jsonExample}`));return a=a.replaceAll("//","/"),a.startsWith("/")||(a=`/${a}`),a}function mI_({endpoint:e,file:t,typeResolver:r}){return{body:g6E({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}function g6E({endpoint:e,file:t,typeResolver:r}){let i=O6E({endpoint:e,file:t,typeResolver:r}),n=m6E({endpoint:e,file:t,typeResolver:r});if(i!=null&&n!=null){let a;switch(i.type){case"fileDownload":{a=cW.fileDownload({...i});break}case"json":{a=cW.json({...i.value});break}case"text":{a=cW.text({...i});break}case"bytes":{a=cW.bytes({...i});break}default:jo(i)}return xw.streamParameter({nonStreamResponse:a,streamResponse:n})}else{if(i!=null)return i;if(n!=null)return xw.streaming(n)}}function O6E({endpoint:e,file:t,typeResolver:r}){let{response:i}=e;if(i!=null){let n=typeof i!="string"?i.docs:void 0,a=typeof i=="string"?i:i.type;if(a!=null)return Xxe(a)!=null?xw.fileDownload({docs:n,v2Examples:void 0}):f1a(a)!=null?xw.text({docs:n,v2Examples:void 0}):lkt(a)!=null?xw.bytes({docs:n,v2Examples:void 0}):P6E(i,n,t,r)}}function m6E({endpoint:e,file:t,typeResolver:r}){let{["response-stream"]:i}=e;if(i!=null){let n=typeof i!="string"?i.docs:void 0,a=typeof i=="string"?i:i.type,u=typeof i=="string"?"json":i.format??"json";return pzn(a)?j9.text({docs:n,v2Examples:void 0}):typeof i!="string"&&u==="sse"?j9.sse({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0,v2Examples:void 0}):j9.json({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0,v2Examples:void 0})}}function P6E(e,t,r,i){let n=typeof e!="string"?e.type:e;if(n==null)return;let a=r.parseTypeReference(typeof e=="string"?e:{...e,type:n}),u=i.resolveTypeOrThrow({type:n,file:r}),l=typeof e!="string"?e.property:void 0;return l!=null?xw.json(P9.nestedPropertyAsResponse({docs:t,responseBodyType:a,responseProperty:Wxa({typeResolver:i,file:r,resolvedType:u,property:l}),v2Examples:void 0})):xw.json(P9.response({docs:t,responseBodyType:a,v2Examples:void 0}))}function PI_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return hQ.cursor({page:e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:n.cursor}),next:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n.next_cursor}),results:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n.results})})}function jI_({propertyResolver:e,file:t,endpointName:r,paginationPropertyComponents:i}){return hQ.custom({results:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results})})}function wI_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return hQ.offset({page:e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:n.offset}),results:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n.results}),step:n.step!=null?e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:n.step}):void 0,hasNextPage:n.hasNextPage!=null?e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n.hasNextPage}):void 0})}function SI_(e){if(w6E(e))return{type:"offset",offset:_Ht(e.offset),results:Dir(e.results),step:e.step!=null?_Ht(e.step):void 0,hasNextPage:e["has-next-page"]!=null?Dir(e["has-next-page"]):void 0};if(j6E(e))return{type:"cursor",cursor:_Ht(e.cursor),next_cursor:Dir(e.next_cursor),results:Dir(e.results)};if(S6E(e))return{type:"custom",results:Dir(e.results)};throw new Error("Invalid pagination schema")}function j6E(e){return e.cursor!=null}function w6E(e){return e.offset!=null&&e.results!=null}function S6E(e){return"type"in e&&e.type==="custom"}function DI_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i}){let n=typeof i.pagination=="boolean"?t.rootApiFile.pagination:i.pagination;if(!n)return;let a=SI_(n);switch(a.type){case"cursor":return PI_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"offset":return wI_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"custom":return jI_({propertyResolver:e,file:t,endpointName:r,paginationPropertyComponents:a});default:jo(a)}}function EI_({errors:e,file:t}){return e==null?[]:Object.values(e).map(r=>{let i=typeof r=="string"?r:r.error,n=yAi({errorName:i,file:t});return{docs:typeof r!="string"?r.docs:void 0,error:n}})}function peu({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function MI_({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:peu({source:e}),name:vAi.generateName(r)}}function AI_({file:e,serviceDeclaration:t,sourceResolver:r}){return kZt(t.source)?TI_(e,t.source,r,t.transport?.grpc?.["service-name"]):Hxe.http()}function qI_({file:e,serviceTransport:t,endpointDeclaration:r,sourceResolver:i}){let n=t.type==="grpc",a=t.type==="http",u=kZt(r.source),l=!u;if(n){if(a&&u)throw new Error("Cannot have a grpc endpoint on an http service");if(n&&l)return Hxe.http();if(n&&u){let d=r.source,s=r.transport?.grpc?.["service-name"];return s?TI_(e,d,i,s):void 0}throw new Error(`Internal error; failed to determine endpoint transport for
|
|
2042
|
-
${JSON.stringify(r)}"`)}}function TI_(e,t,r,i){let n=r.resolveSourceOrThrow({source:t,relativeFilepath:e.relativeFilepath});if(n==null||n.type!=="protobuf")throw new Error(`Expected a protobuf source for ${t.proto}.`);let a=MI_({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return Hxe.grpc({service:a})}function CI_({rootDefaultUrl:e,rootPathParameters:t,serviceDefinition:r,file:i,errorResolver:n,typeResolver:a,propertyResolver:u,exampleResolver:l,variableResolver:d,sourceResolver:s,globalErrors:o,workspace:c}){let b=s9n({pathParameters:r["path-parameters"],location:$xe.Service,file:i,variableResolver:d}),g=AI_({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:Gae(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:JN(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([w,E])=>OFe({headerKey:w,header:E,file:i})):[],pathParameters:b,encoding:A6E(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([w,E])=>{let q=s9n({pathParameters:hHt(E),location:$xe.Endpoint,file:i,variableResolver:d}),A={...lJ(E),id:"",name:i.casingsGenerator.generateName(w),displayName:E["display-name"],auth:E.auth??r.auth,idempotent:E.idempotent??r.idempotent??!1,baseUrl:E.url??r.url??e,v2BaseUrls:void 0,method:E.method!=null?M6E(E.method):KC.Post,basePath:E["base-path"]!=null?JN(E["base-path"]):void 0,path:JN(E.path),fullPath:JN(E["base-path"]!=null?lb(E["base-path"],E.path):i.rootApiFile["base-path"]!=null?lb(i.rootApiFile["base-path"],r["base-path"],E.path):lb(r["base-path"],E.path)),pathParameters:q,allPathParameters:E["base-path"]!=null?q:[...t,...b,...q],queryParameters:typeof E.request!="string"&&E.request?.["query-parameters"]!=null?Object.entries(E.request["query-parameters"]).map(([D,C])=>deu({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof E.request!="string"&&E.request?.headers!=null?Object.entries(E.request.headers).map(([D,C])=>OFe({headerKey:D,header:C,file:i})):[],requestBody:HB_({request:E.request,file:i}),sdkRequest:KB_({service:r,request:E.request,endpoint:E,endpointKey:w,file:i,typeResolver:a,propertyResolver:u}),response:mI_({endpoint:E,file:i,typeResolver:a}),errors:[...EI_({errors:E.errors,file:i}),...o],userSpecifiedExamples:E.examples!=null?E.examples.map(D=>({example:OI_({service:r,endpoint:E,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:d,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(C=>YB_({codeSample:C,file:i}))})):[],autogeneratedExamples:[],pagination:DI_({propertyResolver:u,file:i,endpointName:w,endpointSchema:E}),transport:qI_({file:i,serviceTransport:g,endpointDeclaration:E,sourceResolver:s}),v2Examples:void 0,source:void 0,audiences:E.audiences};return A.id=jm.generateEndpointId(O,A),A}),audiences:r.audiences}}function s9n({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>D6E({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function D6E({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...lJ(t),name:i.casingsGenerator.generateName(e),valueType:E6E({parameter:t,variableResolver:n,file:i}),location:r,variable:fxn(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function E6E({parameter:e,variableResolver:t,file:r}){let i=Jxa({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function Jxa({parameter:e,variableResolver:t,file:r}){let i=_eu({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function _eu({parameter:e,variableResolver:t,file:r}){if(fxn(e)){let i=typeof e=="string"?e:e.variable,n=t.getDeclaration(i,r);return n==null?void 0:{rawType:typeof n.declaration=="string"?n.declaration:n.declaration.type,file:n.file}}else return{file:r,rawType:typeof e=="string"?e:e.type}}function M6E(e){switch(e){case"GET":return KC.Get;case"POST":return KC.Post;case"PUT":return KC.Put;case"PATCH":return KC.Patch;case"DELETE":return KC.Delete;case"HEAD":return KC.Head;default:jo(e)}}function OFe({headerKey:e,header:t,file:r}){let{name:i}=Eir({headerKey:e,header:t});return{...lJ(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:i}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function Eir({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function A6E(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:jo(e)}}var BI_="1.0.0";var heu=class{ir;casingsGenerator;auth;authValues;generatorConfig;constructor(t){this.ir=t.ir,this.generatorConfig=t.generatorConfig,this.casingsGenerator=BZ({generationLanguage:t.generationLanguage,smartCasing:t.smartCasing??!1,keywords:void 0}),this.auth=this.convertAuth(this.ir.auth),this.authValues=this.getAuthValues(this.ir.auth)}convert({disableExamples:t}){return{version:BI_,types:this.convertNamedTypes(),headers:this.convertHeaders(),endpoints:this.convertEndpoints({disableExamples:t}),pathParameters:this.convertPathParameters({pathParameters:this.ir.pathParameters}),environments:this.ir.environments,generatorConfig:this.generatorConfig}}convertNamedTypes(){return Object.fromEntries(Object.entries(this.ir.types).map(([t,r])=>[t,this.convertTypeDeclaration(r)]))}convertHeaders(){return this.convertWireValueParameters({wireValueParameters:this.ir.headers})}convertEndpoints({disableExamples:t}){let r=this.getAllHttpEndpoints();return Object.fromEntries(r.map(i=>[i.id,this.convertEndpoint({endpoint:i,disableExamples:t})]))}convertEndpoint({endpoint:t,disableExamples:r}){let i=this.convertEndpointLocation({endpoint:t});return{auth:this.auth,declaration:this.convertDeclaration({name:t.name,fernFilepath:t.fernFilepath}),location:i,request:this.convertRequest({endpoint:t}),response:bs.Response.json(),examples:r?void 0:this.getEndpointSnippetRequests({endpoint:t,location:i})}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:[...t.servicePathParameters,...t.pathParameters]});if(t.sdkRequest==null&&t.requestBody==null)return bs.Request.body({pathParameters:r,body:void 0});if(t.sdkRequest==null)throw new Error(`Internal error; endpoint "${t.id}" has a request body but no SDK request`);switch(t.sdkRequest.shape.type){case"justRequestBody":return bs.Request.body({pathParameters:r,body:this.convertReferencedRequestBodyType({body:t.sdkRequest.shape.value})});case"wrapper":return this.convertInlinedRequest({fernFilepath:t.fernFilepath,wrapper:t.sdkRequest.shape,pathParameters:r,queryParameters:this.convertQueryParameters({queryParameters:t.queryParameters}),headers:this.convertWireValueParameters({wireValueParameters:[...t.serviceHeaders,...t.headers]}),body:t.requestBody});default:jo(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return bs.ReferencedRequestBodyType.bytes();case"typeReference":return bs.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:jo(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:i,queryParameters:n,headers:a,body:u}){return bs.Request.inlined({declaration:this.convertDeclaration({name:r.wrapperName,fernFilepath:t}),pathParameters:i,queryParameters:n,headers:a,body:u!=null?this.convertInlinedRequestBody({wrapper:r,body:u}):void 0,metadata:this.convertInlinedRequestMetadata({wrapper:r})})}convertInlinedRequestMetadata({wrapper:t}){return{includePathParameters:t.includePathParameters??!1,onlyPathParameters:t.onlyPathParameters??!1}}convertInlinedRequestBody({wrapper:t,body:r}){switch(r.type){case"inlinedRequestBody":{let i=[...r.extendedProperties??[],...r.properties];return bs.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:i}))}case"reference":return bs.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:bs.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return bs.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:bs.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:jo(r)}}convertFileUploadRequestBody({properties:t}){return bs.InlinedRequestBody.fileUpload({properties:this.convertFileUploadRequestBodyProperties({properties:t})})}convertFileUploadRequestBodyProperties({properties:t}){return t.map(r=>{switch(r.type){case"file":return this.convertFileUploadRequestBodyFileProperty({fileProperty:r.value});case"bodyProperty":return bs.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:jo(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return bs.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return bs.FileUploadRequestBodyProperty.fileArray(t.key);default:jo(t)}}convertPathParameters({pathParameters:t}){return t.map(r=>({name:{name:r.name,wireValue:r.name.originalName},typeReference:this.convertTypeReference(r.valueType)}))}convertWireValueParameters({wireValueParameters:t}){return t.map(r=>({name:{name:r.name.name,wireValue:r.name.wireValue},typeReference:this.convertTypeReference(r.valueType)}))}convertQueryParameters({queryParameters:t}){let r=[];for(let i of t){let n=this.convertTypeReference(i.valueType);i.allowMultiple&&(n=bs.TypeReference.list(n)),r.push({name:{name:i.name.name,wireValue:i.name.wireValue},typeReference:n})}return r}convertTypeReference(t){switch(t.type){case"container":return this.convertContainerType(t.container);case"named":return this.convertNamedType(t);case"primitive":return this.convertPrimitiveType(t.primitive);case"unknown":return this.convertUnknownType();default:jo(t)}}convertContainerType(t){switch(t.type){case"list":return bs.TypeReference.list(this.convertTypeReference(t.list));case"map":return bs.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return bs.TypeReference.optional(this.convertTypeReference(t.optional));case"nullable":return bs.TypeReference.nullable(this.convertTypeReference(t.nullable));case"set":return bs.TypeReference.set(this.convertTypeReference(t.set));case"literal":return bs.TypeReference.literal(this.convertLiteral(t.literal));default:jo(t)}}convertNamedType(t){return bs.TypeReference.named(t.typeId)}convertTypeDeclaration(t){let r=this.convertDeclaration(t.name);switch(t.shape.type){case"alias":return this.convertAlias({declaration:r,alias:t.shape});case"enum":return this.convertEnum({declaration:r,enum_:t.shape});case"object":return this.convertObject({declaration:r,object:t.shape});case"union":return this.convertDiscriminatedUnion({declaration:r,union:t.shape});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({declaration:r,union:t.shape});default:jo(t.shape)}}convertAlias({declaration:t,alias:r}){return bs.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return bs.NamedType.enum({declaration:t,values:r.values.map(i=>i.name)})}convertObject({declaration:t,object:r}){let i=[...r.extendedProperties??[],...r.properties];return this.convertObjectProperties({declaration:t,properties:i,additionalProperties:r.extraProperties})}convertObjectProperties({declaration:t,properties:r,additionalProperties:i}){return bs.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r}),additionalProperties:i})}convertDiscriminatedUnion({declaration:t,union:r}){let i=[...this.resolveProperties(r.extends),...r.baseProperties];return bs.NamedType.discriminatedUnion({declaration:t,discriminant:r.discriminant,types:Object.fromEntries(r.types.map(n=>[n.discriminantValue.wireValue,this.convertDiscriminatedUnionType({inheritedProperties:i,discriminantValue:n.discriminantValue,singleUnionTypeProperties:n.shape})]))})}convertDiscriminatedUnionType({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperties:i}){switch(i.propertiesType){case"samePropertiesAsObject":return this.convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i});case"singleProperty":return this.convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i});case"noProperties":return this.convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r});default:jo(i)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i}){return bs.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:i.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:t})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i}){return bs.SingleDiscriminatedUnionType.singleProperty({typeReference:this.convertTypeReference(i.type),discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r}){return bs.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return bs.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(i=>this.convertTypeReference(i.type))})}convertLiteral(t){switch(t.type){case"boolean":return bs.LiteralType.boolean(t.boolean);case"string":return bs.LiteralType.string(t.string);default:jo(t)}}convertPrimitiveType(t){return bs.TypeReference.primitive(t.v1)}convertUnknownType(){return bs.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return bs.Auth.basic(r);case"bearer":return bs.Auth.bearer(r);case"header":return bs.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return bs.Auth.oauth({clientId:this.casingsGenerator.generateName("clientId"),clientSecret:this.casingsGenerator.generateName("clientSecret")});default:jo(r)}}getAuthValues(t){let r=t.schemes[0];if(r!=null)switch(r.type){case"bearer":return bs.AuthValues.bearer({token:"<token>"});case"basic":return bs.AuthValues.basic({username:"<username>",password:"<password>"});case"header":return bs.AuthValues.header({value:"<value>"});case"oauth":return bs.AuthValues.oauth({clientId:"<clientId>",clientSecret:"<clientSecret>"});default:jo(r)}}convertDeclaration({name:t,fernFilepath:r}){return{name:t,fernFilepath:r}}convertEndpointLocation({endpoint:t}){return{method:t.method,path:this.getFullPathForEndpoint(t)}}getAllHttpEndpoints(){return Object.values(this.ir.services).flatMap(t=>t.endpoints.map(r=>({...r,servicePathParameters:t.pathParameters,serviceHeaders:t.headers,fernFilepath:t.name.fernFilepath})))}resolveProperties(t){let r=[];for(let i of t){let n=this.resolveObjectTypeOrThrow(i.typeId);r.push(...this.resolveProperties(n.extends)),r.push(...n.properties)}return Object.values(r)}resolveObjectTypeOrThrow(t){let r=this.ir.types[t];if(r==null)throw new Error(`Internal error; type "${t}" not found`);if(r.shape.type!=="object")throw new Error(`Internal error; type "${t}" is not an object`);return r.shape}getFullPathForEndpoint(t){let r="";t.fullPath.head.length>0&&(r=lb(r,t.fullPath.head));for(let i of t.fullPath.parts)r=lb(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=lb(r,i.tail));return r.startsWith("/")?r:`/${r}`}getEndpointSnippetRequests({endpoint:t,location:r}){let i=[];for(let n of[...t.userSpecifiedExamples,...t.autogeneratedExamples])i.push({id:n?.example?.id??lae(),name:n?.example?.name?.originalName,endpoint:r,baseUrl:void 0,environment:void 0,auth:this.authValues,headers:Object.fromEntries([...n.example?.serviceHeaders??[],...n.example?.endpointHeaders??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),pathParameters:Object.fromEntries([...n.example?.rootPathParameters??[],...n.example?.servicePathParameters??[],...n.example?.endpointPathParameters??[]].map(a=>[a.name.originalName,a.value.jsonExample])),queryParameters:Object.fromEntries([...n.example?.queryParameters??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),requestBody:n.example?.request?.jsonExample});return i}};function II_({ir:e,generationLanguage:t,smartCasing:r,disableExamples:i,generatorConfig:n}){return new heu({ir:e,generationLanguage:t,smartCasing:r,generatorConfig:n}).convert({disableExamples:i})}var fJ={};Po(fJ,{validateObjectExample:()=>sKi,validateTypeExample:()=>leu,validateTypeReferenceExample:()=>sL});var yeu=class{subpackages={};rootPackage={docs:void 0,fernFilepath:{allParts:[],packagePath:[],file:void 0},websocket:void 0,service:void 0,types:[],errors:[],subpackages:[],webhooks:void 0,navigationConfig:void 0};addPackageRedirection({from:t,to:r}){let i=this.getPackageForFernFilepath(t);if(i.navigationConfig!=null)throw new Error("Found duplicate navigationConfig for package");i.navigationConfig={pointsTo:jm.generateSubpackageId(r)}}addDocs(t,r){let i=this.getPackageForFernFilepath(t);if(i.docs!=null)throw new Error("Found duplicate docs for package");i.docs=r}addSubpackage(t){this.getPackageForFernFilepath(t)}addType(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).types.push(t)}addError(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).errors.push(t)}addService(t,r){let i=this.getPackageForFernFilepath(r.name.fernFilepath);if(i.service!=null)throw new Error("Found duplicate service for "+t);i.service=t}addWebhookGroup(t,r){let i=this.getPackageForFernFilepath(r);if(i.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);i.webhooks=t}addWebSocketChannel(t,r){let i=this.getPackageForFernFilepath(r);if(i.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);i.websocket=t}build(t){t!=null&&(Object.entries(this.subpackages).forEach(([i,n])=>{t.hasSubpackageId(i)?this.subpackages[i]={...n,types:n.types.filter(a=>t.hasTypeId(a)),errors:n.errors.filter(a=>t.hasErrorId(a)),service:n.service!=null&&t.hasServiceId(n.service)?n.service:void 0,websocket:n.websocket!=null&&t.hasChannel(n.websocket)?n.websocket:void 0,subpackages:n.subpackages.filter(a=>t.hasSubpackageId(a))}:delete this.subpackages[i]}),this.rootPackage={...this.rootPackage,types:this.rootPackage.types.filter(i=>t.hasTypeId(i)),errors:this.rootPackage.errors.filter(i=>t.hasErrorId(i)),service:this.rootPackage.service!=null&&t.hasServiceId(this.rootPackage.service)?this.rootPackage.service:void 0,subpackages:this.rootPackage.subpackages.filter(i=>t.hasSubpackageId(i)),webhooks:this.rootPackage.webhooks!=null?this.rootPackage.webhooks:void 0});let r=new Set(this.getAllChildrenWithEndpoints(this.rootPackage));return{subpackages:fd(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!zI_(this.rootPackage.subpackages,t))throw new Error("Sorted subpackages differ from unsorted packages in root");this.rootPackage.subpackages=t}sortSubpackage(t,r){let i=this.subpackages[t];if(i==null)throw new Error("Subpackage does not exist: "+t);if(!zI_(i.subpackages,r))throw new Error("Sorted subpackages differ from unsorted packages");i.subpackages=r}getAllSubpackagesWithEndpoints(t){let r=this.subpackages[t];if(r==null)throw new Error("Subpackage does not exist: "+t);let i=this.getAllChildrenWithEndpoints(r);return(i.length>0||r.service!=null)&&i.push(t),i}getAllChildrenWithEndpoints(t){return t.subpackages.flatMap(r=>[...this.getAllSubpackagesWithEndpoints(r)])}getPackageForFernFilepath(t,r=0,i=this.rootPackage){let n=t.allParts[r];if(n==null)return i;let a=i.subpackages.map(s=>{let o=this.subpackages[s];if(o==null)throw new Error("Subpackage ID is invalid: "+s);return o}),u=r+1,l={allParts:t.allParts.slice(0,u),packagePath:t.packagePath.slice(0,u),file:u===t.allParts.length?t.file:void 0},d=a.find(s=>s.name.originalName===n.originalName);if(d==null){let s=jm.generateSubpackageId(l),o={docs:void 0,fernFilepath:l,name:n,service:void 0,types:[],errors:[],subpackages:[],navigationConfig:void 0,webhooks:void 0,websocket:void 0};this.subpackages[s]=o,i.subpackages.push(s),d=o}return this.getPackageForFernFilepath(t,u,d)}};function zI_(e,t){if(e.length!==t.length)return!1;let r=new Set(e);for(let i of t)if(!r.has(i))return!1;return!0}function xI_(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}var veu=e=>{let t=tMe(e.file.fernFilepath),r=e.endpointId;return`endpoint_${t}.${r}`};function beu({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function RI_({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r}),a;try{a=i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0}catch{}return{endpointReference:{endpointId:veu(n),serviceId:jm.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:beu({fernFilePath:n.file.fernFilepath})?void 0:jm.generateSubpackageId(n.file.fernFilepath)},requestProperties:{refreshToken:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.refresh_token})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:a,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}function NI_({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r}),a=typeof n.endpoint.request=="object"&&n.endpoint.request.body!=null&&typeof n.endpoint.request.body=="object"&&"properties"in n.endpoint.request.body?n.endpoint.request.body.properties??{}:{},u;try{u=i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0}catch{}return{endpointReference:{endpointId:veu(n),serviceId:jm.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:beu({fernFilePath:n.file.fernFilepath})?void 0:jm.generateSubpackageId(n.file.fernFilepath)},requestProperties:{clientId:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.client_id}),clientSecret:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.client_secret}),scopes:i.requestProperties.scopes!=null?t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.scopes}):void 0,customProperties:q6E({requestBodyProperties:a,tokenEndpoint:i,file:r,propertyResolver:t})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:u,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}var q6E=({requestBodyProperties:e,tokenEndpoint:t,file:r,propertyResolver:i})=>{let n=Object.keys(e).filter(a=>!t.requestProperties.client_id.includes(a)&&!t.requestProperties.client_secret.includes(a)&&(t.requestProperties.scopes==null||!t.requestProperties.scopes.includes(a)));return n.length>0?n.map(a=>i.resolveRequestPropertyOrThrow({file:r,endpoint:t.endpoint,propertyComponents:[a]})):void 0};function FI_({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=NI_({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?RI_({propertyResolver:e,endpointResolver:t,file:r,refreshTokenEndpoint:a}):void 0;return{clientIdEnvVar:i["client-id-env"],clientSecretEnvVar:i["client-secret-env"],tokenPrefix:i["token-prefix"],tokenHeader:i["token-header"],scopes:i.scopes,tokenEndpoint:u,refreshEndpoint:l}}var Kxa={requestProperties:{type:"access_token",client_id:["client_id"],client_secret:["client_secret"],scopes:void 0},responseProperties:{type:"access_token",access_token:["access_token"],expires_in:["expires_in"],refresh_token:void 0}},Bjc={requestProperties:{type:"refresh_token",refresh_token:["refresh_token"]},responseProperties:{type:"access_token",access_token:["access_token"],refresh_token:void 0,expires_in:["expires_in"]}};function LI_(e){return{endpoint:e["get-token"].endpoint,requestProperties:T6E({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:C6E({responseProperties:e["get-token"]?.["response-properties"]})}}function UI_(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:B6E({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:I6E({responseProperties:e["refresh-token"]?.["response-properties"]})}}function T6E({requestProperties:e}){if(e==null)return Kxa.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?_Ht(t):Kxa.requestProperties.client_id,client_secret:r!=null?_Ht(r):Kxa.requestProperties.client_secret,scopes:i!=null?_Ht(i):Kxa.requestProperties.scopes}}function C6E({responseProperties:e}){return VI_({responseProperties:e,defaultValue:Kxa.responseProperties})}function B6E({requestProperties:e}){if(e==null)return Bjc.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?_Ht(t):Bjc.requestProperties.refresh_token}}function I6E({responseProperties:e}){return VI_({responseProperties:e,defaultValue:Bjc.responseProperties})}function VI_({responseProperties:e,defaultValue:t}){if(e==null)return t;let r=e["access-token"],i=e["expires-in"],n=e["refresh-token"];return{type:"access_token",access_token:r!=null?Dir(r):t.access_token,expires_in:i!=null?Dir(i):t.expires_in,refresh_token:n!=null?Dir(n):t.refresh_token}}function QI_({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:bne.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return cWi(e.auth,{single:a=>{let u=WI_({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:bne.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:bne.Any,schemes:a.map(u=>WI_({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function WI_({reference:e,authSchemeDeclarations:t,file:r,propertyResolver:i,endpointResolver:n}){let a=(l,d)=>{let s=t?.[l];if(s==null)throw new Error("Unknown auth scheme: "+l);return d1a(s,{header:o=>BT.header({docs:d,name:r.casingsGenerator.generateNameAndWireValue({name:o.name??l,wireValue:o.header}),valueType:r.parseTypeReference(o.type??"string"),prefix:o.prefix,headerEnvVar:o.env}),basic:o=>$I_({file:r,docs:d,rawScheme:o}),bearer:o=>HI_({file:r,docs:d,rawScheme:o}),oauth:o=>GI_({file:r,docs:d,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return HI_({file:r,docs:void 0,rawScheme:void 0});case"basic":return $I_({file:r,docs:void 0,rawScheme:void 0});case"oauth":return GI_({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function HI_({file:e,docs:t,rawScheme:r}){return BT.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function $I_({file:e,docs:t,rawScheme:r}){return BT.basic({docs:t,username:e.casingsGenerator.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.casingsGenerator.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function GI_({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return BT.oauth({docs:t,configuration:Xwi.clientCredentials(FI_({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:LI_(r),refreshTokenEndpoint:UI_(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function JI_({file:e,rawApiFileSchema:t}){if(t.version!=null)return e1i.header({header:z6E({file:e,header:t.version.header}),value:x6E({file:e,versionDeclaration:t.version})})}function z6E({file:e,header:t}){return typeof t=="string"?OFe({file:e,headerKey:t,header:{type:"string"}}):OFe({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function x6E({file:e,versionDeclaration:t}){return feu({_enum:{default:t.default,enum:t.values},file:e})}function KI_({channel:e,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a}){let u=[];for(let[l,d]of Object.entries(e.messages??{}))u.push({type:l,availability:Gae(d.availability),docs:d.docs,origin:d.origin,body:F6E({body:d.body,file:n}),displayName:d["display-name"]});return{availability:Gae(e.availability),path:JN(e.path),baseUrl:e.url,auth:e.auth,name:n.fernFilepath.file??n.casingsGenerator.generateName(e["display-name"]??e.path),displayName:e["display-name"],headers:e.headers!=null?Object.entries(e.headers).map(([l,d])=>OFe({headerKey:l,header:d,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?s9n({pathParameters:e["path-parameters"],location:$xe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,d])=>{let{name:s}=lpi({queryParameterKey:l,queryParameter:d}),o=n.parseTypeReference(d);return{...lJ(d),name:n.casingsGenerator.generateNameAndWireValue({wireValue:l,name:s}),valueType:o,allowMultiple:typeof d!="string"&&d["allow-multiple"]!=null?d["allow-multiple"]:!1,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}):[],messages:Object.values(u),examples:(e.examples??[]).map(l=>{let d=U6E({channel:e,example:l,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a});return{name:l.name!=null?n.casingsGenerator.generateName(l.name):void 0,docs:l.docs,url:W6E({channel:e,example:l,pathParams:d}),...d,...V6E({channel:e,example:l,typeResolver:t,exampleResolver:r,file:n,workspace:a}),queryParameters:l["query-parameters"]!=null?Object.entries(l["query-parameters"]).map(([s,o])=>{let c=e["query-parameters"]?.[s];if(c==null)throw new Error(`Query parameter ${s} does not exist`);return{name:n.casingsGenerator.generateNameAndWireValue({name:lpi({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:GE({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:R6E({queryParameter:c})}}):[],messages:l.messages.map(s=>{let o=e.messages?.[s.type];if(o==null)throw new Error(`Message ${s.type} does not exist`);return{type:s.type,body:N6E({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}}),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function R6E({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?A2.exploded():A2.single()}function N6E({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!H6E(e.body))return DEe.reference(GE({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!Gj(t))throw new Error("Example must be an object");let u=[];for(let[l,d]of Object.entries(t)){let s=e.body.properties?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:uL({propertyKey:l,property:s}).name,wireValue:l}),value:GE({example:d,rawTypeBeingExemplified:typeof s!="string"?s.type:s,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),originalTypeDeclaration:void 0});else{let o=Qxa({extends_:e.body.extends,wirePropertyKey:l,typeResolver:r,file:n});if(o==null)throw new Error("Could not find original type declaration for property: "+l);u.push({name:n.casingsGenerator.generateNameAndWireValue({name:uL({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:GE({example:d,rawTypeBeingExemplified:typeof o.rawPropertyType=="string"?o.rawPropertyType:o.rawPropertyType.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:o.file,fileContainingExample:n,workspace:a}),originalTypeDeclaration:o.typeName})}}return DEe.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function F6E({body:e,file:t}){return typeof e=="string"?D9.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):L6E(e)?D9.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):D9.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:pHt(e.extends??[]).map(r=>oL({typeName:r,file:t})),properties:Object.entries(e.properties??{}).map(([r,i])=>({name:t.casingsGenerator.generateNameAndWireValue({name:uL({propertyKey:r,property:i}).name,wireValue:r}),value:t.parseTypeReference(i),valueType:t.parseTypeReference(i),availability:void 0,docs:void 0}))})}function L6E(e){return e.type!=null}function U6E({channel:e,example:t,typeResolver:r,exampleResolver:i,variableResolver:n,file:a,workspace:u}){let l=[],d=({name:s,pathParameterDeclaration:o,examplePathParameter:c})=>{let b=Jxa({parameter:o,variableResolver:n,file:a});return{name:s,value:GE({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=hHt(e);for(let[o,c]of Object.entries(t["path-parameters"])){let b=s[o];if(b!=null)l.push(d({name:a.casingsGenerator.generateName(o),pathParameterDeclaration:b,examplePathParameter:c}));else throw new Error(`Path parameter ${o} does not exist`)}}return{pathParameters:l}}function V6E({channel:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=[];if(t.headers!=null)for(let[l,d]of Object.entries(t.headers)){let s=e.headers?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:Eir({headerKey:l,header:s}).name,wireValue:l}),value:GE({example:d,rawTypeBeingExemplified:typeof s=="string"?s:s.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})});else throw new Error(`Heder ${l} does not exist`)}return{headers:u}}function W6E({channel:e,example:t,pathParams:r}){let i=e.path;if(t["path-parameters"]!=null)for(let n of[...r.pathParameters])i=i.replaceAll(`{${n.name.originalName}}`,encodeURIComponent(`${n.value.jsonExample}`));return i}function H6E(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function YI_({errorName:e,errorDeclaration:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=[];if(t.type!=null&&t.examples!=null)for(let l of t.examples)u.push({name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,docs:l.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:l.value,file:r}).resolvedExample,shape:GE({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:yAi({errorName:e,file:r}),discriminantValue:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:e}),docs:typeof t!="string"?t.docs:void 0,statusCode:t["status-code"],type:t.type!=null?r.parseTypeReference(t.type):void 0,examples:u,v2Examples:void 0,displayName:void 0}}var XI_="content";function ZI_(e,t){if(e==null||e.strategy==="status-code")return SEe.statusCode();switch(e.strategy){case"property":return SEe.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:XI_,wireValue:XI_})});default:jo(e)}}function kI_({readme:e,services:t}){let r=new Ijc(t);return{apiReferenceLink:e.apiReferenceLink,bannerLink:e.bannerLink,introduction:e.introduction,defaultEndpoint:e.defaultEndpoint!=null?r.getEndpointForReadmeOrThrow(e.defaultEndpoint).id:void 0,features:e.features!=null?Object.fromEntries(Object.entries(e.features).map(([i,n])=>[i,n.map(a=>r.getEndpointForReadmeOrThrow(a).id)])):void 0}}var Ijc=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=G6E({endpoint:t}),i=this.getEndpointKeyForReadmeEndpoint(r);return this.endpoints[i]}getEndpointForReadmeOrThrow(t){let r=this.getEndpointForReadme(t);if(r==null)throw new Error(`Endpoint not found for ${JSON.stringify(t)}`);return r}buildEndpoints(t){let r={};for(let i of Object.values(t))for(let n of i.endpoints)r[this.getEndpointKeyForHttpEndpoint(n)]=n;return r}getEndpointKeyForReadmeEndpoint(t){return this.getEndpointKey({method:t.method,path:t.path,stream:t.stream??!1})}getEndpointKeyForHttpEndpoint(t){return this.getEndpointKey({method:t.method,path:$6E(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function $6E(e){let t="";e.fullPath.head.length>0&&(t=lb(t,e.fullPath.head));for(let r of e.fullPath.parts)t=lb(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=lb(t,r.tail));return t.startsWith("/")?t:`/${t}`}function G6E({endpoint:e}){if(typeof e=="string"){let t=e.split(" ");if(t.length!==2||t[0]==null||t[1]==null)throw new Error(`invalid endpoint string: ${e}`);return{method:t[0],path:t[1]}}return e}function ez_({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:jm.generateWebhookId(t.fernFilepath,u),availability:Gae(l.availability),displayName:l["display-name"],docs:l.docs,method:l.method,name:t.casingsGenerator.generateName(u),headers:l.headers!=null?Object.entries(l.headers).map(([d,s])=>OFe({headerKey:d,header:s,file:t})):[],payload:Q6E({payload:l.payload,file:t}),examples:l.examples!=null?K6E({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0,v2Examples:void 0});return a}function Q6E({payload:e,file:t}){return typeof e=="string"?fW.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):X6n(e)?fW.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):fW.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:pHt(e.extends).map(r=>oL({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>J6E({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?Gae(i.availability):void 0,file:t})):[]})}function J6E({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:uL({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function K6E({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:X6n(e.payload)?e.payload.type:void 0;if(u!=null)return t.map(l=>({docs:e.docs,name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,payload:GE({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!Gj(e.payload))throw new Error(`Example webhook payload is not an object. Got: ${JSON.stringify(e.payload)}`);return t.map(l=>({docs:e.docs,name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,payload:GE({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function tz_({name:e,source:t}){return Kj.userDefined({file:peu({source:t}),name:vAi.generateName(e)})}function rz_({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=Y6E({type:e.proto.type});if(t!=null)return t}}function Y6E({type:e}){switch(e){case"google.protobuf.Any":return Kj.wellKnown(id.any());case"google.protobuf.Api":return Kj.wellKnown(id.api());case"google.protobuf.BoolValue":return Kj.wellKnown(id.boolValue());case"google.protobuf.BytesValue":return Kj.wellKnown(id.bytesValue());case"google.protobuf.DoubleValue":return Kj.wellKnown(id.doubleValue());case"google.protobuf.Duration":return Kj.wellKnown(id.duration());case"google.protobuf.Empty":return Kj.wellKnown(id.empty());case"google.protobuf.Enum":return Kj.wellKnown(id.enum());case"google.protobuf.EnumValue":return Kj.wellKnown(id.enumValue());case"google.protobuf.Field":return Kj.wellKnown(id.field());case"google.protobuf.FieldCardinality":return Kj.wellKnown(id.fieldCardinality());case"google.protobuf.FieldKind":return Kj.wellKnown(id.fieldKind());case"google.protobuf.FieldMask":return Kj.wellKnown(id.fieldMask());case"google.protobuf.FloatVlaue":return Kj.wellKnown(id.floatValue());case"google.protobuf.Int32Value":return Kj.wellKnown(id.int32Value());case"google.protobuf.Int64Value":return Kj.wellKnown(id.int64Value());case"google.protobuf.ListValue":return Kj.wellKnown(id.listValue());case"google.protobuf.Method":return Kj.wellKnown(id.method());case"google.protobuf.Mixin":return Kj.wellKnown(id.mixin());case"google.protobuf.NullValue":return Kj.wellKnown(id.nullValue());case"google.protobuf.Option":return Kj.wellKnown(id.option());case"google.protobuf.SourceContext":return Kj.wellKnown(id.sourceContext());case"google.protobuf.StringValue":return Kj.wellKnown(id.stringValue());case"google.protobuf.Struct":return Kj.wellKnown(id.struct());case"google.protobuf.Syntax":return Kj.wellKnown(id.syntax());case"google.protobuf.Timestamp":return Kj.wellKnown(id.timestamp());case"google.protobuf.Type":return Kj.wellKnown(id.type());case"google.protobuf.Uint32Value":return Kj.wellKnown(id.uint32Value());case"google.protobuf.Uint64Value":return Kj.wellKnown(id.uint64Value());case"google.protobuf.Value":return Kj.wellKnown(id.value())}}function iz_({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=Zx(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&xS(a.declaration)){let u=Zx(a.typeName)?.arguments??[],l=Object.entries(a.declaration.properties??{}).map(([d,s])=>{let o=s;return typeof s=="string"&&u?.includes(s)&&(o=n.arguments?.[u.indexOf(s)]??s),[d,o]});return Sb.object({extends:pHt(a.declaration.extends).map(d=>oL({typeName:d,file:t})),properties:Vxa({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function nz_({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return Vxe(i)?iz_({generic:i,file:t,typeResolver:r}):Sb.alias({aliasOf:t.parseTypeReference(e),resolvedType:X6E({aliasOf:i,file:t,typeResolver:r})})}function X6E({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return lW.primitive(i.originalTypeReference.primitive);case"container":return lW.container(i.originalTypeReference.container);case"unknown":return lW.unknown();case"named":{let n=xS(i.declaration)?PVt.Object:c1i(i.declaration)?PVt.Union:DVt(i.declaration)?PVt.Enum:dxn(i.declaration)?PVt.UndiscriminatedUnion:jo(i.declaration);return lW.named({name:i.name,shape:n})}}}function az_({union:e,file:t}){let r=e.union.filter((i,n)=>{let a=typeof i=="string"?i:i.type;return e.union.findIndex(u=>(typeof u=="string"?u:u.type)===a)===n});return Sb.undiscriminatedUnion({members:r.map(i=>{let n=t.parseTypeReference(typeof i=="string"?i:i.type);return{type:n.type==="named"?{...n,displayName:typeof i=="string"?Fyo(n.name.originalName):i["display-name"]??Fyo(n.name.originalName)}:n,docs:typeof i=="string"?void 0:i.docs}})})}function oz_(e){let t=[];if(e.extends!=null){let r=typeof e.extends=="string"?[e.extends]:e.extends;t.push(...r)}return e.properties!=null&&t.push(...Object.values(e.properties).map(r=>typeof r=="string"?r:r.type)),t}function xjc({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new zjc}){let n=n3(e,{alias:u=>{let l=typeof u=="string"?u:u.type,d=Zx(l);if(d!=null){let s=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=Zx(o.typeName)?.arguments;if(xS(o.declaration)){let b=oz_(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>oz_(u),discriminatedUnion:u=>{let l=[];return u["base-properties"]!=null&&l.push(...Object.values(u["base-properties"]).map(d=>typeof d=="string"?d:d.type)),l.push(...Object.values(u.union).reduce((d,s)=>{let o=typeof s=="string"?s:s.type;return typeof o=="string"&&d.push(o),d},[])),l},undiscriminatedUnion:u=>Object.values(u.union).reduce((l,d)=>{let s=typeof d=="string"?d:d.type;return typeof s=="string"&&l.push(s),l},[]),enum:()=>[]}),a=[];for(let u of n){let l=q2({type:u,_default:void 0,validation:void 0,visitor:{primitive:()=>[],map:({keyType:d,valueType:s})=>[...d,...s],list:d=>d,optional:d=>d,nullable:d=>d,set:d=>d,named:d=>[d],literal:()=>[],unknown:()=>[]}});for(let d of l){let s=oL({typeName:d,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(Vxe(o.typeName))continue;a.push(...xjc({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var zjc=class{cache=new Set;addTypeName(t){this.cache.add(this.computeCacheKey(t))}hasTypeNameBeenSeen(t){return this.cache.has(this.computeCacheKey(t))}computeCacheKey(t){return t.fernFilepath.allParts.map(r=>r.originalName).join("/")+":"+t.name.originalName}};function uz_({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=lJ(t),d=oL({typeName:e,file:r}),s=xjc({typeDeclaration:t,file:r,typeResolver:i}),o={};xS(t)&&(o=RGi(t.properties??{}));let c=k6E({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:i4E(t),name:d,shape:Z6E({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:e4E({typeDeclaration:t,source:c}),source:c,userProvidedExamples:typeof t!="string"&&t.examples!=null?t.examples.map(b=>({name:b.name!=null?r.casingsGenerator.generateName(b.name):void 0,docs:b.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:b.value,file:r}).resolvedExample,shape:Cjc({typeName:d,example:b.value,typeResolver:i,exampleResolver:n,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[],v2Examples:void 0},descendantFilepaths:new Set(s.map(b=>b.fernFilepath))}}function Z6E({typeDeclaration:e,file:t,typeResolver:r}){return n3(e,{alias:i=>nz_({alias:i,file:t,typeResolver:r}),object:i=>VB_({object:i,file:t}),discriminatedUnion:i=>iI_({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>az_({union:i,file:t}),enum:i=>Sb.enum(feu({_enum:i,file:t}))})}function k6E({file:e,typeDeclaration:t,typeName:r,sourceResolver:i}){if(typeof t=="string"||t.source==null&&t.encoding==null)return;if(t.encoding!=null){let a=rz_({encoding:t.encoding});if(a!=null)return dli.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return dli.proto(tz_({source:n,name:r}))}function e4E({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?t4E(e.encoding):r4E(t)}function t4E(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function r4E(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function i4E(e){if(typeof e!="string"&&"inline"in e)return e.inline}function sz_(e,t){let r=t[e];if(r==null)throw new Uci(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function cz_(e){e.types=Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,a4E({typeDeclaration:r,ir:e})])),e.services=Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>n4E({endpoint:i,ir:e}))}]))}function n4E({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>lz_(r,t))}}}function a4E({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>lz_(r,t))}}}return e}function lz_(e,t){let r=Rjc(e.typeId,t);return fz_({objectTypeDeclaration:r,ir:t})}function Rjc(e,t){let r=sz_(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return Rjc(r.shape.resolvedType.name.typeId,t)}throw new Uci(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function fz_({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=Rjc(i.typeId,t);return fz_({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function dz_({reference:e,referencedIn:t,imports:r}){let[i,n,...a]=e.split(".");if(i==null||a.length>0)return;if(n==null)return{endpointName:i,relativeFilepath:t};let l=r[i];if(l!=null)return{endpointName:n,relativeFilepath:hAi({referencedIn:t,importPath:l})}}var lKi=class{workspace;constructor(t){this.workspace=t}resolveEndpointOrThrow({endpoint:t,file:r}){let i=this.resolveEndpoint({endpoint:t,file:r});if(i==null)throw new Error("Cannot resolve endpoint: "+t+" in file "+r.relativeFilepath);return i}resolveEndpointByMethodAndPath({method:t,path:r}){let i;return D3(this.workspace,(n,a,u)=>{let l=M0({relativeFilepath:n,definitionFile:a,casingsGenerator:vAi,rootApiFile:this.workspace.definition.rootApiFile.contents,defaultUrl:u.defaultUrl});for(let[d,s]of Object.entries(a.service?.endpoints??{}))s.method===t&&s.path===r&&(i={endpointId:d,endpoint:s,file:l})}),TQi(this.workspace,(n,a)=>{let u=M0({relativeFilepath:n,definitionFile:a,casingsGenerator:vAi,rootApiFile:this.workspace.definition.rootApiFile.contents});for(let[l,d]of Object.entries(a.service?.endpoints??{}))d.method===t&&d.path===r&&(i={endpointId:l,endpoint:d,file:u})}),i}resolveEndpoint({endpoint:t,file:r}){let n=new lWi().tryParse(t);if(n!=null)return this.resolveEndpointByMethodAndPath(n);let a=this.getDeclarationOfEndpoint({referenceToEndpoint:t,file:r});if(a==null)return;let u=a.file.definitionFile.service?.endpoints?.[a.endpointName];if(u!=null)return{endpointId:a.endpointName,endpoint:u,file:a.file}}getDeclarationOfEndpoint({referenceToEndpoint:t,file:r}){let i=dz_({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=zae(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:M0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var fKi=class{workspace;constructor(t){this.workspace=t}getDeclarationOrThrow(t,r){let i=this.getDeclaration(t,r);if(i==null)throw new Error("Error does not exist: "+t);return i}getDeclaration(t,r){let i=gMe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=zae(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:M0({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var mMe=class{typeResolver;constructor(t){this.typeResolver=t}resolveAllReferencesInExample({example:t,file:r}){if(typeof t=="string"){let i=this.resolveExample({example:t,file:r});return i==null||typeof i.resolvedExample=="string"?i:this.resolveAllReferencesInExample({example:i.resolvedExample,file:i.file})}else if(Gj(t)){let i={};for(let[n,a]of Object.entries(t)){let u=this.resolveAllReferencesInExample({example:a,file:r});if(u==null)return;i[n]=u.resolvedExample}return{resolvedExample:i}}else if(Array.isArray(t)){let i=[];for(let n of t){let a=this.resolveAllReferencesInExample({example:n,file:r});if(a==null)return;i.push(a.resolvedExample)}return{resolvedExample:i}}return{resolvedExample:t}}resolveAllReferencesInExampleOrThrow({example:t,file:r}){let i=this.resolveAllReferencesInExample({example:t,file:r});if(i==null)throw new Error("Failed to resolve examples");return i}resolveExample({example:t,file:r}){if(typeof t!="string")return{resolvedExample:t,file:r};if(t.startsWith(`\\${YZt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(YZt))return{resolvedExample:t,file:r};let i=this.parseExampleReference(t);if(i==null)return;let n=this.typeResolver.getDeclarationOfNamedType({referenceToNamedType:i.rawTypeReference,file:r});if(n==null||typeof n.declaration=="string"||n.declaration.examples==null)return;let a=n.declaration.examples.find(u=>u.name===i.exampleName);if(a!=null)return this.resolveExample({example:a.value,file:n.file})}resolveExampleOrThrow({example:t,file:r}){let i=this.resolveExample({example:t,file:r});if(i==null)throw new Error("Cannot resolve example: "+t);return i}parseExampleReference(t){let[r,i,n,...a]=t.split(".");if(!(r==null||i==null||a.length>0))return n==null?{rawTypeReference:r.slice(YZt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(YZt.length),exampleName:n}}};var geu=class{typeResolver;endpointResolver;constructor(t,r){this.typeResolver=t,this.endpointResolver=r,this.typeResolver=t,this.endpointResolver=r}resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i}){let n=this.resolveRequestProperty({file:t,endpoint:r,propertyComponents:i});if(n==null)throw new Error("Cannot resolve request property from endpoint: "+r+" in file "+t.relativeFilepath);return n}resolveRequestProperty({file:t,endpoint:r,propertyComponents:i}){let n=this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t});if(n.endpoint.request==null)return;if(typeof n.endpoint.request!="string")return this.resolveRequestPropertyFromInlinedRequest({typeResolver:this.typeResolver,file:n.file,requestType:n.endpoint.request,propertyComponents:i});let a=this.resolveObjectProperty({file:n.file,typeName:n.endpoint.request,propertyComponents:i});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:i,file:t}),property:One.body(a)}}resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i}){let n=this.resolveResponseProperty({file:t,endpoint:r,propertyComponents:i});if(n==null)throw new Error("Cannot resolve response property from endpoint: "+r+" in file "+t.relativeFilepath);return n}resolveResponseProperty({file:t,endpoint:r,propertyComponents:i}){let n=this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t}),a=this.resolveObjectProperty({file:n.file,typeName:(typeof n.endpoint.response!="string"?n.endpoint.response?.type:n.endpoint.response)??"",propertyComponents:i});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:i,file:t}),property:a}}resolveRequestPropertyFromInlinedRequest({typeResolver:t,file:r,requestType:i,propertyComponents:n}){if(n.length===1){let a=n[0]??"",u=i["query-parameters"]?.[a]??void 0;if(u!=null)return{property:One.query(deu({file:r,queryParameterKey:a,queryParameter:u})),propertyPath:void 0}}return this.resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:i,propertyComponents:n})}resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:i,propertyComponents:n}){if(i.body==null)return;if(typeof i.body=="string"){let u=this.resolveObjectProperty({file:r,typeName:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:One.body(u)}}if(JC(i.body)){let u=Mjc({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:One.body(u)}}let a=this.resolveObjectProperty({file:r,typeName:i.body.type,propertyComponents:n});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:One.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return Ejc({typeResolver:this.typeResolver,file:Hxa(n)??t,resolvedType:n,propertyComponents:i})}propertyPathFromPropertyComponents({propertyComponents:t,file:r}){return t.length<=1?[]:t.slice(0,-1).map(i=>r.casingsGenerator.generateName(i))}};var H1=class{workspace;constructor(t){this.workspace=t}resolveTypeOrThrow({type:t,file:r}){let i=this.resolveType({type:t,file:r});if(i==null)throw new Error("Cannot resolve type: "+t+" in file "+r.relativeFilepath);return i}getDeclarationOfNamedTypeOrThrow({referenceToNamedType:t,file:r}){let i=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(i==null)throw new Error("Cannot find declaration of type: "+t+" in file "+r.relativeFilepath);return i}getDeclarationOfNamedType({referenceToNamedType:t,file:r}){let i=gMe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=zae(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=Zx(i.typeName);if(u!=null){for(let l of Object.keys(n.types??{})??[])if(u.name&&l.startsWith(u.name)&&l.endsWith(">")){let d=n.types?.[l];return d!=null?{typeName:l,declaration:d,file:M0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:M0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return q2({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:Kc.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:Kc.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:Kc.container(Py.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:Kc.container(Py.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:Kc.container(Py.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:Kc.container(Py.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:Kc.container(Py.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:Kc.container(Py.literal(n))}),named:n=>{let a=this.getDeclarationOfNamedType({referenceToNamedType:n,file:r});if(a==null)return;let u={typeName:a.typeName,file:a.file.relativeFilepath,reference:n};if(!i.some(l=>l.file===u.file&&l.typeName===u.typeName))return this.resolveNamedTypeFromDeclaration({referenceToNamedType:n,referencedIn:r,rawDeclaration:a,objectPath:[...i,u]})}}})}resolveNamedTypeOrThrow({referenceToNamedType:t,file:r}){let i=this.resolveNamedType({referenceToNamedType:t,file:r});if(i==null)throw new Error("Cannot resolve type: "+t);return i}resolveNamedType({referenceToNamedType:t,file:r}){let i=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(i!=null)return this.resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:i})}resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:i,objectPath:n=[]}){let{declaration:a,file:u}=i;if(s1i(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=Gxa({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||zae(this.workspace,u.relativeFilepath)==null))return{_type:"named",rawName:i.typeName,name:l,declaration:a,filepath:u.relativeFilepath,objectPath:n,originalTypeReference:l,file:u}}};var vHt=class e{static VARIABLE_PREFIX="$";getDeclarationOrThrow(t,r){let i=this.getDeclaration(t,r);if(i==null)throw new Error("Variable does not exist: "+t);return i}getDeclaration(t,r){if(!t.startsWith(e.VARIABLE_PREFIX))return;let i=r.rootApiFile.variables?.[t.substring(1)];if(i!=null)return{declaration:i,file:cpi({casingsGenerator:r.casingsGenerator,rootApiFile:r.rootApiFile})}}getVariableIdOrThrow(t){let r=this.getVariableId(t);if(r==null)throw new Error("Variable reference does not start with "+e.VARIABLE_PREFIX);return r}getVariableId(t){if(t.startsWith(e.VARIABLE_PREFIX))return t.substring(e.VARIABLE_PREFIX.length)}};function Oeu(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function hR({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,exampleGeneration:n,audiences:a,readme:u,packageName:l,version:d,fdrApiDefinitionId:s,sourceResolver:o,disableDynamicExamples:c,dynamicGeneratorConfig:b}){let g=BZ({generationLanguage:t,keywords:r,smartCasing:i}),O=new NGi(a),m=cpi({casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents}),w=(e.definition.rootApiFile.contents.errors??[]).map(ot=>({error:yAi({errorName:ot,file:m}),docs:void 0})),E=new H1(e),q=new lKi(e),A=new geu(E,q),D=new fKi(e),C=new mMe(E),x=new vHt,I=RTa({casingsGenerator:g,rawApiFileSchema:e.definition.rootApiFile.contents})?.environmentsConfig,F={selfHosted:!1,fdrApiDefinitionId:s,apiVersion:JI_({file:m,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:g.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:Uxa(e.definition.rootApiFile.contents.docs),auth:QI_({rawApiFileSchema:e.definition.rootApiFile.contents,file:m,propertyResolver:A,endpointResolver:q}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([ot,at])=>OFe({headerKey:ot,header:at,file:m})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([ot,at])=>OFe({headerKey:ot,header:at,file:m})):[],types:{},errors:{},services:{},constants:xI_(g),environments:I,errorDiscriminationStrategy:ZI_(e.definition.rootApiFile.contents["error-discrimination"],m),basePath:e.definition.rootApiFile.contents["base-path"]!=null?JN(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:s9n({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:m,location:$xe.Root,variableResolver:x}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([ot,at])=>({docs:typeof at!="string"?at.docs:void 0,id:ot,name:m.casingsGenerator.generateName(ot),type:m.parseTypeReference(at)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,audiences:e.definition.rootApiFile.contents.audiences},V=new yeu,K=ot=>{V.addSubpackage(ot.fernFilepath),Cw(ot.definitionFile,{imports:Go,docs:at=>{at!=null&&V.addDocs(ot.fernFilepath,at)},types:at=>{if(at!=null)for(let[me,we]of Object.entries(at)){if(Vxe(me))continue;let jt=uz_({typeName:me,typeDeclaration:we,file:ot,typeResolver:E,exampleResolver:C,sourceResolver:o,workspace:e}),gt=jt.typeDeclaration;n.disabled&&(gt.userProvidedExamples=[],gt.autogeneratedExamples=[]);let qr=jt.descendantFilepaths,lr=jm.generateTypeId(gt.name);F.types[lr]=gt,V.addType(lr,gt),O.addType({declaredTypeName:gt.name,descendantTypeIds:gt.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:jt.propertiesByAudience,descendantFilepaths:qr}),O.markTypeForAudiences(gt.name,UB_(we))}},errors:at=>{if(at==null)return;if(e.definition.rootApiFile.contents["error-discrimination"]==null)throw new Error("error-discrimination is missing in api.yml but there are declared errors.");for(let[we,jt]of Object.entries(at)){let gt=YI_({errorName:we,errorDeclaration:jt,file:ot,typeResolver:E,exampleResolver:C,workspace:e}),qr=jm.generateErrorId(gt.name);F.errors[qr]=gt,V.addError(qr,gt),O.addError(gt)}},service:at=>{if(at==null)return;let me=CI_({rootDefaultUrl:ot.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:F.pathParameters,serviceDefinition:at,file:ot,errorResolver:D,typeResolver:E,propertyResolver:A,exampleResolver:C,sourceResolver:o,globalErrors:w,variableResolver:x,workspace:e}),we=jm.generateServiceId(me.name);F.services[we]=me,V.addService(we,me);let jt={};me.endpoints.forEach(gt=>{n.disabled&&(gt.autogeneratedExamples=[],gt.userSpecifiedExamples=[]);let qr=at.endpoints[gt.name.originalName];O.addEndpoint(me,gt,qr),jt[gt.name.originalName]=gt}),at.audiences!=null&&O.markEndpointForAudience(me.name,me.endpoints,at.audiences),Object.entries(at.endpoints).map(([gt,qr])=>{let lr=jt[gt];lr!=null&&qr.audiences!=null&&O.markEndpointForAudience(me.name,[lr],qr.audiences)})},webhooks:at=>{if(at==null)return;let me=jm.generateWebhookGroupId(ot.fernFilepath),we=ez_({webhooks:at,file:ot,typeResolver:E,exampleResolver:C,workspace:e}),jt={};for(let gt of we)jt[gt.name.originalName]=gt;Object.entries(at).forEach(([gt,qr])=>{let lr=jt[gt];lr!=null&&(O.addWebhook(ot.fernFilepath,lr,qr),qr.audiences!=null&&O.markWebhookForAudiences(ot.fernFilepath,lr,qr.audiences))}),F.webhookGroups[me]=we,V.addWebhookGroup(me,ot.fernFilepath)},channel:at=>{if(at==null)return;let me=jm.generateWebSocketChannelId(ot.fernFilepath),we=KI_({channel:at,file:ot,variableResolver:x,typeResolver:E,exampleResolver:C,workspace:e});O.addChannel(ot.fernFilepath,me,we,at),at.audiences!=null&&O.markChannelForAudiences(ot.fernFilepath,me,at.audiences),F.websocketChannels!=null&&(F.websocketChannels[me]=we,V.addWebSocketChannel(me,ot.fernFilepath))}})};D3(e,(ot,at,me)=>{K(M0({relativeFilepath:ot,definitionFile:at,casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:me.defaultUrl}))}),TQi(e,(ot,at)=>{if(at.navigation!=null)if(typeof at.navigation=="string")V.addPackageRedirection({from:$ae({relativeFilepath:ot,casingsGenerator:g}),to:$ae({relativeFilepath:EN(axe(ot),Oy.of(at.navigation)),casingsGenerator:g})});else{let me=at.navigation.map(we=>jm.generateSubpackageId($ae({relativeFilepath:EN(axe(ot),Oy.of(we)),casingsGenerator:g})));ot===TS?V.sortRootPackage(me):V.sortSubpackage(jm.generateSubpackageId($ae({relativeFilepath:ot,casingsGenerator:g})),me)}}),F.serviceTypeReferenceInfo=u4E(O),cz_(F);let Y=n.disabled?F:xTa({ir:F,exampleGeneration:n}),Z=e.definition.rootApiFile.contents,oe=I?.environments._visit({singleBaseUrl:ot=>ot.environments.filter(at=>Oeu(at.id,Z.environments)!=null).length===0,multipleBaseUrls:ot=>ot.environments.filter(at=>Oeu(at.id,Z.environments)!=null).length===0,_other:()=>!1});I?.environments.environments.forEach(ot=>{O.markEnvironmentForAudiences(ot,Oeu(ot.id,Z.environments)??[],oe)});let pe=O.hasNoAudiences()?void 0:O.build(),de=Ioc(Y,pe),Oe=e.definition.rootApiFile.contents.auth!=null&&Object.values(de.services).every(ot=>ot.endpoints.every(at=>at.auth)),Ue=Object.values(de.services).some(ot=>ot.endpoints.some(at=>at.response?.body?.type==="streaming")),wt=Object.values(de.services).some(ot=>ot.endpoints.some(at=>at.pagination!=null)),De=Object.values(de.services).some(ot=>ot.endpoints.some(at=>at.response?.body?.type==="fileDownload")),Te={isAuthMandatory:Oe,hasStreamingEndpoints:Ue,hasPaginatedEndpoints:wt,hasFileDownloadEndpoints:De,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:d!=null&&l!=null?{header:"User-Agent",value:`${l}/${d}`}:void 0}},xt=u!=null?kI_({readme:u,services:F.services}):void 0,Pe=o4E({...de,...V.build(pe),sdkConfig:Te,readmeConfig:xt});return{...Pe,dynamic:II_({ir:Pe,generatorConfig:b,disableExamples:c,generationLanguage:t,smartCasing:i})}}function o4E(e){let t=r=>{if(!r||typeof r!="object")return r;if(Array.isArray(r))return r.map(t);for(let i in r){let n=r[i];i==="docs"&&typeof n=="string"?r[i]=Uxa(n):n&&typeof n=="object"&&t(n)}return r};return t(e)}function u4E(e){let t={},r=[],i=e.getTypesReferencedByService();for(let[n,a]of Object.entries(i)){if(a.size===1){let u=a.values().next().value;if(u==null)break;t[u]===void 0&&(t[u]=[]),t[u]?.push(n);continue}r.push(n)}return{typesReferencedOnlyByService:t,sharedTypes:r}}function pz_(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var hz_=ui(wCn(),1);var _z_=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function bHt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,hz_.default)(e,{special:_z_}).replace(/V\s(\d)/g,"V$1")}function Yxa(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&pz_(e),r._other(e))}}}function Mir(e){return typeof e.subpackageId=="string"}function c9n(e,t){return`${e} ${tB(t)}`}function tB(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function mFe(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var Njc="__package__",gAi=class e{api;context;static create(t,r){return new e(t,r)}#e=new Map;#t=new Map;#r=new Map;#n=new Map;#i=new Map;#a=new Map;#o=new Map;#s=new Map;#f=new Map;#u=new Map;#l=new Map;static getSubpackageId(t){return Mir(t)?t.subpackageId:Njc}getSubpackageByIdOrLocator(t){if(t==null)return;let r=Y6.SubpackageId(t),i=Y6.SubpackageId(`subpackage_${d_(t)}`);return r===Njc?this.api.rootPackage:this.api.subpackages[r]??this.#l.get(r)??this.api.subpackages[i]??this.#l.get(i)}resolveSubpackage(t){if(t!=null){for(;t?.pointsTo!=null;)t=this.api.subpackages[t.pointsTo];return t}}constructor(t,r){this.api=t,this.context=r,[t.rootPackage,...Object.values(t.subpackages)].forEach(i=>{let n=Y6.SubpackageId(e.getSubpackageId(i)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map};this.#o.set(n,a),i.endpoints.forEach(u=>{a.endpoints.set(u.id,u);let l=e.createEndpointId(u,n);this.#e.set(l,u);let d=[],s=[u.method];u.response?.type.type==="stream"&&s.push("STREAM"),s.forEach(o=>{d.push(`${o} ${tB(u.path.parts)}`),d.push(`${o} ${mFe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${lb(c.baseUrl,tB(u.path.parts))}`),d.push(`${o} ${lb(c.baseUrl,mFe(u.path.parts))}`);let b=meu(c);b!=null&&(d.push(`${o} ${lb(b,tB(u.path.parts))}`),d.push(`${o} ${lb(b,mFe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering endpoint locator: ${o}`),this.#s.set(o,u)})}),i.websockets.forEach(u=>{a.webSockets.set(u.id,u);let l=e.createWebSocketId(u,n);this.#t.set(l,u);let d=[];["GET","WSS"].forEach(o=>{d.push(`${o} ${tB(u.path.parts)}`),d.push(`${o} ${mFe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${lb(c.baseUrl,tB(u.path.parts))}`),d.push(`${o} ${lb(c.baseUrl,mFe(u.path.parts))}`);let b=meu(c);b!=null&&(d.push(`${o} ${lb(b,tB(u.path.parts))}`),d.push(`${o} ${lb(b,mFe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering websocket locator: ${o}`),this.#f.set(o,u)})}),i.webhooks.forEach(u=>{a.webhooks.set(u.id,u),this.#r.set(e.createWebhookId(u,n),u)})}),this.#e.forEach((i,n)=>{this.#n.set(i,n)}),this.#t.forEach((i,n)=>{this.#i.set(i,n)}),this.#r.forEach((i,n)=>{this.#a.set(i,n)}),this.#c(t.rootPackage,[])}#c(t,r){if(t==null)return;let i=Mir(t)?[...r,t.name]:r,n=i.length===0?[Njc]:i;if([n.join("."),n.join("/"),`${n.join(".")}.yml`].forEach(u=>{this.context?.logger.trace(`Registering subpackage locator: ${u}`),this.#l.set(u,t)}),t.pointsTo!=null)return this.#c(this.api.subpackages[t.pointsTo],i);t.endpoints.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering endpoint locator: ${s}`),this.#s.set(s,u)})}),t.websockets.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering websocket locator: ${s}`),this.#f.set(s,u)})}),t.webhooks.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering webhook locator: ${s}`),this.#u.set(s,u)})}),t.subpackages.forEach(u=>{this.#c(this.api.subpackages[u],i)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#r}get endpointsByLocator(){return this.#s}get webSocketsByLocator(){return this.#f}get webhooksByLocator(){return this.#u}get subpackages(){return this.#o}get subpackagesByLocator(){return this.#l}getEndpointId(t){return this.#n.get(t)}getWebSocketId(t){return this.#i.get(t)}getWebhookId(t){return this.#a.get(t)}static createEndpointId(t,r){return So.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return So.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return So.WebhookId(`${r}.${t.id}`)}};function meu(e){if(e!=null){if(e.baseUrl.startsWith("/"))return e.baseUrl;if(e.baseUrl.startsWith("http")||e.baseUrl.startsWith("ws"))try{return new URL(e.baseUrl).pathname}catch{return}}}var l9n=ui(lZo(),1),vz_=ui(fZo(),1);function yz_(e){let t=e.split(".")[0];if(t==null)return;let i=/(^\d{1,4})-(\d{1,2})-(\d{1,4})/.exec(t)?.[0];if(i!=null)try{return new Date(i)}catch{}}l9n.default.extend(vz_.default);var s4E="Changelog",c4E=["summary","index","overview"],fpi=class{markdownToFullSlug;markdownToNoIndex;changelogFiles;docsWorkspace;idgen;constructor(t,r,i,n,a){this.markdownToFullSlug=t,this.markdownToNoIndex=r,this.changelogFiles=i,this.docsWorkspace=n,this.idgen=a}toChangelogNode(t){let r=t.title??s4E,i=[],n;for(let b of this.changelogFiles??[]){let g=QBs(b.split("/"));if(g==null)continue;let O=yz_(g);if(O==null){let w=g.split(".")[0]?.toLowerCase();w!=null&&c4E.includes(w)&&(n=b);continue}let m=this.toRelativeFilepath(b);i.push({date:O,pageId:So.PageId(m),absoluteFilepath:b})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??Tq(r)}),u=n!=null?this.markdownToNoIndex.get(n):void 0,l=i.map(b=>{let g=l9n.default.utc(b.date);return{id:this.idgen.get(b.pageId),type:"changelogEntry",title:g.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(b.absoluteFilepath)?.split("/"),urlSlug:g.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:b.date.toISOString(),pageId:b.pageId,noindex:this.markdownToNoIndex.get(b.absoluteFilepath),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),d=Fjc(l,b=>b.date,"desc"),s=n!=null?So.PageId(this.toRelativeFilepath(n)):void 0,o=this.idgen.get(s??"changelog"),c=this.groupByYear(o,d,a);return{id:o,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:c,overviewPageId:s,noindex:u,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:void 0}}orUndefined(){return this.changelogFiles!=null&&this.changelogFiles.length>0?this:void 0}groupByYear(t,r,i){let n=new Map;for(let a of r){let u=l9n.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return Fjc(Array.from(n.entries()).map(([a,u])=>{let l=i.append(a.toString()).get(),d=this.idgen.get(`${t}/year/${a}`);return{id:d,type:"changelogYear",title:a.toString(),year:a,slug:l,icon:void 0,hidden:void 0,children:this.groupByMonth(d,u,i),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),"year","desc")}groupByMonth(t,r,i){let n=new Map;for(let a of r){let u=l9n.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return Fjc(Array.from(n.entries()).map(([a,u])=>{let l=(0,l9n.default)(new Date(0,a-1));return{id:this.idgen.get(`${t}/month/${a}`),type:"changelogMonth",title:l.format("MMMM YYYY"),month:a,slug:i.append(a.toString()).get(),icon:void 0,hidden:void 0,children:u,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),"month","desc")}toRelativeFilepath(t){if(t!=null)return Bq(this.docsWorkspace.absoluteFilePath,t)}};function Fjc(e,t,r="asc"){return e.concat().sort((i,n)=>{let a=typeof t=="function"?t(i):i[t],u=typeof t=="function"?t(n):n[t];return a<u?r==="asc"?-1:1:a>u?r==="asc"?1:-1:0})}function Peu(e){if(e)return{environments:e.environments!=null&&e.environments.length>0?e.environments.map(t=>So.V1.EnvironmentId(t)):void 0,button:e.button!=null&&e.button.href?{href:So.V1.Url(e.button.href)}:void 0,"limit-websocket-messages-per-connection":e.limitWebsocketMessagesPerConnection!=null?e.limitWebsocketMessagesPerConnection:void 0}}function Xxa({child:e,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i}){if(e.type==="apiPackage"){let n=So.V1.SlugGenerator.init(e.slug),u=(t.get(e.id)??[]).flatMap(s=>r(s,n)),l=e.children.map(s=>Xxa({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),d=i(l,u);return{...e,children:d,pointsTo:void 0}}return e}function f9n({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)return e;let a=[],u=new Map;return e.forEach(l=>{if(l.type!=="endpoint"){a.push(l);return}let d=t(l.endpointId);if(d==null)throw new Error(`Endpoint ${l.endpointId} not found`);let s=`${d.method} ${r(d)}`,o=u.get(s);if(u.set(s,l),o==null||o.isResponseStream===l.isResponseStream){a.push(l);return}let c=a.indexOf(o),b=l.isResponseStream?l:o,g=l.isResponseStream?o:l,O={id:So.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[c]=O}),a}function jeu({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return f9n({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function Air(e,t){if(t!=null)return Bq(e.absoluteFilePath,t)}function weu({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let l=So.V1.PageId(Air(e,t.absolutePath)),d=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??Tq(t.title)});return{id:i.get(l),type:"page",pageId:l,title:t.title,slug:d.get(),icon:t.icon,hidden:u||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var Seu=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;workspace;hideChildren;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Map;#o=[];#s;#f;#u;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=u,this.markdownFilesToNoIndex=l,this.workspace=s,this.hideChildren=o,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=So.V1.ApiDefinitionId(r.id),this.#e=gAi.create(r,a),this.#u=d,this.#s=this.apiSection.overviewAbsolutePath!=null?So.V1.PageId(Air(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#f=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Tq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#l(this.apiSection.navigation,this.#e.api.rootPackage,this.#f)),this.#o=this.#O(this.#o.map(b=>this.#v(b)),this.#P(this.#e.api.rootPackage,this.#f))}get(){let t=So.V1.followRedirects(this.#o),r=new fpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#u).orUndefined();return{id:this.#u.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#s,paginated:this.apiSection.paginated,slug:this.#f.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#f,viewers:void 0,hidden:this.hideChildren}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#g(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#l(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?gAi.getSubpackageId(r):void 0;return t.map(a=>Yxa(a)._visit({link:u=>({id:this.#u.get(u.url),type:"link",title:u.text,icon:u.icon,url:So.Url(u.url)}),page:u=>this.#c(u,i),package:u=>this.#p(u,i),section:u=>this.#h(u,i),item:({value:u})=>this.#_(u,n,i),endpoint:u=>this.#y(u,n,i)})).filter(yv)}#c(t,r){return weu({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#u,hideChildren:this.hideChildren})}#p(t,r){let i=t.overviewAbsolutePath!=null?So.V1.PageId(Air(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=gAi.getSubpackageId(a),l=this.#u.get(i??`${this.apiDefinitionId}:${u}`);this.#i.has(u)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${u}`),this.#i.add(u),this.#a.set(l,[u]);let d=t.slug??(Mir(a)?a.urlSlug:this.apiSection.slug??Tq(this.apiSection.title)),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,a,s);return{id:l,type:"apiPackage",children:o,title:t.title??(Mir(a)?a.displayName??bHt(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??Tq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#l(t.contents,void 0,l);return{id:this.#u.get(i??`${this.apiDefinitionId}:${Tq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#h(t,r){let i=t.overviewAbsolutePath!=null?So.V1.PageId(Air(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,u=this.#u.get(i??n??r.get()),l=t.referencedSubpackages.map(c=>{let b=this.#e.getSubpackageByIdOrLocator(c);return b!=null?gAi.getSubpackageId(b):void 0}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(yv);this.#a.set(u,l),l.forEach(c=>{this.#i.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#i.add(c)});let d=t.slug??Tq(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,void 0,s);return{id:u,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:a,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#_(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(d_(t));if(n!=null){let a=gAi.getSubpackageId(n),u=this.#u.get(`${this.apiDefinitionId}:${a}`);this.#i.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#i.add(a),this.#a.set(u,[a]);let l=Mir(n)?n.urlSlug:"",d=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:Mir(n)?n.displayName??bHt(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#y({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#y(t,r,i){let n=(r!=null?this.#e.subpackages.get(Y6.SubpackageId(r))?.endpoints.get(Y6.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let l=this.#e.getEndpointId(n);if(l==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${c9n(n.method,n.path.parts)}. Got undefined.`);else{this.#t.has(l)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${l}`),this.#t.add(l);let d=t.slug!=null?i.append(t.slug):i.apply(n);return{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"endpoint",method:n.method,endpointId:l,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??tB(n.path.parts),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let a=(r!=null?this.#e.subpackages.get(Y6.SubpackageId(r))?.webSockets.get(Y6.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let l=this.#e.getWebSocketId(a);if(l==null)this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);else return this.#r.has(l)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${l}`),this.#r.add(l),{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"webSocket",webSocketId:l,title:t.title??a.name??tB(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(a.availability),playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(Y6.SubpackageId(r))?.webhooks.get(Y6.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(So.V1.WebhookId(t.endpoint));if(u!=null){let l=this.#e.getWebhookId(u);if(l==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#n.has(l)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${l}`),this.#n.add(l),{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"webhook",webhookId:l,method:u.method,title:t.title??u.name??lb("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#O(t,r){return jeu({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>tB(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#v(t){return Xxa({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(r,i)=>this.#j(r,i),mergeAndFilterChildren:this.#O.bind(this)})}#P(t,r){let i=[];return t.endpoints.forEach(n=>{let a=this.#e.getEndpointId(n);if(a==null){this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${c9n(n.method,n.path.parts)}. Got undefined.`);return}if(this.#t.has(a))return;let u=r.apply(n);i.push({id:So.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??tB(n.path.parts),slug:u.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null){this.taskContext.logger.error(`Expected WebSocket ID for ${n.id}. Got undefined.`);return}this.#r.has(a)||i.push({id:So.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??tB(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(n.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(n=>{let a=this.#e.getWebhookId(n);if(a==null){this.taskContext.logger.error(`Expected Webhook ID for ${n.id}. Got undefined.`);return}this.#n.has(a)||i.push({id:So.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??bHt(n.id),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#i.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=Mir(a)?r.apply(a):r,l=this.#j(n,u);l.length>0&&i.push({id:So.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:l,title:Mir(a)?a.displayName??bHt(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)})),i}#j(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#P(i,r)}#g(t){return Peu(t)}mergeEndpointPairs(t){return f9n({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>tB(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Deu=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[d_(r).toLowerCase()]=i,this.#e[`subpackage_${d_(r).toLowerCase()}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${lb(a.baseUrl,tB(i.path))}`]=i,this.#r[`${n} ${lb(a.baseUrl,mFe(i.path))}`]=i;let u=meu(a);u!=null&&(this.#r[`${n} ${lb(u,tB(i.path))}`]=i,this.#r[`${n} ${lb(u,mFe(i.path))}`]=i)}),this.#r[`${i.method} ${tB(i.path)}`]=i,this.#r[`${i.method} ${mFe(i.path)}`]=i}for(let[r,i]of Object.entries(t.webhooks))this.#t[r]=i,this.#t[r.replace("webhook_","")]=i,this.#t[r.replace("webhook_","subpackage_")]=i,this.#t[`${i.method} ${i.path.join("/")}`]=i;for(let[r,i]of Object.entries(t.websockets))this.#n[r]=i,this.#n[r.replace("websocket_","")]=i,this.#n[r.replace("websocket_","subpackage_")]=i,this.#n[`STREAM ${tB(i.path)}`]=i,this.#n[`STREAM ${mFe(i.path)}`]=i}getSubpackageByLocator(t){if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"].some(i=>t.includes(i)))return;let r=t.replace(".yml","").replace(".yaml","");return this.#e[r]}getWebhookByLocator(t,r){return this.#t[t]??this.#t[`${r}.${t}`]??this.#t[`webhook_${r}.${t}`]}getEndpointByLocator(t,r){return this.#r[t]??this.#r[`${r}.${t}`]??this.#r[`endpoint_${r}.${t}`]}getWebSocketByLocator(t,r){return this.#n[t]??this.#n[`${r}.${t}`]??this.#n[`websocket_${r}.${t}`]}};function Zxa({item:e,parentSlug:t}){return t.apply({urlSlug:Tq(e.id.split(".").pop()??"")}).get()}var kxa=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;hideChildren;apiDefinitionId;#e;#t;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#l;#c=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.markdownFilesToNoIndex=d,this.hideChildren=o,this.#e=r,this.#t=new Deu(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=So.V1.ApiDefinitionId(r.id),this.#l=s,this.#f=this.apiSection.overviewAbsolutePath!=null?So.V1.PageId(Air(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Tq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#p(this.apiSection.navigation,void 0,this.#u)),this.#s=this.#P(this.#s.map(b=>this.#j(b)),this.#g(this.#e,this.#u))}get(){let t=So.V1.followRedirects(this.#s),r=new fpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#l).orUndefined();return{id:this.#l.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#S(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#p(t,r,i){return t.map(n=>Yxa(n)._visit({link:a=>({id:this.#l.get(a.url),type:"link",title:a.text,icon:a.icon,url:So.Url(a.url)}),page:a=>this.#h(a,i),package:a=>this.#_(a,i),section:a=>this.#y(a,i),item:({value:a})=>this.#O(a,r,i),endpoint:a=>this.#v(a,r,i)})).filter(yv)}#h(t,r){return weu({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#l,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#_(t,r){let i=t.overviewAbsolutePath!=null?So.V1.PageId(Air(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#t.getSubpackageByLocator(t.package);if(a!=null){let u=this.#l.get(i??`${this.apiDefinitionId}:${a.id}`);this.#a.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#a.add(a.id),this.#o.set(u,[a.id]);let l=t.slug??Tq(a.name),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#p(t.contents,a.id,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??bHt(a.name),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#c.set(a.id,o),o}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??Tq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#p(t.contents,t.package,l),s={id:this.#l.get(i??`${this.apiDefinitionId}:${Tq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#c.set(t.package,s),s}}#y(t,r){let i=t.overviewAbsolutePath!=null?So.V1.PageId(Air(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#l.get(i??n??r.get()),u=t.referencedSubpackages.map(c=>{let b=this.#t.getSubpackageByLocator(c);return b?.id}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(yv);this.#o.set(a,u),u.forEach(c=>{this.#a.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#a.add(c)});let l=t.slug??Tq(t.title),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#p(t.contents,t.title,d),o={id:a,type:"apiPackage",children:s,title:t.title,slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return u.forEach(c=>{this.#c.set(c,o)}),o}#O(t,r,i){t=t.trim();let n=this.#t.getSubpackageByLocator(t);if(n!=null){let a=n.id,u=this.#l.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#a.add(a),this.#o.set(u,[a]);let l=Tq(n.name),d=i.apply({urlSlug:l}),s={id:u,type:"apiPackage",children:[],title:n.displayName??bHt(n.name),slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#c.set(a,s),s}return this.#v({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#v(t,r,i){let n=this.#t.getEndpointByLocator(t.endpoint,r);if(n!=null)if(this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${n.id}`),n.id==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${c9n(n.method,n.path)}. Got undefined.`);else{this.#r.add(n.id);let l=t.slug!=null?i.append(t.slug).get():Zxa({item:n,parentSlug:i});return{id:this.#l.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??tB(n.path),slug:l,icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#t.getWebSocketByLocator(t.endpoint,r);if(a!=null)if(this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${a.id}`),a.id==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}else return this.#n.add(a.id),{id:this.#l.get(`${this.apiDefinitionId}:${a.id}`),type:"webSocket",webSocketId:a.id,title:t.title??a.displayName??tB(a.path),slug:t.slug!=null?i.append(t.slug).get():Zxa({item:a,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(a.availability),playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};let u=this.#t.getWebhookByLocator(t.endpoint,r);if(u!=null)if(this.#i.has(u.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${u.id}`),u.id==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#i.add(u.id),{id:this.#l.get(`${this.apiDefinitionId}:${u.id}`),type:"webhook",webhookId:u.id,method:u.method,title:t.title??u.displayName??lb("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():Zxa({item:u,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#P(t,r){return jeu({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>tB(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#j(t){return Xxa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#E(r,i),mergeAndFilterChildren:this.#P.bind(this)})}#g(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(!this.#a.has(n)){let u=this.#w(n,a,r);u!=null&&i.push(u)}}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Endpoint ID for ${a.id} at path: ${c9n(a.method,a.path)}. Got undefined.`);return}!this.#r.has(JA.EndpointId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#m(n,a,r,i)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}!this.#n.has(JA.WebSocketId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#A(n,a,r,i)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}!this.#i.has(JA.WebhookId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#d(n,a,r,i)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)}),i}#w(t,r,i){let n=So.V1.SlugGenerator.init(i.get()).apply({urlSlug:Tq(r.name)}),a=this.#E(t,n),u={id:So.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??bHt(r.name),slug:n.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#c.set(t,u),a.length>0?u:void 0}#D(t,r,i,n){r.slug=Zxa({item:t,parentSlug:i}),n.push(r)}#m(t,r,i,n){let a={id:So.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"endpoint",method:r.method,endpointId:JA.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??tB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#A(t,r,i,n){let a={id:So.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webSocket",webSocketId:JA.WebSocketId(t),title:r.displayName??tB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(r.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#d(t,r,i,n){let a={id:So.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webhook",webhookId:JA.WebhookId(t),method:r.method,title:r.displayName??bHt(r.id),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#T(t){let r=Object.fromEntries(Object.entries(this.#e?.subpackages??{}).filter(([u,l])=>t===this.#e.id?l.id.split(".").length===1:l.id!=null&&l.id.includes(t)&&l.id!==t&&l.id.split(".").length===t.split(".").length+1)),i=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===JA.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===JA.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===JA.api.v1.SubpackageId(t)));return{id:JA.ApiDefinitionId(t),endpoints:i,websockets:n,webhooks:a,types:{},subpackages:r,auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#E(t,r){let i=t!=null?this.#T(t):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#g(i,r)}#S(t){return Peu(t)}mergeEndpointPairs(t){return f9n({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>tB(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var bz_=ui(require("crypto"),1);function l4E(e){return bz_.default.createHash("sha256").update(e).digest("hex")}var Eeu=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),l4E(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return So.V1.NodeId(this.#n(t))}};function Meu(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0}}var Aeu=ui(PEe(),1);var Ljc=ui(PEe(),1);function gz_(e,t,r){if(e.schemes.length>0&&e.schemes[0]!=null){let i=e.schemes[0];switch(i.type){case"basic":return{type:"basicAuth",passwordName:i.password.originalName,usernameName:i.username.originalName,description:e.docs};case"bearer":return{type:"bearerAuth",tokenName:i.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:i.name.wireValue,nameOverride:i.name.name.originalName,prefix:i.prefix,description:e.docs};case"oauth":{let n=i.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(a=>a.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Ljc.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:Ljc.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:jo(i)}}}var cm=ui(PEe(),1);var OAi=ui(PEe(),1);function mz_(e){return e._visit({alias:t=>({type:"alias",value:jE(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:e4(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>OAi.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:OAi.FernRegistry.PropertyKey(r.name.wireValue),valueType:jE(r.valueType),availability:e4(r.availability),propertyAccess:r.propertyAccess})),extraProperties:p4E(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:OAi.FernRegistry.PropertyKey(i.name.wireValue),valueType:jE(i.valueType),availability:e4(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?e4(i.availability):void 0,additionalProperties:Gs.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[OAi.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:OAi.FernRegistry.PropertyKey(n.name.wireValue),valueType:jE(n.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:jE(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function jE(e){return e._visit({container:t=>Gs.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:jE(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:jE(r),valueType:jE(i)}),optional:r=>({type:"optional",itemType:jE(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:jE(r)}),set:r=>({type:"set",itemType:jE(r)}),literal:r=>Gs.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:OAi.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Gs.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>d4E(t.v2),float:()=>Oz_(t.v2),double:()=>Oz_(t.v2),string:()=>f4E(t.v2),long:()=>({type:"long",default:t.v2?.type==="long"?t.v2.default:void 0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),uint:()=>({type:"uint"}),uint64:()=>({type:"uint64"}),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function f4E(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function d4E(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="integer"?e.default:void 0}}function Oz_(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="double"?e.default:void 0}}function p4E(e){return typeof e=="boolean"?e?Kc.unknown():void 0:typeof e=="string"?{type:"id",value:OAi.FernRegistry.TypeId(e),default:void 0}:jE(e)}function Vjc(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?h4E(r,t):[],webhooks:i!=null?_4E(i):[],websockets:n!=null?[y4E(n,t)]:[],types:e.types.map(a=>cm.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>cm.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?cm.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function _4E(e){return e.map(t=>{let r=[];return t.v2Examples!=null?(r.push(...Object.values(t.v2Examples.userSpecifiedExamples)),r.push(...Object.values(t.v2Examples.autogeneratedExamples))):r.push(...t.examples?.map(i=>({payload:i.payload.jsonExample}))??[]),{description:t.docs??void 0,id:cm.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??oUi(t.name.originalName),headers:t.headers.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:jE(i.valueType),availability:e4(i.availability)})),payload:w4E(t.payload),examples:r}})}function h4E(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let l,d=i.v2Examples.userSpecifiedExamples,s=i.v2Examples.autogeneratedExamples,o=Object.keys(d).length>1;for(let[b,g]of Object.entries(d))l=Pz_({shouldUseExampleName:o,exampleName:b,example:g,irEndpoint:i}),l!=null&&a.push(l);let c=Object.keys(s).length>1;for(let[b,g]of Object.entries(s))l=Pz_({shouldUseExampleName:c,exampleName:b,example:g,irEndpoint:i}),l!=null&&a.push(l)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>Ujc({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(yv));else if(n!=null){let l=Ujc({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=ITa({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let d=Ujc({autogeneratedExample:l,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={slug:void 0,availability:e4(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:O4E(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?cm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?v4E({environmentsConfig:t.environments,endpoint:i}):void 0,id:cm.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.source?.type=="proto"?i.name.originalName:i.displayName??oUi(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:cm.FernRegistry.PropertyKey(l.name.originalName),type:jE(l.valueType),availability:void 0})),parts:[...d9n(i.basePath),...d9n(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:cm.FernRegistry.PropertyKey(l.name.originalName),type:jE(l.valueType),availability:void 0})),parts:[...t.basePath!=null?d9n(t.basePath):[],...d9n(e.basePath),...d9n(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:jE(l.valueType),availability:e4(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:jE(l.valueType),availability:e4(l.availability)})),request:i.requestBody!=null?m4E(i.requestBody):void 0,response:i.response!=null?P4E(i.response):void 0,errors:void 0,errorsV2:j4E(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:()=>({type:"grpc",methodName:i.id}),_other:()=>{}})};r.push(u)}return r}function y4E(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let i=Object.values(e.v2Examples.userSpecifiedExamples),n=Object.values(e.v2Examples.autogeneratedExamples),a=i.length>0?i[0]:n[0];a!=null&&r.push({name:"",description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(u=>({type:cm.FernRegistry.api.v1.WebSocketMessageId(u.type),body:u.body}))??[]})}else r=e.examples.map(i=>({name:i.name?.originalName,description:i.docs,path:i.url,pathParameters:i.pathParameters.reduce((n,a)=>(n[cm.FernRegistry.PropertyKey(a.name.originalName)]=a.value.jsonExample,n),{}),queryParameters:i.queryParameters.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),headers:i.headers.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),messages:i.messages.map(n=>({type:cm.FernRegistry.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}));return{auth:e.auth,availability:e4(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?cm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?b4E({environmentsConfig:t.environments,channel:e}):[],id:cm.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??oUi(e.name.originalName),path:{pathParameters:e.pathParameters.map(i=>({description:i.docs??void 0,key:cm.FernRegistry.PropertyKey(i.name.originalName),type:jE(i.valueType),availability:void 0})),parts:d9n(e.path)},headers:e.headers.map(i=>({key:i.name.wireValue,type:jE(i.valueType),description:i.docs,availability:e4(i.availability)})),queryParameters:e.queryParameters.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:jE(i.valueType),availability:e4(i.availability)})),messages:e.messages.map(i=>({type:cm.FernRegistry.api.v1.WebSocketMessageId(i.type),displayName:i.displayName,origin:i.origin,body:S4E(i.body),description:i.docs,availability:e4(i.availability)})),examples:r}}function e4(e){if(e!=null)switch(e.status){case"DEPRECATED":return cm.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return cm.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return cm.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return cm.FernRegistry.Availability.Beta;default:jo(e.status)}}function v4E({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl,n=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:cm.FernRegistry.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(n!=null)return n.flatMap(u=>r.environments.map(l=>{let d=l.urls[u];if(d==null)throw new Error(`Expected environment ${l.id} to contain url for ${u}`);return{id:cm.FernRegistry.EnvironmentId(u),baseUrl:d}})).filter((u,l,d)=>l===d.findIndex(s=>s.id===u.id&&s.baseUrl===u.baseUrl));if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let u=a.urls[i];if(u==null)throw new Error(`Expected environment ${a.id} to contain url for ${i}`);return{id:cm.FernRegistry.EnvironmentId(a.id),baseUrl:u}});default:jo(r)}}function b4E({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:cm.FernRegistry.EnvironmentId(n.id),baseUrl:g4E(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:cm.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:jo(r)}}function g4E(e,t){return e.replace(/^[^:]+/,t)}function O4E(e){return Gs.http.HttpMethod._visit(e,{get:()=>cm.FernRegistry.HttpMethod.Get,post:()=>cm.FernRegistry.HttpMethod.Post,put:()=>cm.FernRegistry.HttpMethod.Put,patch:()=>cm.FernRegistry.HttpMethod.Patch,delete:()=>cm.FernRegistry.HttpMethod.Delete,head:()=>cm.FernRegistry.HttpMethod.Get,_other:()=>{throw new Error("Unknown http method: "+e)}})}function d9n(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:cm.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function m4E(e){let t=Gs.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??_M.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>cm.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:cm.FernRegistry.PropertyKey(i.name.wireValue),valueType:jE(i.valueType),availability:e4(i.availability),propertyAccess:void 0})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??_M.APPLICATION_JSON,shape:{type:"reference",value:jE(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:u=>({type:"file",key:cm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:cm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:cm.FernRegistry.PropertyKey(n.name.wireValue),valueType:jE(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:e4(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(yv)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function P4E(e){if(e.body==null)return;let t,r=Gs.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:jE(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:jE(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:jE(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function j4E(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:jE(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:n.examples.map(a=>({name:a.name?.originalName,responseBody:{type:"json",value:a.jsonExample},description:a.docs}))})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:cm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0,propertyAccess:void 0}];n.type!=null&&a.push({key:cm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:jE(n.type),description:n.docs,availability:void 0,propertyAccess:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function Pz_({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:i}){if(r==null)return;let n=r.response?.body!=null?r.response.body.value:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:r.request?.headers??{},requestBody:r.request?.requestBody,requestBodyV3:i.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:a=>{if(r.request==null)return;let u={};if(Gj(r.request.requestBody)){let l=r.request.requestBody;for(let d of a.properties)d._visit({file:s=>{let o=l[s.key.wireValue];if(s.type==="file")u[s.key.wireValue]={type:"filename",value:typeof o=="string"?o:"<file1>"};else if(s.type==="fileArray"){let c=(Array.isArray(o)?o:[o]).filter(b=>typeof b=="string");u[s.key.wireValue]={type:"filenames",value:c}}},bodyProperty:s=>{if(s.style==="exploded"){let o=l[s.name.wireValue];u[s.name.wireValue]={type:"exploded",value:Array.isArray(o)?o:[o]}}else u[s.name.wireValue]={type:"json",value:l[s.name.wireValue]}},_other:Qze})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??i.response?.statusCode??200,responseBody:n??void 0,responseBodyV3:n!=null?r.response?.body?._visit({json:a=>({type:"json",value:a}),stream:a=>({type:"stream",value:a.map(u=>({type:"json",value:u}))}),error:()=>{},_other:()=>{throw new Error("Unknown ExampleResponseBody: "+r.response?.body?.type)}}):void 0,codeSamples:r.codeSamples?.map(a=>({name:a.name,description:a.docs??void 0,install:void 0,language:a.language,code:a.code})).filter(yv)}}function Ujc({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(l=>{let d=l.valueType.type==="container"&&l.valueType.container.type==="literal"?l.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):void 0;if(d!=null)return{name:l.name,value:{jsonExample:d,shape:Gs.ExampleTypeReferenceShape.primitive(Gs.ExamplePrimitive.string({original:d}))}}}).filter(yv),a=e?.example??t?.example;if(a==null)return;let{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((l,d)=>(l[cm.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,l),{}),queryParameters:a.queryParameters.reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),requestBody:a.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,reference:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,fileUpload:l=>{if(a.request==null)return;let d={};if(Gj(a.request.jsonExample)){let s=a.request.jsonExample;for(let o of l.properties)o._visit({file:c=>{let b=s[c.key.wireValue];if(c.type==="file")d[c.key.wireValue]={type:"filename",value:typeof b=="string"?b:"<file1>"};else if(c.type==="fileArray"){let g=(Array.isArray(b)?b:[b]).filter(O=>typeof O=="string");d[c.key.wireValue]={type:"filenames",value:g}}},bodyProperty:c=>{if(c.style==="exploded"){let b=s[c.name.wireValue];d[c.name.wireValue]={type:"exploded",value:Array.isArray(b)?b:[b]}}else d[c.name.wireValue]={type:"json",value:s[c.name.wireValue]}},_other:Qze})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Gs.http.ExampleResponse._visit(a.response,{ok:l=>l._visit({body:d=>d!=null?200:204,stream:d=>d.length>0?200:204,sse:d=>d.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:({error:l})=>{let d=i.errors[l.errorId];if(d==null)throw new Error("Cannot find error "+l.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:l=>l._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:l=>l.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:l=>l._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(s=>s.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:s,data:o})=>({event:s,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:l=>l.body!=null?{type:"json",value:l.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(l=>wEe._visit(l,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter(yv)}}function w4E(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>cm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:cm.FernRegistry.PropertyKey(t.name.wireValue),valueType:jE(t.valueType),availability:e4(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:jE(e.payloadType)},description:e.docs};default:jo(e)}}function S4E(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>cm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:cm.FernRegistry.PropertyKey(t.name.wireValue),valueType:jE(t.valueType),availability:e4(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:jE(e.bodyType)};default:jo(e)}}function ZZ({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:Vjc(e.rootPackage,e),auth:gz_(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:e4(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:jE(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[Aeu.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:mz_(a.shape),availability:e4(a.availability),displayName:a.name.displayName};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[Aeu.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:Aeu.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...Vjc(a,e)}}return i}var Wjc=ui(PEe(),1);async function Hjc({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=hR({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new _R(r,t)}),d=IWi({token:i.value}),s=ZZ({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await d.api.v1.register.registerApiDefinition({orgId:Wjc.FernRegistry.OrgId(e),apiId:Wjc.FernRegistry.ApiId(l.apiName.originalName),definition:s});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:l};switch(o.error.error){case"UnauthorizedError":case"UserNotInOrgError":return r.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return r.failAndThrow("Failed to register API",o.error)}}var D4E=new tKi({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function eRa(e,t,r){return wxa(mxa(ZZ({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r}),Y6.ApiDefinitionId(t),D4E))}var uh={};Po(uh,{AlgoliaSearchIndex:()=>jz_,ApiDefinitionId:()=>Hz_,ApiId:()=>Jz_,Availability:()=>cx_,DocsConfigId:()=>Kz_,EndpointId:()=>Xz_,EndpointPathLiteral:()=>ux_,EnvironmentId:()=>Yz_,FileId:()=>rx_,HttpMethod:()=>sx_,IndexSegmentId:()=>wz_,JqString:()=>nx_,OrgId:()=>Gz_,PageId:()=>tx_,PayloadLocation:()=>xx_,PropertyKey:()=>ax_,PullRequestState:()=>Tx_,RoleId:()=>ox_,TokenId:()=>Qz_,TypeId:()=>ex_,Url:()=>ix_,VersionId:()=>$z_,WebSocketId:()=>Zz_,WebhookId:()=>kz_,algolia:()=>$jc,api:()=>twc,commons:()=>rwc,diff:()=>lx_,docs:()=>fwc,generators:()=>pwc,git:()=>_wc,navigation:()=>vwc,sdks:()=>gwc,snippets:()=>Ix_,snippetsFactory:()=>zx_,templates:()=>Owc,tokens:()=>Rx_});var $jc={};Po($jc,{AlgoliaSearchIndex:()=>jz_,IndexSegmentId:()=>wz_});function jz_(e){return e}function wz_(e){return e}var twc={};Po(twc,{latest:()=>Jjc,v1:()=>ewc});var Jjc={};Po(Jjc,{AuthSchemeId:()=>Sz_,WebhookHttpMethod:()=>Az_,auth:()=>Gjc,commons:()=>Dz_,endpoint:()=>Ez_,type_:()=>Mz_,webhook:()=>Qjc,websocket:()=>qz_});var Gjc={};Po(Gjc,{AuthSchemeId:()=>Sz_});function Sz_(e){return e}var Dz_={};var Ez_={};var Mz_={};var Qjc={};Po(Qjc,{WebhookHttpMethod:()=>Az_});var Az_={Get:"GET",Post:"POST"};var qz_={};var ewc={};Po(ewc,{SubpackageId:()=>Lz_,WebSocketMessageId:()=>Uz_,WebSocketMessageOrigin:()=>Vz_,WebhookHttpMethod:()=>Wz_,commons:()=>kjc,db:()=>Kjc,read:()=>Xjc,register:()=>Zjc});var Kjc={};Po(Kjc,{endpoint:()=>Tz_});var Tz_={};var Xjc={};Po(Xjc,{SupportedLanguage:()=>Cz_,endpoint:()=>Yjc,type_:()=>Bz_,webhook:()=>Iz_,websocket:()=>zz_});var Yjc={};Po(Yjc,{SupportedLanguage:()=>Cz_});var Cz_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var Bz_={};var Iz_={};var zz_={};var Zjc={};Po(Zjc,{SourceId:()=>E4E,endpoint:()=>xz_,type_:()=>Rz_,webhook:()=>Nz_,websocket:()=>Fz_});var xz_={};var Rz_={};var Nz_={};var Fz_={};function E4E(e){return e}var kjc={};Po(kjc,{SubpackageId:()=>Lz_,WebSocketMessageId:()=>Uz_,WebSocketMessageOrigin:()=>Vz_,WebhookHttpMethod:()=>Wz_});function Lz_(e){return e}function Uz_(e){return e}var Vz_={Client:"client",Server:"server"};var Wz_={Get:"GET",Post:"POST"};var rwc={};Po(rwc,{ApiDefinitionId:()=>Hz_,ApiId:()=>Jz_,Availability:()=>cx_,DocsConfigId:()=>Kz_,EndpointId:()=>Xz_,EndpointPathLiteral:()=>ux_,EnvironmentId:()=>Yz_,FileId:()=>rx_,HttpMethod:()=>sx_,JqString:()=>nx_,OrgId:()=>Gz_,PageId:()=>tx_,PropertyKey:()=>ax_,RoleId:()=>ox_,TokenId:()=>Qz_,TypeId:()=>ex_,Url:()=>ix_,VersionId:()=>$z_,WebSocketId:()=>Zz_,WebhookId:()=>kz_});function Hz_(e){return e}function $z_(e){return e}function Gz_(e){return e}function Qz_(e){return e}function Jz_(e){return e}function Kz_(e){return e}function Yz_(e){return e}function Xz_(e){return e}function Zz_(e){return e}function kz_(e){return e}function ex_(e){return e}function tx_(e){return e}function rx_(e){return e}function ix_(e){return e}function nx_(e){return e}function ax_(e){return e}function ox_(e){return e}function ux_(e){return e}var sx_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var cx_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var lx_={};var fwc={};Po(fwc,{latest:()=>awc,v1:()=>cwc,v2:()=>lwc});var awc={};Po(awc,{Layout:()=>dx_,MdxEngine:()=>M4E,TwitterCardSetting:()=>px_,commons:()=>fx_,frontmatter:()=>iwc,seo:()=>nwc});var M4E={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var fx_={};var iwc={};Po(iwc,{Layout:()=>dx_});var dx_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var nwc={};Po(nwc,{TwitterCardSetting:()=>px_});var px_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var cwc={};Po(cwc,{commons:()=>swc,db:()=>_x_,read:()=>hx_,write:()=>owc});var _x_={};var hx_={};var owc={};Po(owc,{DocsRegistrationId:()=>q4E,FilePath:()=>A4E});function A4E(e){return e}function q4E(e){return e}var swc={};Po(swc,{ContentAlignment:()=>gx_,FontDisplay:()=>wx_,FontStyle:()=>jx_,HeaderPosition:()=>Ox_,JsScriptStrategy:()=>Px_,ProgrammingLanguage:()=>yx_,SearchbarPlacement:()=>vx_,TabsPlacement:()=>bx_,TwitterCardSetting:()=>mx_,commons:()=>uwc});var uwc={};Po(uwc,{ContentAlignment:()=>gx_,FontDisplay:()=>wx_,FontStyle:()=>jx_,HeaderPosition:()=>Ox_,JsScriptStrategy:()=>Px_,ProgrammingLanguage:()=>yx_,SearchbarPlacement:()=>vx_,TabsPlacement:()=>bx_,TwitterCardSetting:()=>mx_});var yx_={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var vx_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var bx_={Header:"HEADER",Sidebar:"SIDEBAR"};var gx_={Center:"CENTER",Left:"LEFT"};var Ox_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var mx_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Px_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var jx_={Normal:"normal",Italic:"italic"};var wx_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var lwc={};Po(lwc,{read:()=>Sx_,write:()=>Dx_});var Sx_={};var Dx_={};var pwc={};Po(pwc,{ChangelogEntryType:()=>Mx_,GeneratorId:()=>T4E,GeneratorLanguage:()=>C4E,ReleaseType:()=>Ax_,cli:()=>Ex_,commons:()=>dwc,versions:()=>qx_});var Ex_={};var dwc={};Po(dwc,{ChangelogEntryType:()=>Mx_,ReleaseType:()=>Ax_});var Mx_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var Ax_={Ga:"GA",Rc:"RC"};var qx_={};function T4E(e){return e}var C4E={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var _wc={};Po(_wc,{PullRequestState:()=>Tx_});var Tx_={Open:"open",Closed:"closed",Merged:"merged"};var vwc={};Po(vwc,{latest:()=>hwc,v1:()=>ywc});var hwc={};Po(hwc,{NodeId:()=>z4E,ProductId:()=>x4E,Slug:()=>B4E,TabId:()=>I4E});function B4E(e){return e}function I4E(e){return e}function z4E(e){return e}function x4E(e){return e}var ywc={};Po(ywc,{NavigationV1Availability:()=>U4E,NodeId:()=>F4E,ProductId:()=>L4E,Slug:()=>R4E,TabId:()=>N4E});function R4E(e){return e}function N4E(e){return e}function F4E(e){return e}function L4E(e){return e}var U4E={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var gwc={};Po(gwc,{Language:()=>Cx_,VersionBump:()=>Bx_,versions:()=>bwc});var bwc={};Po(bwc,{Language:()=>Cx_,VersionBump:()=>Bx_});var Cx_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var Bx_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var Ix_={};var zx_={};var Owc={};Po(Owc,{PayloadLocation:()=>xx_});var xx_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var Rx_={};var p9n=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Gd(e){return e!=null}var Fx_=ui(wCn(),1);var Nx_=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function qir(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,Fx_.default)(e,{special:Nx_}).replace(/V\s(\d)/g,"V$1")}function qeu({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let u=[...n,a],l=uh.api.v1.SubpackageId(u.join("."));r[l]={id:l,name:a,displayName:qir(a)},n.push(a)})}),r}var Teu=class{errors=new p9n},_9n=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function Lx_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var Ceu=class extends Teu{},n_=class extends _9n{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((u,l)=>u===this.accessPath[this.accessPath.length-a.length+l])||this.accessPath.push(...a)}r.logger.debug(`Processing ${Lx_(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},z3=class extends n_{},Qae=class extends z3{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var Ux_="x-fern-base-path",Vx_="x-fern-availability",Beu="x-fern-sdk-group-name",Wx_="x-fern-global-headers",Hx_="x-fern-sdk-method-name";var $x_="x-fern-webhook",Gx_="x-fern-access-token-locator",Qx_="x-fern-basic",Jx_="x-fern-username-variable-name",Kx_="x-fern-password-variable-name",Yx_="x-fern-bearer",Xx_="x-fern-token-variable-name",Zx_="x-fern-header",kx_="x-fern-header-variable-name",eR_="x-fern-server-name",tR_="x-fern-examples";var Ieu=class extends n_{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[eR_]}convert(){if(this.serverName!=null)return this.serverName}};var zeu=class extends n_{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new Ieu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:uh.EnvironmentId(t),baseUrl:this.url}}};function Tir(e,t,r,i){let n=e??[],a=new Set(n.map(l=>l.url)),u=(t??[]).filter(l=>!a.has(l.url)).map((l,d)=>new zeu({input:l,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...u]}function LS(e){return typeof e=="object"&&Gd(e)&&"$ref"in e&&typeof e.$ref=="string"}function iH(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(LS(n)&&(n=iH(n,t,r)),n)}function xeu(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return LS(r)?iH(r,t,void 0):r}var pR_=ui(lz());var Reu=class extends n_{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[Qx_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var Neu=class extends n_{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[Kx_]}convert(){return this.passwordVariableName}};var Feu=class extends n_{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[Jx_]}convert(){return this.usernameVariableName}};var Leu=class extends n_{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[Yx_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var Ueu=class extends n_{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[Xx_]}convert(){return this.tokenVariableName}};function rR_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var iR_="x-bearer-format",nR_="x-code-samples",aR_="x-codeSamples";var Veu=class extends n_{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[iR_]}convert(){return this.bearerFormat}};var Weu=class extends n_{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[Zx_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var Heu=class extends n_{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[kx_]}convert(){return this.headerVariableName}};function oR_(e){return e.type==="apiKey"}var h9n=class extends n_{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){oR_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new Weu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new Heu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new Veu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function uR_(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function sR_(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function cR_(e){let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",u=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let l=e[i];a?l==="\\"&&i+1<r?(i++,n+=e[i]):l===a?a="":n+=l:u?l==='"'||l==="'"?a=l:l==="]"?(u=!1,t.push(n),n=""):n+=l:l==="["?(u=!0,n&&(t.push(n),n="")):l==="."?n&&(t.push(n),n=""):n+=l,i++}return n&&t.push(n),t}function mwc(e,t,r){if(e==null)return r;switch(typeof t){case"string":{let i=e[t];return i===void 0?uR_(t)?mwc(e,cR_(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=sR_(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return V4E(e,t,r);Object.is(t?.valueOf(),-0)?t="-0":t=String(t);let i=e[t];return i===void 0?r:i}}}function V4E(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null)return r;i=i[t[n]]}return i===void 0?r:i}function lR_(e){return function(t){return mwc(t,e)}}function Pwc(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Pwc).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function $eu(e,t){switch(t=t??yT_,typeof t){case"string":case"symbol":case"number":case"object":return nL(e,lR_(t));case"function":return nL(e,t)}}function fR_(e){return typeof e!="string"&&(e=Pwc(e)),e.replace(/['\u2019]/g,"")}function gHt(e){return GD_(fR_(e))}function yA(e){if(e!=null)return Array.isArray(e)?e:[e]}function Geu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:u}){if(t==null)return;let l=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&l==null))return`${W4E(u)}${H4E(e)}.${$4E(i,n,a,l)}`}function W4E(e){return e?"webhook_":"endpoint_"}function H4E(e){return e!=null?yA(e)?.map(t=>gHt(t)).join("/"):""}function $4E(e,t,r,i){return e||t||gHt(r??"")||gHt(i??"")}function dR_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var Qeu=class extends n_{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[Gx_],this.accessTokenLocator!=null&&(dR_(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var Jeu=class extends n_{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new h9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new Qeu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=Geu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:uh.EndpointId(r),accessTokenLocator:uh.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var y9n=class extends n_{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new Reu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new Feu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new Neu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new Leu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new Ueu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{rR_(this.input)?(this.authScheme="header",this.headerAuthNode=new h9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new Jeu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new pR_.UnreachableCaseError(this.authScheme);return}}};var v9n=class extends n_{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=xeu(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new y9n({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(Gd))}};var Keu=class extends n_{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[Ux_],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function _R_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function hR_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function b9n(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>yA(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!_R_(n))&&(u=hR_(u,u.type==="enum"?u.default:void 0)),{key:uh.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(Gd)).filter(Gd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function Yeu(e,t){return LS(e)?iH(e,t,void 0):e}function mAi(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function yR_(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function vR_(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var bR_=ui(lz());var jwc=["decimal","decimal128","double-int","double","float","sf-decimal"],wwc=["int16","int32","int64","int8","sf-integer","uint8"],Swc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],Dwc=["beta","pre-release","in-development","generally-available","deprecated"];function x3(e,t){return LS(e)?iH(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var PFe=class extends n_{availability;constructor(t){super(t),this.safeParse()}parse(){if(x3(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[Vx_];r!=null&&(Dwc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${Dwc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return uh.Availability.Beta;case"in-development":return uh.Availability.InDevelopment;case"generally-available":return uh.Availability.GenerallyAvailable;case"deprecated":return uh.Availability.Deprecated;case void 0:return;default:new bR_.UnreachableCaseError(this.availability);return}}};var Zeu=ui(lz());function gR_(e){return typeof e=="object"&&e!=null&&"language"in e}function OR_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function mR_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function PR_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function Xeu(e){return typeof e=="object"&&e!=null&&"event"in e}function Ewc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(Xeu)}function PAi(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function jR_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var keu=class extends n_{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[tR_]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let u=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return PAi(u)?[n,{type:"filenameWithData",filename:u.filename,data:uh.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(l=>PAi(l)))return[n,{type:"filenamesWithData",value:u.map(l=>({filename:l.filename,data:uh.FileId(l.data)}))}];if(u.every(l=>typeof l=="string"))return[n,{type:"filenames",value:u}]}return}case"property":return[n,{type:"json",value:u}];case void 0:return;default:new Zeu.UnreachableCaseError(a.multipartType);return}}).filter(Gd))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=jR_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new Zeu.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{mR_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{Ewc(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!Ewc(r.response)&&PR_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new Zeu.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{gR_(c)?c.language!=null&&(l[c.language]??=[],l[c.language]?.push({name:c.name,language:c.language,install:c.install,code:c.code,generated:!1,description:c.docs})):OR_(c)&&c.sdk!=null&&(l[c.sdk]??=[],l[c.sdk]?.push({name:c.name,language:c.sdk,install:void 0,code:c.code,generated:!1,description:c.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([c,b])=>[uh.PropertyKey(c),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([c,b])=>[uh.PropertyKey(c),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([c,b])=>[uh.PropertyKey(c),b]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(o).length>0?o:void 0,requestBody:a,responseBody:u,snippets:l}}))}};var tRa=class extends n_{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[Beu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>uh.api.v1.SubpackageId(gHt(r)))}};var etu=class extends n_{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[Hx_]}convert(){return this.sdkMethodName}};var ttu=class extends n_{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[$x_]}convert(){return this.isWebhook}};var rtu=class extends n_{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[nR_]??[],...this.input[aR_]??[]],this.codeSamples.forEach(t=>{[...Object.values(uh.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var dKi=ui(lz());function Mwc(e,t){return LS(e)?iH(e,t,void 0):e}function wR_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var cL="",Cir=class extends n_{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(PAi(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>PAi(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new dKi.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=Mwc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=Mwc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new dKi.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(Xeu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new dKi.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return PAi(n)?[r,{type:"filenameWithData",filename:n.filename,data:uh.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>PAi(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:uh.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new dKi.UnreachableCaseError(i.multipartType);return}}).filter(Gd))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new dKi.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new dKi.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,l])=>[u,l.example({includeOptionals:!1,override:u})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Gd));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Gd));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:wR_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?qir(this.name):this.summary!=null?qir(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function SR_(e,t){return LS(e)?iH(e,t,void 0):e}var NR_=ui(lz());var DR_="#/components/schemas/";function g9n(e){if(e.$ref.startsWith(DR_))return e.$ref.replace(DR_,"")}function dpi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function jAi(e){return typeof e.type=="string"&&e.type==="array"}function ER_(e){return e.type==="boolean"}function MR_(e){return e.type==="integer"}function wAi(e){return!Array.isArray(e.type)&&!jAi(e)}function AR_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||wAi(t)||jAi(t))}function qR_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function TR_(e){return e.type==="null"}function CR_(e){return e.type==="number"}function Awc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function BR_(e){return e.type==="string"}var itu=class extends Qae{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new Gq({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return yA(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var ntu=class extends z3{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new PFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var atu=class extends Qae{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new Gq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Gd)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>yA(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(Gd).reduce((n,a)=>n.flatMap(u=>a.length>0?a.map(l=>[...u,l]):[[...u]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(dpi).filter(Gd):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function otu(e){return e!=null&&e.length>0?e:[void 0]}var O9n=class extends Qae{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new Gq({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new Gq({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(LS(t))return g9n(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new Gq({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Gd))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return b9n(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:yA(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(Gd)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>otu(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>uh.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=x3(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new Gq({input:u,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var utu=class extends Qae{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>x3(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>x3(t,this.context.document)?.type!=="null"?new Gq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Gd);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=x3({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new Gq({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(Gd);return this.isNullable&&n!=null?n.map(dpi).filter(Gd):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:uh.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>yA(a.convert())?.map(l=>{if(!(l==null||l.type!=="object"))return{discriminantValue:n,displayName:a.name??qir(n),availability:a.availability?.convert(),description:a.description,...l}}).filter(Gd)).filter(Gd)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>yA(n.convert())?.map(u=>{if(u==null)return;t+=1;let l=u.type==="object"?qir(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?qir(u.value.id):l),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(Gd)).filter(Gd)}:void 0,i=this.isNullable?dpi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var stu=class extends z3{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var SAi=class extends z3{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(LS(r)){let n=x3(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(Gd),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var IR_=ui(lz());function G4E(e){return wwc.includes(e)}var ctu=class extends z3{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(G4E(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${wwc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new IR_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var ltu=class extends z3{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return dpi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var zR_=ui(lz());function Q4E(e){return jwc.includes(e)}var ftu=class extends z3{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(Q4E(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${jwc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new zR_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var xR_=ui(lz());function J4E(e){return Swc.includes(e)}var dtu=class extends z3{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new xR_.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(J4E(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Swc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new SAi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var RR_=ui(lz());var ptu=class extends z3{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,RR_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var pKi=class extends Qae{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=g9n(this.input);let t=x3(this.input,this.context.document);t?.enum!=null&&wAi(t)&&(this.maybeEnumConverterNode=new SAi({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:uh.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=x3(this.input,this.context.document);if(r!=null)return new Gq({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var Gq=class e extends Qae{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new PFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),wAi(this.input)&&qR_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),LS(this.input)){let t=g9n(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new pKi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new ntu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(AR_(this.input))this.typeShapeNode=new atu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(wAi(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new utu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Awc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new O9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(wAi(this.input)&&this.input.enum!=null)this.typeShapeNode=new SAi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":Awc(this.input)&&(this.typeShapeNode=new O9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":jAi(this.input)&&(this.typeShapeNode=new itu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":ER_(this.input)&&(this.typeShapeNode=new stu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":MR_(this.input)&&(this.typeShapeNode=new ctu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":CR_(this.input)&&(this.typeShapeNode=new ftu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":BR_(this.input)&&(this.typeShapeNode=new dtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":TR_(this.input)&&(this.typeShapeNode=new ltu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new NR_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new O9n({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new ptu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!LS(this.input)&&(!jAi(this.input)&&this.input==null||jAi(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=yA(t)?.map(i=>this.nullable?dpi(i):i).filter(Gd);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function DAi(e){if(e!=null)return b9n(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Gd))}var Bir=class extends z3{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;LS(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new PFe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new Gq({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=SR_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function FR_(e,t){return LS(e)?iH(e,t,void 0):e}var qwc=ui(lz());function _tu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[uh.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var LR_=ui(RBs(),1),m9n=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,u){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=u}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=LR_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function K4E(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var P9n=class extends n_{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new Gq({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),K4E(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(LS(r)?n=xeu(r.$ref,this.context.document):n=r,n!=null)return[t,new y9n({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Gd)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[uh.api.latest.AuthSchemeId(t),i]}).filter(Gd)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=yA(r.convert());return n==null?[t,void 0]:[uh.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Gd(r))):void 0}}};var htu=class extends Gq{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=x3(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${LS(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=x3(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var ytu=class extends n_{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=x3(this.input.schema,this.context.document);this.availability=new PFe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=LS(this.input.schema)?new pKi({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=m9n.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new Gq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,u])=>{if(u!=null)return[a,new htu({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Gd))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[cL]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[cL]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:yA(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=gHt([this.method,this.path,this.contentType,"request"].join("_"));return _tu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uh.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new qwc.UnreachableCaseError(n);return}}).filter(Gd)}convert(){if(this.schema instanceof pKi)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:uh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:uh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=yA(n.convert()),u=n.multipartType;return a?.map(l=>({type:u,key:uh.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:l,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new qwc.UnreachableCaseError(n.multipartType),[]}}).filter(Gd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var vtu=class extends n_{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=FR_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new ytu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>yA(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Gd)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>yA(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Gd)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var UR_={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function VR_(e,t){if(LS(e)){let r=iH(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var btu=ui(lz());var WR_="application/json";var HR_="application/octet-stream";function $R_(e,t){return e===t||t===cL||e===cL}var rRa=class extends n_{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,l,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=l,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[l,d]of Object.entries(r))for(let s of d)$R_(l,a)&&(i.add(l),this.examples?.push(new Cir({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,mAi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[u,l]of r){if(a===i){let[d,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...l.map(c=>new Cir({input:{requestExample:o,responseExample:c},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,mAi(s,u),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,u]=r[r.length-1]??[void 0,void 0],[l,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new Cir({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,mAi(d,a),{requestBody:l,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,u]=t[t.length-1]??[void 0,void 0,void 0];for(let[l,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new Cir({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,mAi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[cL];if(a!=null)for(let u of a)this.examples?.push(new Cir({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,mAi(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let l=m9n.parse(t);if(l?.isJSON()||l?.isEventStream())this.contentType=WR_,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new Gq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(l?.isOctetStream())this.contentType=HR_,this.contentSubtype=x3(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new Gq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=$eu(this.input.examples,l=>[l])),this.input.example!=null&&Object.keys(r).length===0&&(r[cL]??=[],r[cL]=[{value:this.input.example}]);let i=x3(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=$eu(i.examples,l=>[l])),i.example!=null&&Object.keys(r).length===0&&(r[cL]??=[],r[cL]?.push({value:i.example}))),Object.keys(r).length===0){let l=this.schema?.example({includeOptionals:!0,override:void 0});r[cL]??=[],r[cL]?.push(l!=null?{value:l}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let l of this.requests)a.push(...Object.entries(l.examples??{}).filter(([d])=>!n.has(d)&&d!==cL).map(([d,s])=>[l,d,s]));let u=Object.entries(r).filter(([l,d])=>!n.has(l)&&Gd(d)&&l!==cL);Object.keys(r).every(l=>l===cL)||this.matchExamplesByIndex(a,u),!n.has(cL)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return yA(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new btu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return yA(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=gHt([this.method,this.path,this.statusCode,"response"].join("_"));return _tu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uh.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new btu.UnreachableCaseError(i);return}}).filter(Gd)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new btu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var iRa=class extends n_{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,u){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=u,this.safeParse()}parse(t){this.description=this.input.description;let r=VR_(this.input,this.context.document);if(r==null){this.context.errors.error({message:LS(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new Bir({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new rRa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new rRa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(Gd)}};var gtu=class extends n_{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new iRa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new iRa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return otu(DAi(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(u=>(u.examples??[]).map(l=>l.convert()).filter(Gd))})))}).filter(Gd)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=yA(n?.convert());if(n!=null)return a?.map(u=>({statusCode:parseInt(t),shape:u,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??UR_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(l=>{let d=l.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(Gd)})).filter(Gd)})).filter(Gd)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var EAi=class extends n_{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new Cir({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,mAi(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new PFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=Tir(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new ttu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(LS(i)){let a=Yeu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new Bir({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new Bir({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new Bir({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new rtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new vtu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new gtu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,u])=>{this.pushEmptyResponseExample(u,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new v9n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new tRa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new tRa({input:{[Beu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new etu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>Geu({namespace:yA(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(Gd),this.xFernExamplesNode=new keu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(Gd)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:uh.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(o=>o.convert()).filter(Gd),n=vR_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:yR_(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,c)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:uh.WebhookId(o),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[c]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(b=>b.value.toString())??[],queryParameters:DAi(this.queryParameters)?.flat(),headers:DAi(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Gd)}}).filter(Gd);let a=this.servers?.map(o=>o.convert()).filter(Gd),u=this.convertPathToPathParts();if(u==null)return;let l,d=this.auth?.convert();d!=null&&(l=Object.keys(d));let s=t?.flatMap(o=>o.headers).filter(Gd);return this.endpointIds.map((o,c)=>({id:uh.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[c]?.convert()?.map(b=>uh.api.v1.SubpackageId(b)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:l?.map(b=>uh.api.latest.AuthSchemeId(b)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:DAi(this.pathParameters)?.flat(),queryParameters:DAi(this.queryParameters)?.flat(),requestHeaders:DAi(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(b=>b.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var j9n=class extends n_{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=Tir(t,this.input.servers,this.context,this.accessPath),u=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new EAi({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:u,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new EAi({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:u,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new EAi({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:u,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new EAi({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:u,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new EAi({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:u,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(Gd)}};function Otu(e){return"payloads"in e}var mtu=class extends n_{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new j9n({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:Tir(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Gd)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{Otu(a)?r[uh.WebhookId(a.id)]=a:t[uh.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var Ptu=class extends n_{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[Wx_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||Yeu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new Bir({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return b9n(this.globalHeaders,this.requiredProperties)?.flat()}};function GR_(e,t){if(LS(e)){let r=iH(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var jtu=class extends n_{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let u=GR_(a,this.context.document);if(u!=null)return new j9n({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Gd)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{Otu(i)&&(t[uh.WebhookId(i.id)]=i)}),t),{})}};var wtu=class extends n_{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=Tir(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new v9n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new Keu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new mtu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new jtu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new P9n({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new Ptu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=lae(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=qeu({endpoints:i,webhookEndpoints:n}),{types:u,auths:l}=this.components?.convert()??{};return{id:uh.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...u,...this.context.generatedTypes},subpackages:a,auths:{...l,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var w9n=class extends _9n{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,this.pathId&&this.pathId!==this.accessPath[this.accessPath.length-1]&&(this.accessPath.push(this.pathId),r.logger.debug(`Processing #/${this.accessPath.join("/")}`))}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}};function jFe(e){return typeof e=="object"&&Gd(e)&&"$ref"in e&&typeof e.$ref=="string"}function OHt(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(jFe(n)&&(n=OHt(n,t,r)),n)}function QR_(e,t){return jFe(e)?OHt(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var XR_=ui(lz());function ppi(e){if(typeof e=="boolean")return e;if(e.enum!=null&&e.enum.length>0)return e.enum[0];if(e.const!=null)return e.const;if(e.examples!=null&&e.examples.length>0)return e.examples[0];if(e.type==="object"){let t={};if(e.properties!=null)for(let[r,i]of Object.entries(e.properties))t[r]=ppi(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>ppi(t)):[ppi(e.items)];if(e.type==="string")return e.default??"string";if(e.type==="number"||e.type==="integer")return e.default??0;if(e.type==="boolean")return e.default??!1;if(e.type==="null")return null;if(e.oneOf?.[0]!=null)return ppi(e.oneOf[0]);if(e.anyOf?.[0]!=null)return ppi(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,ppi(r));return t}}function nRa(e,t){return jFe(e)?OHt(e,t,{name:"",schema:{type:"object"}}):e}function JR_(e,t){return jFe(e)?OHt(e,t,void 0):e}function KR_(e,t){return jFe(e)?OHt(e,t,void 0):e}function YR_(e,t){return jFe(e)?OHt(e,t,void 0):e}var Y4E={key:uh.PropertyKey("apiKey"),description:void 0,availability:void 0,valueShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}},Stu=class extends w9n{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?nRa(this.method.result,this.context.openrpc):void 0,r=t?new Gq({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result",seenSchemas:new Set,nullable:void 0,schemaName:"Result"}).convert():void 0,n=this.method.params?.map(l=>nRa(l,this.context.openrpc)).filter(Gd)?.map(l=>{let d=new Gq({input:l.schema,context:this.context,accessPath:this.accessPath,pathId:["params",l.name],seenSchemas:new Set,nullable:void 0,schemaName:l.name}).convert();if(!d)return;let s=Array.isArray(d)?d[0]:d;if(s)return{key:uh.PropertyKey(l.name),valueShape:l.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:l.description,availability:void 0}}).filter(Gd),a=n.length>0?{contentType:"application/json",body:{type:"object",extends:[],properties:n,extraProperties:void 0},description:void 0}:void 0,u=this.method.examples?.map(l=>{let d=KR_(l,this.context.openrpc);if(d)return{name:d.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:d.params.length>0?{type:"json",value:Object.fromEntries(d.params.map(s=>{let o=JR_(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(Gd))}:void 0,responseStatusCode:200,responseBody:d.result?{type:"json",value:d.result}:void 0}}).filter(Gd)??[];if(u.length<=0){let l=ppi({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=nRa(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:l},responseStatusCode:200,responseBody:{type:"json",value:ppi(nRa(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}return{protocol:{type:"openrpc",methodName:this.input.name},id:uh.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:uh.PropertyKey("apiKey")}],auth:void 0,pathParameters:[Y4E],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(Gd):[],errors:[],examples:u,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(l=>l.convert()).filter(Gd),availability:this.method.deprecated?"Deprecated":void 0,requestHeaders:[],responseHeaders:[],snippetTemplates:void 0,namespace:this.getNamespace()}}catch{this.context.errors.error({message:"Failed to convert method",path:this.accessPath});return}}getNamespace(){if(this.method.tags?.[0]==null)return;let t=YR_(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[uh.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=yA(t)?.map(a=>{let u=a.type;switch(u){case"alias":return a;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":return;case"object":return a;default:new XR_.UnreachableCaseError(u);return}}).filter(Gd)[0];if(n)return{statusCode:200,body:n,description:r}}};var aRa=class extends w9n{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=Tir(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=QR_(t,this.context.openrpc);r!=null&&this.methods.push(new Stu({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new P9n({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=lae(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(Gd),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=qeu({endpoints:n});return{id:uh.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var oRa=class extends Ceu{openrpc;logger;generatedTypes;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger,this.generatedTypes={}}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function uRa(e,t){if(e instanceof nir){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof fR))return;let r=new eHt(e.absoluteFilePath),i=await sFe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let u of n){if(u.type!=="openapi")continue;let l={document:u.value,logger:t.logger,errors:new p9n,generatedTypes:{}},d=new wtu({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=kBs(a,d.convert())}return a}var ZR_=require("fs/promises");async function kR_(e,t){let r=await(0,ZR_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new oRa({openrpc:i,logger:t.logger});return new aRa({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function X4E(e){return e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function Z4E(e){return/^(https?:)?\/\//.test(e)}async function k4E({pathToImage:e,absolutePathToFernFolder:t}){if(e==null||Z4E(e))return;let r=Gv(t,Na.of(e));if(await mf(r))return r}async function S9n({iconPath:e,filepaths:t,docsWorkspace:r}){if(X4E(e)){let i=await k4E({pathToImage:e,absolutePathToFernFolder:r.absoluteFilePath});i&&t.add(i)}}async function eN_({parsedDocsConfig:e,docsWorkspace:t}){let r=new Set;return e.logo?.dark!=null&&r.add(e.logo.dark),e.logo?.light!=null&&r.add(e.logo.light),e.favicon!=null&&r.add(e.favicon),e.backgroundImage?.dark!=null&&r.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&r.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&r.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&r.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&r.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(n=>{n.image!=null&&r.add(n.image)}),(await Twc({navigation:e.navigation,docsWorkspace:t})).forEach(n=>{r.add(n)}),e.js!=null&&e.js.files.forEach(n=>{r.add(n.absolutePath)}),r}async function Twc({navigation:e,docsWorkspace:t}){let r=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(i=>sRa({item:i,filepaths:r,docsWorkspace:t})));break;case"tabbed":await Promise.all(e.items.map(async i=>{i.icon!=null&&await S9n({iconPath:i.icon,filepaths:r,docsWorkspace:t}),i.child.type==="layout"&&i.child.layout!=null&&await Promise.all(i.child.layout.map(n=>sRa({item:n,filepaths:r,docsWorkspace:t})))}));break;case"versioned":await Promise.all(e.versions.map(async i=>{i.landingPage!=null&&await sRa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await Twc({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break;case"productgroup":await Promise.all(e.products.map(async i=>{i.landingPage!=null&&await sRa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await Twc({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break}return r}async function sRa({item:e,filepaths:t,docsWorkspace:r}){switch(e.type){case"page":e.icon!=null&&await S9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"section":e.icon!=null&&await S9n({iconPath:e.icon,filepaths:t,docsWorkspace:r}),await Promise.all(e.contents.map(i=>sRa({item:i,filepaths:t,docsWorkspace:r})));break;case"apiSection":e.icon!=null&&await S9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"link":e.icon!=null&&await S9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"changelog":e.icon!=null&&await S9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break}}async function tN_({navigation:e,apiWorkspaces:t,visitor:r,context:i}){t2E(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await Cwc({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await Cwc({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function Cwc({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await UYt(e,{alphabetized:Go,api:Go,apiName:Go,audiences:Go,displayErrors:Go,snippets:Go,summary:Go,title:Go,layout:Go,icon:Go,slug:Go,hidden:Go,skipSlug:Go,paginated:Go,playground:Go,flattened:Go,path:Go,page:Go,featureFlag:Go,openrpc:Go,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await Cwc({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:Go,orphaned:Go}),e2E(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function e2E(e){return e.api!=null}function t2E(e){return e[0]?.tab!=null}function kZ(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}rN_.default.extend(iN_.default);var r2E=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),Dtu=0,i2E=async({ir:e})=>(Dtu++,`${e.apiName.snakeCase.unsafeName}-${Dtu}`),n2E=async({api:e})=>(Dtu++,`${e.id}-${Dtu}`),mHt=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=r2E,d=i2E,s=n2E){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=d,this.registerApiV2=s}#e=Eeu.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;async resolve(){this._parsedDocsConfig=await J7s({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});let t=this.parsedDocsConfig.experimental?.openapiParserV3,r=t!=null&&!t;this.docsWorkspace.config.navigation!=null&&r&&await tN_({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:o})=>{(await o.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(b=>{let g=Bq(this.docsWorkspace.absoluteFilePath,b.absoluteFilepath);this.parsedDocsConfig.pages[g]=b.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages);for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Na.of(o)]=await fgc({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Na.of(o)]=await lgc({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});let i=await eN_({parsedDocsConfig:this.parsedDocsConfig,docsWorkspace:this.docsWorkspace});for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:b,markdown:g}=kza(c,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Na.of(o)]=g;for(let O of b)i.add(O)}catch(b){throw this.taskContext.logger.error(`Failed to parse ${o}: ${b instanceof Error?b.message:String(b)}`),b}let n=Array.from(i).map(o=>({absoluteFilePath:o,relativeFilePath:this.toRelativeFilepath(o)}));(await this.uploadFiles(n)).forEach(o=>{this.collectedFileIds.set(o.absoluteFilePath,o.fileId)});let u=await this.getMarkdownFilesToFullyQualifiedPathNames();for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Na.of(o)]=cgc(c,this.collectedFileIds,u,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let l={};Object.entries(this.parsedDocsConfig.pages).forEach(([o,c])=>{let b=a2E(this.editThisPage,o);l[dHt.PageId(o)]={markdown:c,editThisPageUrl:b?dHt.Url(b):void 0}});let d=await this.convertDocsConfiguration(),s={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let o=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async c=>{let b=Gv(this.docsWorkspace.absoluteFilePath,c);(await(0,Etu.stat)(b)).isDirectory()?(await cxe(b,"{js,ts,jsx,tsx,md,mdx}")).forEach(m=>{o.add(m)}):b.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&o.add(b)})),s=Object.fromEntries(await Promise.all([...o].map(async c=>{let b=this.toRelativeFilepath(c),g=(await(0,Etu.readFile)(c)).toString();return[b,g]})))}return{config:d,pages:l,jsFiles:s}}resolveFilepath(t){if(t!=null)return Gv(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return Bq(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,Bwc.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,Bwc.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(){let t={},r=So.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return So.NodeCollector.collect(r).slugMap.forEach((n,a)=>{if(n==null||!So.isPage(n))return;let u=So.getPageId(n);if(u==null)return;let l=Ru(this.docsWorkspace.absoluteFilePath,Na.of(u));t[l]=a}),t}getDocsBasePath(){return new URL(kZ(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?dHt.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>({...i,url:dHt.Url(i.url)})),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:dHt.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}getOpenApiWorkspaceForApiSection(t){if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];if(t.apiName!=null){let i=this.ossWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}async toRootNode(){let t=So.V1.SlugGenerator.init(So.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>So.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return rCn(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=So.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??Tq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((n,a)=>this.toVersionNode(n,r,a===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(u=>this.toProductNode(u,i)))}}async toProductNode(t,r){let i=r.setProductSlug(t.slug??Tq(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:jo(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:So.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:t.icon,image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??Tq(t.version)),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:So.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?o2E(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(l=>this.toNavigationChild(n,l,i))),u=[];return a.forEach(l=>{if(l.type==="apiReference"){u.push(l);return}if(l.type==="section"&&!l.collapsed){u.push(l);return}let d=u.length>0?u[u.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(s)),s.children.push(l)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i,n){return rCn(r)._visit({page:async a=>this.toPageNode(a,i,n),apiSection:async a=>this.toApiSectionNode(a,i,n),section:async a=>this.toSectionNode(t,a,i,n),link:async a=>this.toLinkNode(a),changelog:async a=>this.toChangelogNode(a,i,n)})}async toApiSectionNode(t,r,i){if(t.openrpc!=null){let b=Gv(this.docsWorkspace.absoluteFilePath,Na.of(t.openrpc));if(!await mf(b))throw new Error(`OpenRPC file does not exist at path: ${b}`);let g=await kR_(b,this.taskContext);if(g==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:g,apiName:t.apiName,snippetsConfig:Meu(t.snippetsConfiguration)}),new kxa(t,g,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let b=this.getOpenApiWorkspaceForApiSection(t),g=Meu(t.snippetsConfiguration),O=await uRa(b,this.taskContext);if(O==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:O,snippetsConfig:g,apiName:t.apiName}),new kxa(t,O,r,b,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}let n=Meu(t.snippetsConfiguration),a,u,l=this.parsedDocsConfig.experimental?.openapiParserV3;if(l==null||l)try{a=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1})}catch{}a==null&&(u=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),a=hR({workspace:u,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new _R(this.taskContext,u)}));let s=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),o=eRa(a,s,{oauth:t.playground?.oauth});return new Seu(t,o,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,u,i).get()}async toChangelogNode(t,r,i){return new fpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:So.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r,i){let n=So.PageId(this.toRelativeFilepath(t.absolutePath)),a=r.apply({urlSlug:t.slug??Tq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:a.get(),title:t.title,icon:t.icon,hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toSectionNode(t,r,i,n){let a=this.toRelativeFilepath(r.overviewAbsolutePath),u=a?So.PageId(a):void 0,l=this.#e.get(u??`${t}/section`),d=i.apply({urlSlug:r.slug??Tq(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),s=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,o=n||r.hidden;return{id:l,type:"section",overviewPageId:u,slug:d.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:o,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(c=>this.toNavigationChild(l,c,d,o))),authed:void 0,pointsTo:void 0,noindex:s,featureFlags:r.featureFlags}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return rCn(r.child)._visit({link:({href:n})=>this.toTabLinkNode(r,n),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i)})}async toTabChangelogNode(t,r,i){return new fpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:So.V1.Url(r),icon:t.icon}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),u=n.apply({urlSlug:r.slug??Tq(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:u.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,u),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):dHt.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(yv),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:dHt.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return rCn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:dHt.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function a2E(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${kZ(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function o2E(e){switch(e){case"beta":return So.V1.NavigationV1Availability.Beta;case"deprecated":return So.V1.NavigationV1Availability.Deprecated;case"ga":return So.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return So.V1.NavigationV1Availability.Stable;default:jo(e)}}async function nH(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof fR?t:null))).filter(yv)}async function Iwc(e,t,r){if(e instanceof nir){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof fR))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1});return ZZ({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:{oauth:!0}})}var t6_=ui(ktu(),1),SMe=require("fs/promises"),yru=require("os"),r6_=ui(QX(),1),i6_=ui(e6_(),1);var k5E="etag",q1c="preview",T1c="app-preview",e9E="bundle",t9E=".next",C1c=".fern";function r9E({app:e=!1}){return Ru(ll.of((0,yru.homedir)()),Na.of(C1c),Na.of(e?T1c:q1c))}function gKi({app:e=!1}){return Ru(ll.of((0,yru.homedir)()),Na.of(C1c),Na.of(e?T1c:q1c),Na.of(e?t9E:e9E))}function i9E({app:e=!1}){return Ru(ll.of((0,yru.homedir)()),Na.of(C1c),Na.of(e?T1c:q1c),Na.of(k5E))}async function MRa({bucketUrl:e,logger:t,preferCached:r,app:i=!1,tryTar:n=!1}){t.debug("Setting up docs preview bundle...");let a=await fetch(e);if(!a.ok)return{type:"failure"};let u=await a.text(),d=await new i6_.default.Parser().parseStringPromise(u),s=d?.ListBucketResult?.Contents?.[0]?.ETag?.[0],o=d?.ListBucketResult?.Contents?.[0]?.Key?.[0],c=i9E({app:i});if(r){let m=await mf(c),w;if(m&&(t.debug("Reading existing ETag"),w=(await(0,SMe.readFile)(c)).toString()),w!=null&&w===s)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle"),i&&t.info(`Setting up docs preview bundle...
|
|
2044
|
+
${JSON.stringify(r)}"`)}}function TI_(e,t,r,i){let n=r.resolveSourceOrThrow({source:t,relativeFilepath:e.relativeFilepath});if(n==null||n.type!=="protobuf")throw new Error(`Expected a protobuf source for ${t.proto}.`);let a=MI_({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return Hxe.grpc({service:a})}function CI_({rootDefaultUrl:e,rootPathParameters:t,serviceDefinition:r,file:i,errorResolver:n,typeResolver:a,propertyResolver:u,exampleResolver:l,variableResolver:d,sourceResolver:s,globalErrors:o,workspace:c}){let b=s9n({pathParameters:r["path-parameters"],location:$xe.Service,file:i,variableResolver:d}),g=AI_({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:Gae(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:JN(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([w,E])=>OFe({headerKey:w,header:E,file:i})):[],pathParameters:b,encoding:A6E(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([w,E])=>{let q=s9n({pathParameters:hHt(E),location:$xe.Endpoint,file:i,variableResolver:d}),A={...lJ(E),id:"",name:i.casingsGenerator.generateName(w),displayName:E["display-name"],auth:E.auth??r.auth,idempotent:E.idempotent??r.idempotent??!1,baseUrl:E.url??r.url??e,v2BaseUrls:void 0,method:E.method!=null?M6E(E.method):KC.Post,basePath:E["base-path"]!=null?JN(E["base-path"]):void 0,path:JN(E.path),fullPath:JN(E["base-path"]!=null?lb(E["base-path"],E.path):i.rootApiFile["base-path"]!=null?lb(i.rootApiFile["base-path"],r["base-path"],E.path):lb(r["base-path"],E.path)),pathParameters:q,allPathParameters:E["base-path"]!=null?q:[...t,...b,...q],queryParameters:typeof E.request!="string"&&E.request?.["query-parameters"]!=null?Object.entries(E.request["query-parameters"]).map(([D,C])=>deu({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof E.request!="string"&&E.request?.headers!=null?Object.entries(E.request.headers).map(([D,C])=>OFe({headerKey:D,header:C,file:i})):[],requestBody:HB_({request:E.request,file:i}),sdkRequest:KB_({service:r,request:E.request,endpoint:E,endpointKey:w,file:i,typeResolver:a,propertyResolver:u}),response:mI_({endpoint:E,file:i,typeResolver:a}),errors:[...EI_({errors:E.errors,file:i}),...o],userSpecifiedExamples:E.examples!=null?E.examples.map(D=>({example:OI_({service:r,endpoint:E,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:d,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(C=>YB_({codeSample:C,file:i}))})):[],autogeneratedExamples:[],pagination:DI_({propertyResolver:u,file:i,endpointName:w,endpointSchema:E}),transport:qI_({file:i,serviceTransport:g,endpointDeclaration:E,sourceResolver:s}),v2Examples:void 0,source:void 0,audiences:E.audiences};return A.id=jm.generateEndpointId(O,A),A}),audiences:r.audiences}}function s9n({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>D6E({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function D6E({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...lJ(t),name:i.casingsGenerator.generateName(e),valueType:E6E({parameter:t,variableResolver:n,file:i}),location:r,variable:fxn(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function E6E({parameter:e,variableResolver:t,file:r}){let i=Jxa({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function Jxa({parameter:e,variableResolver:t,file:r}){let i=_eu({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function _eu({parameter:e,variableResolver:t,file:r}){if(fxn(e)){let i=typeof e=="string"?e:e.variable,n=t.getDeclaration(i,r);return n==null?void 0:{rawType:typeof n.declaration=="string"?n.declaration:n.declaration.type,file:n.file}}else return{file:r,rawType:typeof e=="string"?e:e.type}}function M6E(e){switch(e){case"GET":return KC.Get;case"POST":return KC.Post;case"PUT":return KC.Put;case"PATCH":return KC.Patch;case"DELETE":return KC.Delete;case"HEAD":return KC.Head;default:jo(e)}}function OFe({headerKey:e,header:t,file:r}){let{name:i}=Eir({headerKey:e,header:t});return{...lJ(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:i}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function Eir({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function A6E(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:jo(e)}}var BI_="1.0.0";var heu=class{ir;casingsGenerator;auth;authValues;generatorConfig;constructor(t){this.ir=t.ir,this.generatorConfig=t.generatorConfig,this.casingsGenerator=BZ({generationLanguage:t.generationLanguage,smartCasing:t.smartCasing??!1,keywords:void 0}),this.auth=this.convertAuth(this.ir.auth),this.authValues=this.getAuthValues(this.ir.auth)}convert({disableExamples:t}){return{version:BI_,types:this.convertNamedTypes(),headers:this.convertHeaders(),endpoints:this.convertEndpoints({disableExamples:t}),pathParameters:this.convertPathParameters({pathParameters:this.ir.pathParameters}),environments:this.ir.environments,generatorConfig:this.generatorConfig}}convertNamedTypes(){return Object.fromEntries(Object.entries(this.ir.types).map(([t,r])=>[t,this.convertTypeDeclaration(r)]))}convertHeaders(){return this.convertWireValueParameters({wireValueParameters:this.ir.headers})}convertEndpoints({disableExamples:t}){let r=this.getAllHttpEndpoints();return Object.fromEntries(r.map(i=>[i.id,this.convertEndpoint({endpoint:i,disableExamples:t})]))}convertEndpoint({endpoint:t,disableExamples:r}){let i=this.convertEndpointLocation({endpoint:t});return{auth:this.auth,declaration:this.convertDeclaration({name:t.name,fernFilepath:t.fernFilepath}),location:i,request:this.convertRequest({endpoint:t}),response:bs.Response.json(),examples:r?void 0:this.getEndpointSnippetRequests({endpoint:t,location:i})}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:[...t.servicePathParameters,...t.pathParameters]});if(t.sdkRequest==null&&t.requestBody==null)return bs.Request.body({pathParameters:r,body:void 0});if(t.sdkRequest==null)throw new Error(`Internal error; endpoint "${t.id}" has a request body but no SDK request`);switch(t.sdkRequest.shape.type){case"justRequestBody":return bs.Request.body({pathParameters:r,body:this.convertReferencedRequestBodyType({body:t.sdkRequest.shape.value})});case"wrapper":return this.convertInlinedRequest({fernFilepath:t.fernFilepath,wrapper:t.sdkRequest.shape,pathParameters:r,queryParameters:this.convertQueryParameters({queryParameters:t.queryParameters}),headers:this.convertWireValueParameters({wireValueParameters:[...t.serviceHeaders,...t.headers]}),body:t.requestBody});default:jo(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return bs.ReferencedRequestBodyType.bytes();case"typeReference":return bs.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:jo(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:i,queryParameters:n,headers:a,body:u}){return bs.Request.inlined({declaration:this.convertDeclaration({name:r.wrapperName,fernFilepath:t}),pathParameters:i,queryParameters:n,headers:a,body:u!=null?this.convertInlinedRequestBody({wrapper:r,body:u}):void 0,metadata:this.convertInlinedRequestMetadata({wrapper:r})})}convertInlinedRequestMetadata({wrapper:t}){return{includePathParameters:t.includePathParameters??!1,onlyPathParameters:t.onlyPathParameters??!1}}convertInlinedRequestBody({wrapper:t,body:r}){switch(r.type){case"inlinedRequestBody":{let i=[...r.extendedProperties??[],...r.properties];return bs.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:i}))}case"reference":return bs.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:bs.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return bs.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:bs.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:jo(r)}}convertFileUploadRequestBody({properties:t}){return bs.InlinedRequestBody.fileUpload({properties:this.convertFileUploadRequestBodyProperties({properties:t})})}convertFileUploadRequestBodyProperties({properties:t}){return t.map(r=>{switch(r.type){case"file":return this.convertFileUploadRequestBodyFileProperty({fileProperty:r.value});case"bodyProperty":return bs.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:jo(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return bs.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return bs.FileUploadRequestBodyProperty.fileArray(t.key);default:jo(t)}}convertPathParameters({pathParameters:t}){return t.map(r=>({name:{name:r.name,wireValue:r.name.originalName},typeReference:this.convertTypeReference(r.valueType)}))}convertWireValueParameters({wireValueParameters:t}){return t.map(r=>({name:{name:r.name.name,wireValue:r.name.wireValue},typeReference:this.convertTypeReference(r.valueType)}))}convertQueryParameters({queryParameters:t}){let r=[];for(let i of t){let n=this.convertTypeReference(i.valueType);i.allowMultiple&&(n=bs.TypeReference.list(n)),r.push({name:{name:i.name.name,wireValue:i.name.wireValue},typeReference:n})}return r}convertTypeReference(t){switch(t.type){case"container":return this.convertContainerType(t.container);case"named":return this.convertNamedType(t);case"primitive":return this.convertPrimitiveType(t.primitive);case"unknown":return this.convertUnknownType();default:jo(t)}}convertContainerType(t){switch(t.type){case"list":return bs.TypeReference.list(this.convertTypeReference(t.list));case"map":return bs.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return bs.TypeReference.optional(this.convertTypeReference(t.optional));case"nullable":return bs.TypeReference.nullable(this.convertTypeReference(t.nullable));case"set":return bs.TypeReference.set(this.convertTypeReference(t.set));case"literal":return bs.TypeReference.literal(this.convertLiteral(t.literal));default:jo(t)}}convertNamedType(t){return bs.TypeReference.named(t.typeId)}convertTypeDeclaration(t){let r=this.convertDeclaration(t.name);switch(t.shape.type){case"alias":return this.convertAlias({declaration:r,alias:t.shape});case"enum":return this.convertEnum({declaration:r,enum_:t.shape});case"object":return this.convertObject({declaration:r,object:t.shape});case"union":return this.convertDiscriminatedUnion({declaration:r,union:t.shape});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({declaration:r,union:t.shape});default:jo(t.shape)}}convertAlias({declaration:t,alias:r}){return bs.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return bs.NamedType.enum({declaration:t,values:r.values.map(i=>i.name)})}convertObject({declaration:t,object:r}){let i=[...r.extendedProperties??[],...r.properties];return this.convertObjectProperties({declaration:t,properties:i,additionalProperties:r.extraProperties})}convertObjectProperties({declaration:t,properties:r,additionalProperties:i}){return bs.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r}),additionalProperties:i})}convertDiscriminatedUnion({declaration:t,union:r}){let i=[...this.resolveProperties(r.extends),...r.baseProperties];return bs.NamedType.discriminatedUnion({declaration:t,discriminant:r.discriminant,types:Object.fromEntries(r.types.map(n=>[n.discriminantValue.wireValue,this.convertDiscriminatedUnionType({inheritedProperties:i,discriminantValue:n.discriminantValue,singleUnionTypeProperties:n.shape})]))})}convertDiscriminatedUnionType({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperties:i}){switch(i.propertiesType){case"samePropertiesAsObject":return this.convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i});case"singleProperty":return this.convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i});case"noProperties":return this.convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r});default:jo(i)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i}){return bs.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:i.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:t})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i}){return bs.SingleDiscriminatedUnionType.singleProperty({typeReference:this.convertTypeReference(i.type),discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r}){return bs.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return bs.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(i=>this.convertTypeReference(i.type))})}convertLiteral(t){switch(t.type){case"boolean":return bs.LiteralType.boolean(t.boolean);case"string":return bs.LiteralType.string(t.string);default:jo(t)}}convertPrimitiveType(t){return bs.TypeReference.primitive(t.v1)}convertUnknownType(){return bs.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return bs.Auth.basic(r);case"bearer":return bs.Auth.bearer(r);case"header":return bs.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return bs.Auth.oauth({clientId:this.casingsGenerator.generateName("clientId"),clientSecret:this.casingsGenerator.generateName("clientSecret")});default:jo(r)}}getAuthValues(t){let r=t.schemes[0];if(r!=null)switch(r.type){case"bearer":return bs.AuthValues.bearer({token:"<token>"});case"basic":return bs.AuthValues.basic({username:"<username>",password:"<password>"});case"header":return bs.AuthValues.header({value:"<value>"});case"oauth":return bs.AuthValues.oauth({clientId:"<clientId>",clientSecret:"<clientSecret>"});default:jo(r)}}convertDeclaration({name:t,fernFilepath:r}){return{name:t,fernFilepath:r}}convertEndpointLocation({endpoint:t}){return{method:t.method,path:this.getFullPathForEndpoint(t)}}getAllHttpEndpoints(){return Object.values(this.ir.services).flatMap(t=>t.endpoints.map(r=>({...r,servicePathParameters:t.pathParameters,serviceHeaders:t.headers,fernFilepath:t.name.fernFilepath})))}resolveProperties(t){let r=[];for(let i of t){let n=this.resolveObjectTypeOrThrow(i.typeId);r.push(...this.resolveProperties(n.extends)),r.push(...n.properties)}return Object.values(r)}resolveObjectTypeOrThrow(t){let r=this.ir.types[t];if(r==null)throw new Error(`Internal error; type "${t}" not found`);if(r.shape.type!=="object")throw new Error(`Internal error; type "${t}" is not an object`);return r.shape}getFullPathForEndpoint(t){let r="";t.fullPath.head.length>0&&(r=lb(r,t.fullPath.head));for(let i of t.fullPath.parts)r=lb(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=lb(r,i.tail));return r.startsWith("/")?r:`/${r}`}getEndpointSnippetRequests({endpoint:t,location:r}){let i=[];for(let n of[...t.userSpecifiedExamples,...t.autogeneratedExamples])i.push({id:n?.example?.id??lae(),name:n?.example?.name?.originalName,endpoint:r,baseUrl:void 0,environment:void 0,auth:this.authValues,headers:Object.fromEntries([...n.example?.serviceHeaders??[],...n.example?.endpointHeaders??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),pathParameters:Object.fromEntries([...n.example?.rootPathParameters??[],...n.example?.servicePathParameters??[],...n.example?.endpointPathParameters??[]].map(a=>[a.name.originalName,a.value.jsonExample])),queryParameters:Object.fromEntries([...n.example?.queryParameters??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),requestBody:n.example?.request?.jsonExample});return i}};function II_({ir:e,generationLanguage:t,smartCasing:r,disableExamples:i,generatorConfig:n}){return new heu({ir:e,generationLanguage:t,smartCasing:r,generatorConfig:n}).convert({disableExamples:i})}var fJ={};Po(fJ,{validateObjectExample:()=>sKi,validateTypeExample:()=>leu,validateTypeReferenceExample:()=>sL});var yeu=class{subpackages={};rootPackage={docs:void 0,fernFilepath:{allParts:[],packagePath:[],file:void 0},websocket:void 0,service:void 0,types:[],errors:[],subpackages:[],webhooks:void 0,navigationConfig:void 0};addPackageRedirection({from:t,to:r}){let i=this.getPackageForFernFilepath(t);if(i.navigationConfig!=null)throw new Error("Found duplicate navigationConfig for package");i.navigationConfig={pointsTo:jm.generateSubpackageId(r)}}addDocs(t,r){let i=this.getPackageForFernFilepath(t);if(i.docs!=null)throw new Error("Found duplicate docs for package");i.docs=r}addSubpackage(t){this.getPackageForFernFilepath(t)}addType(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).types.push(t)}addError(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).errors.push(t)}addService(t,r){let i=this.getPackageForFernFilepath(r.name.fernFilepath);if(i.service!=null)throw new Error("Found duplicate service for "+t);i.service=t}addWebhookGroup(t,r){let i=this.getPackageForFernFilepath(r);if(i.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);i.webhooks=t}addWebSocketChannel(t,r){let i=this.getPackageForFernFilepath(r);if(i.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);i.websocket=t}build(t){t!=null&&(Object.entries(this.subpackages).forEach(([i,n])=>{t.hasSubpackageId(i)?this.subpackages[i]={...n,types:n.types.filter(a=>t.hasTypeId(a)),errors:n.errors.filter(a=>t.hasErrorId(a)),service:n.service!=null&&t.hasServiceId(n.service)?n.service:void 0,websocket:n.websocket!=null&&t.hasChannel(n.websocket)?n.websocket:void 0,subpackages:n.subpackages.filter(a=>t.hasSubpackageId(a))}:delete this.subpackages[i]}),this.rootPackage={...this.rootPackage,types:this.rootPackage.types.filter(i=>t.hasTypeId(i)),errors:this.rootPackage.errors.filter(i=>t.hasErrorId(i)),service:this.rootPackage.service!=null&&t.hasServiceId(this.rootPackage.service)?this.rootPackage.service:void 0,subpackages:this.rootPackage.subpackages.filter(i=>t.hasSubpackageId(i)),webhooks:this.rootPackage.webhooks!=null?this.rootPackage.webhooks:void 0});let r=new Set(this.getAllChildrenWithEndpoints(this.rootPackage));return{subpackages:fd(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!zI_(this.rootPackage.subpackages,t))throw new Error("Sorted subpackages differ from unsorted packages in root");this.rootPackage.subpackages=t}sortSubpackage(t,r){let i=this.subpackages[t];if(i==null)throw new Error("Subpackage does not exist: "+t);if(!zI_(i.subpackages,r))throw new Error("Sorted subpackages differ from unsorted packages");i.subpackages=r}getAllSubpackagesWithEndpoints(t){let r=this.subpackages[t];if(r==null)throw new Error("Subpackage does not exist: "+t);let i=this.getAllChildrenWithEndpoints(r);return(i.length>0||r.service!=null)&&i.push(t),i}getAllChildrenWithEndpoints(t){return t.subpackages.flatMap(r=>[...this.getAllSubpackagesWithEndpoints(r)])}getPackageForFernFilepath(t,r=0,i=this.rootPackage){let n=t.allParts[r];if(n==null)return i;let a=i.subpackages.map(s=>{let o=this.subpackages[s];if(o==null)throw new Error("Subpackage ID is invalid: "+s);return o}),u=r+1,l={allParts:t.allParts.slice(0,u),packagePath:t.packagePath.slice(0,u),file:u===t.allParts.length?t.file:void 0},d=a.find(s=>s.name.originalName===n.originalName);if(d==null){let s=jm.generateSubpackageId(l),o={docs:void 0,fernFilepath:l,name:n,service:void 0,types:[],errors:[],subpackages:[],navigationConfig:void 0,webhooks:void 0,websocket:void 0};this.subpackages[s]=o,i.subpackages.push(s),d=o}return this.getPackageForFernFilepath(t,u,d)}};function zI_(e,t){if(e.length!==t.length)return!1;let r=new Set(e);for(let i of t)if(!r.has(i))return!1;return!0}function xI_(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}var veu=e=>{let t=tMe(e.file.fernFilepath),r=e.endpointId;return`endpoint_${t}.${r}`};function beu({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function RI_({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r}),a;try{a=i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0}catch{}return{endpointReference:{endpointId:veu(n),serviceId:jm.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:beu({fernFilePath:n.file.fernFilepath})?void 0:jm.generateSubpackageId(n.file.fernFilepath)},requestProperties:{refreshToken:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.refresh_token})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:a,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}function NI_({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r}),a=typeof n.endpoint.request=="object"&&n.endpoint.request.body!=null&&typeof n.endpoint.request.body=="object"&&"properties"in n.endpoint.request.body?n.endpoint.request.body.properties??{}:{},u;try{u=i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0}catch{}return{endpointReference:{endpointId:veu(n),serviceId:jm.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:beu({fernFilePath:n.file.fernFilepath})?void 0:jm.generateSubpackageId(n.file.fernFilepath)},requestProperties:{clientId:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.client_id}),clientSecret:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.client_secret}),scopes:i.requestProperties.scopes!=null?t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.scopes}):void 0,customProperties:q6E({requestBodyProperties:a,tokenEndpoint:i,file:r,propertyResolver:t})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:u,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}var q6E=({requestBodyProperties:e,tokenEndpoint:t,file:r,propertyResolver:i})=>{let n=Object.keys(e).filter(a=>!t.requestProperties.client_id.includes(a)&&!t.requestProperties.client_secret.includes(a)&&(t.requestProperties.scopes==null||!t.requestProperties.scopes.includes(a)));return n.length>0?n.map(a=>i.resolveRequestPropertyOrThrow({file:r,endpoint:t.endpoint,propertyComponents:[a]})):void 0};function FI_({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=NI_({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?RI_({propertyResolver:e,endpointResolver:t,file:r,refreshTokenEndpoint:a}):void 0;return{clientIdEnvVar:i["client-id-env"],clientSecretEnvVar:i["client-secret-env"],tokenPrefix:i["token-prefix"],tokenHeader:i["token-header"],scopes:i.scopes,tokenEndpoint:u,refreshEndpoint:l}}var Kxa={requestProperties:{type:"access_token",client_id:["client_id"],client_secret:["client_secret"],scopes:void 0},responseProperties:{type:"access_token",access_token:["access_token"],expires_in:["expires_in"],refresh_token:void 0}},Bjc={requestProperties:{type:"refresh_token",refresh_token:["refresh_token"]},responseProperties:{type:"access_token",access_token:["access_token"],refresh_token:void 0,expires_in:["expires_in"]}};function LI_(e){return{endpoint:e["get-token"].endpoint,requestProperties:T6E({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:C6E({responseProperties:e["get-token"]?.["response-properties"]})}}function UI_(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:B6E({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:I6E({responseProperties:e["refresh-token"]?.["response-properties"]})}}function T6E({requestProperties:e}){if(e==null)return Kxa.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?_Ht(t):Kxa.requestProperties.client_id,client_secret:r!=null?_Ht(r):Kxa.requestProperties.client_secret,scopes:i!=null?_Ht(i):Kxa.requestProperties.scopes}}function C6E({responseProperties:e}){return VI_({responseProperties:e,defaultValue:Kxa.responseProperties})}function B6E({requestProperties:e}){if(e==null)return Bjc.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?_Ht(t):Bjc.requestProperties.refresh_token}}function I6E({responseProperties:e}){return VI_({responseProperties:e,defaultValue:Bjc.responseProperties})}function VI_({responseProperties:e,defaultValue:t}){if(e==null)return t;let r=e["access-token"],i=e["expires-in"],n=e["refresh-token"];return{type:"access_token",access_token:r!=null?Dir(r):t.access_token,expires_in:i!=null?Dir(i):t.expires_in,refresh_token:n!=null?Dir(n):t.refresh_token}}function QI_({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:bne.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return cWi(e.auth,{single:a=>{let u=WI_({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:bne.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:bne.Any,schemes:a.map(u=>WI_({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function WI_({reference:e,authSchemeDeclarations:t,file:r,propertyResolver:i,endpointResolver:n}){let a=(l,d)=>{let s=t?.[l];if(s==null)throw new Error("Unknown auth scheme: "+l);return d1a(s,{header:o=>BT.header({docs:d,name:r.casingsGenerator.generateNameAndWireValue({name:o.name??l,wireValue:o.header}),valueType:r.parseTypeReference(o.type??"string"),prefix:o.prefix,headerEnvVar:o.env}),basic:o=>$I_({file:r,docs:d,rawScheme:o}),bearer:o=>HI_({file:r,docs:d,rawScheme:o}),oauth:o=>GI_({file:r,docs:d,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return HI_({file:r,docs:void 0,rawScheme:void 0});case"basic":return $I_({file:r,docs:void 0,rawScheme:void 0});case"oauth":return GI_({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function HI_({file:e,docs:t,rawScheme:r}){return BT.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function $I_({file:e,docs:t,rawScheme:r}){return BT.basic({docs:t,username:e.casingsGenerator.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.casingsGenerator.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function GI_({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return BT.oauth({docs:t,configuration:Xwi.clientCredentials(FI_({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:LI_(r),refreshTokenEndpoint:UI_(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function JI_({file:e,rawApiFileSchema:t}){if(t.version!=null)return e1i.header({header:z6E({file:e,header:t.version.header}),value:x6E({file:e,versionDeclaration:t.version})})}function z6E({file:e,header:t}){return typeof t=="string"?OFe({file:e,headerKey:t,header:{type:"string"}}):OFe({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function x6E({file:e,versionDeclaration:t}){return feu({_enum:{default:t.default,enum:t.values},file:e})}function KI_({channel:e,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a}){let u=[];for(let[l,d]of Object.entries(e.messages??{}))u.push({type:l,availability:Gae(d.availability),docs:d.docs,origin:d.origin,body:F6E({body:d.body,file:n}),displayName:d["display-name"]});return{availability:Gae(e.availability),path:JN(e.path),baseUrl:e.url,auth:e.auth,name:n.fernFilepath.file??n.casingsGenerator.generateName(e["display-name"]??e.path),displayName:e["display-name"],headers:e.headers!=null?Object.entries(e.headers).map(([l,d])=>OFe({headerKey:l,header:d,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?s9n({pathParameters:e["path-parameters"],location:$xe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,d])=>{let{name:s}=lpi({queryParameterKey:l,queryParameter:d}),o=n.parseTypeReference(d);return{...lJ(d),name:n.casingsGenerator.generateNameAndWireValue({wireValue:l,name:s}),valueType:o,allowMultiple:typeof d!="string"&&d["allow-multiple"]!=null?d["allow-multiple"]:!1,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}):[],messages:Object.values(u),examples:(e.examples??[]).map(l=>{let d=U6E({channel:e,example:l,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a});return{name:l.name!=null?n.casingsGenerator.generateName(l.name):void 0,docs:l.docs,url:W6E({channel:e,example:l,pathParams:d}),...d,...V6E({channel:e,example:l,typeResolver:t,exampleResolver:r,file:n,workspace:a}),queryParameters:l["query-parameters"]!=null?Object.entries(l["query-parameters"]).map(([s,o])=>{let c=e["query-parameters"]?.[s];if(c==null)throw new Error(`Query parameter ${s} does not exist`);return{name:n.casingsGenerator.generateNameAndWireValue({name:lpi({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:GE({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:R6E({queryParameter:c})}}):[],messages:l.messages.map(s=>{let o=e.messages?.[s.type];if(o==null)throw new Error(`Message ${s.type} does not exist`);return{type:s.type,body:N6E({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}}),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function R6E({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?A2.exploded():A2.single()}function N6E({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!H6E(e.body))return DEe.reference(GE({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!Gj(t))throw new Error("Example must be an object");let u=[];for(let[l,d]of Object.entries(t)){let s=e.body.properties?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:uL({propertyKey:l,property:s}).name,wireValue:l}),value:GE({example:d,rawTypeBeingExemplified:typeof s!="string"?s.type:s,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),originalTypeDeclaration:void 0});else{let o=Qxa({extends_:e.body.extends,wirePropertyKey:l,typeResolver:r,file:n});if(o==null)throw new Error("Could not find original type declaration for property: "+l);u.push({name:n.casingsGenerator.generateNameAndWireValue({name:uL({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:GE({example:d,rawTypeBeingExemplified:typeof o.rawPropertyType=="string"?o.rawPropertyType:o.rawPropertyType.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:o.file,fileContainingExample:n,workspace:a}),originalTypeDeclaration:o.typeName})}}return DEe.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function F6E({body:e,file:t}){return typeof e=="string"?D9.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):L6E(e)?D9.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):D9.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:pHt(e.extends??[]).map(r=>oL({typeName:r,file:t})),properties:Object.entries(e.properties??{}).map(([r,i])=>({name:t.casingsGenerator.generateNameAndWireValue({name:uL({propertyKey:r,property:i}).name,wireValue:r}),value:t.parseTypeReference(i),valueType:t.parseTypeReference(i),availability:void 0,docs:void 0}))})}function L6E(e){return e.type!=null}function U6E({channel:e,example:t,typeResolver:r,exampleResolver:i,variableResolver:n,file:a,workspace:u}){let l=[],d=({name:s,pathParameterDeclaration:o,examplePathParameter:c})=>{let b=Jxa({parameter:o,variableResolver:n,file:a});return{name:s,value:GE({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=hHt(e);for(let[o,c]of Object.entries(t["path-parameters"])){let b=s[o];if(b!=null)l.push(d({name:a.casingsGenerator.generateName(o),pathParameterDeclaration:b,examplePathParameter:c}));else throw new Error(`Path parameter ${o} does not exist`)}}return{pathParameters:l}}function V6E({channel:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=[];if(t.headers!=null)for(let[l,d]of Object.entries(t.headers)){let s=e.headers?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:Eir({headerKey:l,header:s}).name,wireValue:l}),value:GE({example:d,rawTypeBeingExemplified:typeof s=="string"?s:s.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})});else throw new Error(`Heder ${l} does not exist`)}return{headers:u}}function W6E({channel:e,example:t,pathParams:r}){let i=e.path;if(t["path-parameters"]!=null)for(let n of[...r.pathParameters])i=i.replaceAll(`{${n.name.originalName}}`,encodeURIComponent(`${n.value.jsonExample}`));return i}function H6E(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function YI_({errorName:e,errorDeclaration:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=[];if(t.type!=null&&t.examples!=null)for(let l of t.examples)u.push({name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,docs:l.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:l.value,file:r}).resolvedExample,shape:GE({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:yAi({errorName:e,file:r}),discriminantValue:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:e}),docs:typeof t!="string"?t.docs:void 0,statusCode:t["status-code"],type:t.type!=null?r.parseTypeReference(t.type):void 0,examples:u,v2Examples:void 0,displayName:void 0}}var XI_="content";function ZI_(e,t){if(e==null||e.strategy==="status-code")return SEe.statusCode();switch(e.strategy){case"property":return SEe.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:XI_,wireValue:XI_})});default:jo(e)}}function kI_({readme:e,services:t}){let r=new Ijc(t);return{apiReferenceLink:e.apiReferenceLink,bannerLink:e.bannerLink,introduction:e.introduction,defaultEndpoint:e.defaultEndpoint!=null?r.getEndpointForReadmeOrThrow(e.defaultEndpoint).id:void 0,features:e.features!=null?Object.fromEntries(Object.entries(e.features).map(([i,n])=>[i,n.map(a=>r.getEndpointForReadmeOrThrow(a).id)])):void 0}}var Ijc=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=G6E({endpoint:t}),i=this.getEndpointKeyForReadmeEndpoint(r);return this.endpoints[i]}getEndpointForReadmeOrThrow(t){let r=this.getEndpointForReadme(t);if(r==null)throw new Error(`Endpoint not found for ${JSON.stringify(t)}`);return r}buildEndpoints(t){let r={};for(let i of Object.values(t))for(let n of i.endpoints)r[this.getEndpointKeyForHttpEndpoint(n)]=n;return r}getEndpointKeyForReadmeEndpoint(t){return this.getEndpointKey({method:t.method,path:t.path,stream:t.stream??!1})}getEndpointKeyForHttpEndpoint(t){return this.getEndpointKey({method:t.method,path:$6E(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function $6E(e){let t="";e.fullPath.head.length>0&&(t=lb(t,e.fullPath.head));for(let r of e.fullPath.parts)t=lb(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=lb(t,r.tail));return t.startsWith("/")?t:`/${t}`}function G6E({endpoint:e}){if(typeof e=="string"){let t=e.split(" ");if(t.length!==2||t[0]==null||t[1]==null)throw new Error(`invalid endpoint string: ${e}`);return{method:t[0],path:t[1]}}return e}function ez_({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:jm.generateWebhookId(t.fernFilepath,u),availability:Gae(l.availability),displayName:l["display-name"],docs:l.docs,method:l.method,name:t.casingsGenerator.generateName(u),headers:l.headers!=null?Object.entries(l.headers).map(([d,s])=>OFe({headerKey:d,header:s,file:t})):[],payload:Q6E({payload:l.payload,file:t}),examples:l.examples!=null?K6E({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0,v2Examples:void 0});return a}function Q6E({payload:e,file:t}){return typeof e=="string"?fW.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):X6n(e)?fW.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):fW.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:pHt(e.extends).map(r=>oL({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>J6E({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?Gae(i.availability):void 0,file:t})):[]})}function J6E({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:uL({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function K6E({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:X6n(e.payload)?e.payload.type:void 0;if(u!=null)return t.map(l=>({docs:e.docs,name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,payload:GE({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!Gj(e.payload))throw new Error(`Example webhook payload is not an object. Got: ${JSON.stringify(e.payload)}`);return t.map(l=>({docs:e.docs,name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,payload:GE({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function tz_({name:e,source:t}){return Kj.userDefined({file:peu({source:t}),name:vAi.generateName(e)})}function rz_({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=Y6E({type:e.proto.type});if(t!=null)return t}}function Y6E({type:e}){switch(e){case"google.protobuf.Any":return Kj.wellKnown(id.any());case"google.protobuf.Api":return Kj.wellKnown(id.api());case"google.protobuf.BoolValue":return Kj.wellKnown(id.boolValue());case"google.protobuf.BytesValue":return Kj.wellKnown(id.bytesValue());case"google.protobuf.DoubleValue":return Kj.wellKnown(id.doubleValue());case"google.protobuf.Duration":return Kj.wellKnown(id.duration());case"google.protobuf.Empty":return Kj.wellKnown(id.empty());case"google.protobuf.Enum":return Kj.wellKnown(id.enum());case"google.protobuf.EnumValue":return Kj.wellKnown(id.enumValue());case"google.protobuf.Field":return Kj.wellKnown(id.field());case"google.protobuf.FieldCardinality":return Kj.wellKnown(id.fieldCardinality());case"google.protobuf.FieldKind":return Kj.wellKnown(id.fieldKind());case"google.protobuf.FieldMask":return Kj.wellKnown(id.fieldMask());case"google.protobuf.FloatVlaue":return Kj.wellKnown(id.floatValue());case"google.protobuf.Int32Value":return Kj.wellKnown(id.int32Value());case"google.protobuf.Int64Value":return Kj.wellKnown(id.int64Value());case"google.protobuf.ListValue":return Kj.wellKnown(id.listValue());case"google.protobuf.Method":return Kj.wellKnown(id.method());case"google.protobuf.Mixin":return Kj.wellKnown(id.mixin());case"google.protobuf.NullValue":return Kj.wellKnown(id.nullValue());case"google.protobuf.Option":return Kj.wellKnown(id.option());case"google.protobuf.SourceContext":return Kj.wellKnown(id.sourceContext());case"google.protobuf.StringValue":return Kj.wellKnown(id.stringValue());case"google.protobuf.Struct":return Kj.wellKnown(id.struct());case"google.protobuf.Syntax":return Kj.wellKnown(id.syntax());case"google.protobuf.Timestamp":return Kj.wellKnown(id.timestamp());case"google.protobuf.Type":return Kj.wellKnown(id.type());case"google.protobuf.Uint32Value":return Kj.wellKnown(id.uint32Value());case"google.protobuf.Uint64Value":return Kj.wellKnown(id.uint64Value());case"google.protobuf.Value":return Kj.wellKnown(id.value())}}function iz_({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=Zx(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&xS(a.declaration)){let u=Zx(a.typeName)?.arguments??[],l=Object.entries(a.declaration.properties??{}).map(([d,s])=>{let o=s;return typeof s=="string"&&u?.includes(s)&&(o=n.arguments?.[u.indexOf(s)]??s),[d,o]});return Sb.object({extends:pHt(a.declaration.extends).map(d=>oL({typeName:d,file:t})),properties:Vxa({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function nz_({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return Vxe(i)?iz_({generic:i,file:t,typeResolver:r}):Sb.alias({aliasOf:t.parseTypeReference(e),resolvedType:X6E({aliasOf:i,file:t,typeResolver:r})})}function X6E({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return lW.primitive(i.originalTypeReference.primitive);case"container":return lW.container(i.originalTypeReference.container);case"unknown":return lW.unknown();case"named":{let n=xS(i.declaration)?PVt.Object:c1i(i.declaration)?PVt.Union:DVt(i.declaration)?PVt.Enum:dxn(i.declaration)?PVt.UndiscriminatedUnion:jo(i.declaration);return lW.named({name:i.name,shape:n})}}}function az_({union:e,file:t}){let r=e.union.filter((i,n)=>{let a=typeof i=="string"?i:i.type;return e.union.findIndex(u=>(typeof u=="string"?u:u.type)===a)===n});return Sb.undiscriminatedUnion({members:r.map(i=>{let n=t.parseTypeReference(typeof i=="string"?i:i.type);return{type:n.type==="named"?{...n,displayName:typeof i=="string"?Fyo(n.name.originalName):i["display-name"]??Fyo(n.name.originalName)}:n,docs:typeof i=="string"?void 0:i.docs}})})}function oz_(e){let t=[];if(e.extends!=null){let r=typeof e.extends=="string"?[e.extends]:e.extends;t.push(...r)}return e.properties!=null&&t.push(...Object.values(e.properties).map(r=>typeof r=="string"?r:r.type)),t}function xjc({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new zjc}){let n=n3(e,{alias:u=>{let l=typeof u=="string"?u:u.type,d=Zx(l);if(d!=null){let s=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=Zx(o.typeName)?.arguments;if(xS(o.declaration)){let b=oz_(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>oz_(u),discriminatedUnion:u=>{let l=[];return u["base-properties"]!=null&&l.push(...Object.values(u["base-properties"]).map(d=>typeof d=="string"?d:d.type)),l.push(...Object.values(u.union).reduce((d,s)=>{let o=typeof s=="string"?s:s.type;return typeof o=="string"&&d.push(o),d},[])),l},undiscriminatedUnion:u=>Object.values(u.union).reduce((l,d)=>{let s=typeof d=="string"?d:d.type;return typeof s=="string"&&l.push(s),l},[]),enum:()=>[]}),a=[];for(let u of n){let l=q2({type:u,_default:void 0,validation:void 0,visitor:{primitive:()=>[],map:({keyType:d,valueType:s})=>[...d,...s],list:d=>d,optional:d=>d,nullable:d=>d,set:d=>d,named:d=>[d],literal:()=>[],unknown:()=>[]}});for(let d of l){let s=oL({typeName:d,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(Vxe(o.typeName))continue;a.push(...xjc({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var zjc=class{cache=new Set;addTypeName(t){this.cache.add(this.computeCacheKey(t))}hasTypeNameBeenSeen(t){return this.cache.has(this.computeCacheKey(t))}computeCacheKey(t){return t.fernFilepath.allParts.map(r=>r.originalName).join("/")+":"+t.name.originalName}};function uz_({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=lJ(t),d=oL({typeName:e,file:r}),s=xjc({typeDeclaration:t,file:r,typeResolver:i}),o={};xS(t)&&(o=RGi(t.properties??{}));let c=k6E({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:i4E(t),name:d,shape:Z6E({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:e4E({typeDeclaration:t,source:c}),source:c,userProvidedExamples:typeof t!="string"&&t.examples!=null?t.examples.map(b=>({name:b.name!=null?r.casingsGenerator.generateName(b.name):void 0,docs:b.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:b.value,file:r}).resolvedExample,shape:Cjc({typeName:d,example:b.value,typeResolver:i,exampleResolver:n,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[],v2Examples:void 0},descendantFilepaths:new Set(s.map(b=>b.fernFilepath))}}function Z6E({typeDeclaration:e,file:t,typeResolver:r}){return n3(e,{alias:i=>nz_({alias:i,file:t,typeResolver:r}),object:i=>VB_({object:i,file:t}),discriminatedUnion:i=>iI_({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>az_({union:i,file:t}),enum:i=>Sb.enum(feu({_enum:i,file:t}))})}function k6E({file:e,typeDeclaration:t,typeName:r,sourceResolver:i}){if(typeof t=="string"||t.source==null&&t.encoding==null)return;if(t.encoding!=null){let a=rz_({encoding:t.encoding});if(a!=null)return dli.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return dli.proto(tz_({source:n,name:r}))}function e4E({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?t4E(e.encoding):r4E(t)}function t4E(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function r4E(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function i4E(e){if(typeof e!="string"&&"inline"in e)return e.inline}function sz_(e,t){let r=t[e];if(r==null)throw new Uci(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function cz_(e){e.types=Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,a4E({typeDeclaration:r,ir:e})])),e.services=Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>n4E({endpoint:i,ir:e}))}]))}function n4E({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>lz_(r,t))}}}function a4E({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>lz_(r,t))}}}return e}function lz_(e,t){let r=Rjc(e.typeId,t);return fz_({objectTypeDeclaration:r,ir:t})}function Rjc(e,t){let r=sz_(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return Rjc(r.shape.resolvedType.name.typeId,t)}throw new Uci(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function fz_({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=Rjc(i.typeId,t);return fz_({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function dz_({reference:e,referencedIn:t,imports:r}){let[i,n,...a]=e.split(".");if(i==null||a.length>0)return;if(n==null)return{endpointName:i,relativeFilepath:t};let l=r[i];if(l!=null)return{endpointName:n,relativeFilepath:hAi({referencedIn:t,importPath:l})}}var lKi=class{workspace;constructor(t){this.workspace=t}resolveEndpointOrThrow({endpoint:t,file:r}){let i=this.resolveEndpoint({endpoint:t,file:r});if(i==null)throw new Error("Cannot resolve endpoint: "+t+" in file "+r.relativeFilepath);return i}resolveEndpointByMethodAndPath({method:t,path:r}){let i;return D3(this.workspace,(n,a,u)=>{let l=M0({relativeFilepath:n,definitionFile:a,casingsGenerator:vAi,rootApiFile:this.workspace.definition.rootApiFile.contents,defaultUrl:u.defaultUrl});for(let[d,s]of Object.entries(a.service?.endpoints??{}))s.method===t&&s.path===r&&(i={endpointId:d,endpoint:s,file:l})}),TQi(this.workspace,(n,a)=>{let u=M0({relativeFilepath:n,definitionFile:a,casingsGenerator:vAi,rootApiFile:this.workspace.definition.rootApiFile.contents});for(let[l,d]of Object.entries(a.service?.endpoints??{}))d.method===t&&d.path===r&&(i={endpointId:l,endpoint:d,file:u})}),i}resolveEndpoint({endpoint:t,file:r}){let n=new lWi().tryParse(t);if(n!=null)return this.resolveEndpointByMethodAndPath(n);let a=this.getDeclarationOfEndpoint({referenceToEndpoint:t,file:r});if(a==null)return;let u=a.file.definitionFile.service?.endpoints?.[a.endpointName];if(u!=null)return{endpointId:a.endpointName,endpoint:u,file:a.file}}getDeclarationOfEndpoint({referenceToEndpoint:t,file:r}){let i=dz_({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=zae(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:M0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var fKi=class{workspace;constructor(t){this.workspace=t}getDeclarationOrThrow(t,r){let i=this.getDeclaration(t,r);if(i==null)throw new Error("Error does not exist: "+t);return i}getDeclaration(t,r){let i=gMe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=zae(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:M0({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var mMe=class{typeResolver;constructor(t){this.typeResolver=t}resolveAllReferencesInExample({example:t,file:r}){if(typeof t=="string"){let i=this.resolveExample({example:t,file:r});return i==null||typeof i.resolvedExample=="string"?i:this.resolveAllReferencesInExample({example:i.resolvedExample,file:i.file})}else if(Gj(t)){let i={};for(let[n,a]of Object.entries(t)){let u=this.resolveAllReferencesInExample({example:a,file:r});if(u==null)return;i[n]=u.resolvedExample}return{resolvedExample:i}}else if(Array.isArray(t)){let i=[];for(let n of t){let a=this.resolveAllReferencesInExample({example:n,file:r});if(a==null)return;i.push(a.resolvedExample)}return{resolvedExample:i}}return{resolvedExample:t}}resolveAllReferencesInExampleOrThrow({example:t,file:r}){let i=this.resolveAllReferencesInExample({example:t,file:r});if(i==null)throw new Error("Failed to resolve examples");return i}resolveExample({example:t,file:r}){if(typeof t!="string")return{resolvedExample:t,file:r};if(t.startsWith(`\\${YZt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(YZt))return{resolvedExample:t,file:r};let i=this.parseExampleReference(t);if(i==null)return;let n=this.typeResolver.getDeclarationOfNamedType({referenceToNamedType:i.rawTypeReference,file:r});if(n==null||typeof n.declaration=="string"||n.declaration.examples==null)return;let a=n.declaration.examples.find(u=>u.name===i.exampleName);if(a!=null)return this.resolveExample({example:a.value,file:n.file})}resolveExampleOrThrow({example:t,file:r}){let i=this.resolveExample({example:t,file:r});if(i==null)throw new Error("Cannot resolve example: "+t);return i}parseExampleReference(t){let[r,i,n,...a]=t.split(".");if(!(r==null||i==null||a.length>0))return n==null?{rawTypeReference:r.slice(YZt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(YZt.length),exampleName:n}}};var geu=class{typeResolver;endpointResolver;constructor(t,r){this.typeResolver=t,this.endpointResolver=r,this.typeResolver=t,this.endpointResolver=r}resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i}){let n=this.resolveRequestProperty({file:t,endpoint:r,propertyComponents:i});if(n==null)throw new Error("Cannot resolve request property from endpoint: "+r+" in file "+t.relativeFilepath);return n}resolveRequestProperty({file:t,endpoint:r,propertyComponents:i}){let n=this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t});if(n.endpoint.request==null)return;if(typeof n.endpoint.request!="string")return this.resolveRequestPropertyFromInlinedRequest({typeResolver:this.typeResolver,file:n.file,requestType:n.endpoint.request,propertyComponents:i});let a=this.resolveObjectProperty({file:n.file,typeName:n.endpoint.request,propertyComponents:i});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:i,file:t}),property:One.body(a)}}resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i}){let n=this.resolveResponseProperty({file:t,endpoint:r,propertyComponents:i});if(n==null)throw new Error("Cannot resolve response property from endpoint: "+r+" in file "+t.relativeFilepath);return n}resolveResponseProperty({file:t,endpoint:r,propertyComponents:i}){let n=this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t}),a=this.resolveObjectProperty({file:n.file,typeName:(typeof n.endpoint.response!="string"?n.endpoint.response?.type:n.endpoint.response)??"",propertyComponents:i});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:i,file:t}),property:a}}resolveRequestPropertyFromInlinedRequest({typeResolver:t,file:r,requestType:i,propertyComponents:n}){if(n.length===1){let a=n[0]??"",u=i["query-parameters"]?.[a]??void 0;if(u!=null)return{property:One.query(deu({file:r,queryParameterKey:a,queryParameter:u})),propertyPath:void 0}}return this.resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:i,propertyComponents:n})}resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:i,propertyComponents:n}){if(i.body==null)return;if(typeof i.body=="string"){let u=this.resolveObjectProperty({file:r,typeName:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:One.body(u)}}if(JC(i.body)){let u=Mjc({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:One.body(u)}}let a=this.resolveObjectProperty({file:r,typeName:i.body.type,propertyComponents:n});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:One.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return Ejc({typeResolver:this.typeResolver,file:Hxa(n)??t,resolvedType:n,propertyComponents:i})}propertyPathFromPropertyComponents({propertyComponents:t,file:r}){return t.length<=1?[]:t.slice(0,-1).map(i=>r.casingsGenerator.generateName(i))}};var H1=class{workspace;constructor(t){this.workspace=t}resolveTypeOrThrow({type:t,file:r}){let i=this.resolveType({type:t,file:r});if(i==null)throw new Error("Cannot resolve type: "+t+" in file "+r.relativeFilepath);return i}getDeclarationOfNamedTypeOrThrow({referenceToNamedType:t,file:r}){let i=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(i==null)throw new Error("Cannot find declaration of type: "+t+" in file "+r.relativeFilepath);return i}getDeclarationOfNamedType({referenceToNamedType:t,file:r}){let i=gMe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=zae(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=Zx(i.typeName);if(u!=null){for(let l of Object.keys(n.types??{})??[])if(u.name&&l.startsWith(u.name)&&l.endsWith(">")){let d=n.types?.[l];return d!=null?{typeName:l,declaration:d,file:M0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:M0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return q2({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:Kc.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:Kc.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:Kc.container(Py.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:Kc.container(Py.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:Kc.container(Py.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:Kc.container(Py.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:Kc.container(Py.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:Kc.container(Py.literal(n))}),named:n=>{let a=this.getDeclarationOfNamedType({referenceToNamedType:n,file:r});if(a==null)return;let u={typeName:a.typeName,file:a.file.relativeFilepath,reference:n};if(!i.some(l=>l.file===u.file&&l.typeName===u.typeName))return this.resolveNamedTypeFromDeclaration({referenceToNamedType:n,referencedIn:r,rawDeclaration:a,objectPath:[...i,u]})}}})}resolveNamedTypeOrThrow({referenceToNamedType:t,file:r}){let i=this.resolveNamedType({referenceToNamedType:t,file:r});if(i==null)throw new Error("Cannot resolve type: "+t);return i}resolveNamedType({referenceToNamedType:t,file:r}){let i=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(i!=null)return this.resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:i})}resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:i,objectPath:n=[]}){let{declaration:a,file:u}=i;if(s1i(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=Gxa({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||zae(this.workspace,u.relativeFilepath)==null))return{_type:"named",rawName:i.typeName,name:l,declaration:a,filepath:u.relativeFilepath,objectPath:n,originalTypeReference:l,file:u}}};var vHt=class e{static VARIABLE_PREFIX="$";getDeclarationOrThrow(t,r){let i=this.getDeclaration(t,r);if(i==null)throw new Error("Variable does not exist: "+t);return i}getDeclaration(t,r){if(!t.startsWith(e.VARIABLE_PREFIX))return;let i=r.rootApiFile.variables?.[t.substring(1)];if(i!=null)return{declaration:i,file:cpi({casingsGenerator:r.casingsGenerator,rootApiFile:r.rootApiFile})}}getVariableIdOrThrow(t){let r=this.getVariableId(t);if(r==null)throw new Error("Variable reference does not start with "+e.VARIABLE_PREFIX);return r}getVariableId(t){if(t.startsWith(e.VARIABLE_PREFIX))return t.substring(e.VARIABLE_PREFIX.length)}};function Oeu(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function hR({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,exampleGeneration:n,audiences:a,readme:u,packageName:l,version:d,fdrApiDefinitionId:s,sourceResolver:o,disableDynamicExamples:c,dynamicGeneratorConfig:b}){let g=BZ({generationLanguage:t,keywords:r,smartCasing:i}),O=new NGi(a),m=cpi({casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents}),w=(e.definition.rootApiFile.contents.errors??[]).map(ot=>({error:yAi({errorName:ot,file:m}),docs:void 0})),E=new H1(e),q=new lKi(e),A=new geu(E,q),D=new fKi(e),C=new mMe(E),x=new vHt,I=RTa({casingsGenerator:g,rawApiFileSchema:e.definition.rootApiFile.contents})?.environmentsConfig,F={selfHosted:!1,fdrApiDefinitionId:s,apiVersion:JI_({file:m,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:g.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:Uxa(e.definition.rootApiFile.contents.docs),auth:QI_({rawApiFileSchema:e.definition.rootApiFile.contents,file:m,propertyResolver:A,endpointResolver:q}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([ot,at])=>OFe({headerKey:ot,header:at,file:m})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([ot,at])=>OFe({headerKey:ot,header:at,file:m})):[],types:{},errors:{},services:{},constants:xI_(g),environments:I,errorDiscriminationStrategy:ZI_(e.definition.rootApiFile.contents["error-discrimination"],m),basePath:e.definition.rootApiFile.contents["base-path"]!=null?JN(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:s9n({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:m,location:$xe.Root,variableResolver:x}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([ot,at])=>({docs:typeof at!="string"?at.docs:void 0,id:ot,name:m.casingsGenerator.generateName(ot),type:m.parseTypeReference(at)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,audiences:e.definition.rootApiFile.contents.audiences},V=new yeu,K=ot=>{V.addSubpackage(ot.fernFilepath),Cw(ot.definitionFile,{imports:Go,docs:at=>{at!=null&&V.addDocs(ot.fernFilepath,at)},types:at=>{if(at!=null)for(let[me,we]of Object.entries(at)){if(Vxe(me))continue;let jt=uz_({typeName:me,typeDeclaration:we,file:ot,typeResolver:E,exampleResolver:C,sourceResolver:o,workspace:e}),gt=jt.typeDeclaration;n.disabled&&(gt.userProvidedExamples=[],gt.autogeneratedExamples=[]);let qr=jt.descendantFilepaths,lr=jm.generateTypeId(gt.name);F.types[lr]=gt,V.addType(lr,gt),O.addType({declaredTypeName:gt.name,descendantTypeIds:gt.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:jt.propertiesByAudience,descendantFilepaths:qr}),O.markTypeForAudiences(gt.name,UB_(we))}},errors:at=>{if(at==null)return;if(e.definition.rootApiFile.contents["error-discrimination"]==null)throw new Error("error-discrimination is missing in api.yml but there are declared errors.");for(let[we,jt]of Object.entries(at)){let gt=YI_({errorName:we,errorDeclaration:jt,file:ot,typeResolver:E,exampleResolver:C,workspace:e}),qr=jm.generateErrorId(gt.name);F.errors[qr]=gt,V.addError(qr,gt),O.addError(gt)}},service:at=>{if(at==null)return;let me=CI_({rootDefaultUrl:ot.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:F.pathParameters,serviceDefinition:at,file:ot,errorResolver:D,typeResolver:E,propertyResolver:A,exampleResolver:C,sourceResolver:o,globalErrors:w,variableResolver:x,workspace:e}),we=jm.generateServiceId(me.name);F.services[we]=me,V.addService(we,me);let jt={};me.endpoints.forEach(gt=>{n.disabled&&(gt.autogeneratedExamples=[],gt.userSpecifiedExamples=[]);let qr=at.endpoints[gt.name.originalName];O.addEndpoint(me,gt,qr),jt[gt.name.originalName]=gt}),at.audiences!=null&&O.markEndpointForAudience(me.name,me.endpoints,at.audiences),Object.entries(at.endpoints).map(([gt,qr])=>{let lr=jt[gt];lr!=null&&qr.audiences!=null&&O.markEndpointForAudience(me.name,[lr],qr.audiences)})},webhooks:at=>{if(at==null)return;let me=jm.generateWebhookGroupId(ot.fernFilepath),we=ez_({webhooks:at,file:ot,typeResolver:E,exampleResolver:C,workspace:e}),jt={};for(let gt of we)jt[gt.name.originalName]=gt;Object.entries(at).forEach(([gt,qr])=>{let lr=jt[gt];lr!=null&&(O.addWebhook(ot.fernFilepath,lr,qr),qr.audiences!=null&&O.markWebhookForAudiences(ot.fernFilepath,lr,qr.audiences))}),F.webhookGroups[me]=we,V.addWebhookGroup(me,ot.fernFilepath)},channel:at=>{if(at==null)return;let me=jm.generateWebSocketChannelId(ot.fernFilepath),we=KI_({channel:at,file:ot,variableResolver:x,typeResolver:E,exampleResolver:C,workspace:e});O.addChannel(ot.fernFilepath,me,we,at),at.audiences!=null&&O.markChannelForAudiences(ot.fernFilepath,me,at.audiences),F.websocketChannels!=null&&(F.websocketChannels[me]=we,V.addWebSocketChannel(me,ot.fernFilepath))}})};D3(e,(ot,at,me)=>{K(M0({relativeFilepath:ot,definitionFile:at,casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:me.defaultUrl}))}),TQi(e,(ot,at)=>{if(at.navigation!=null)if(typeof at.navigation=="string")V.addPackageRedirection({from:$ae({relativeFilepath:ot,casingsGenerator:g}),to:$ae({relativeFilepath:EN(axe(ot),Oy.of(at.navigation)),casingsGenerator:g})});else{let me=at.navigation.map(we=>jm.generateSubpackageId($ae({relativeFilepath:EN(axe(ot),Oy.of(we)),casingsGenerator:g})));ot===TS?V.sortRootPackage(me):V.sortSubpackage(jm.generateSubpackageId($ae({relativeFilepath:ot,casingsGenerator:g})),me)}}),F.serviceTypeReferenceInfo=u4E(O),cz_(F);let Y=n.disabled?F:xTa({ir:F,exampleGeneration:n}),Z=e.definition.rootApiFile.contents,oe=I?.environments._visit({singleBaseUrl:ot=>ot.environments.filter(at=>Oeu(at.id,Z.environments)!=null).length===0,multipleBaseUrls:ot=>ot.environments.filter(at=>Oeu(at.id,Z.environments)!=null).length===0,_other:()=>!1});I?.environments.environments.forEach(ot=>{O.markEnvironmentForAudiences(ot,Oeu(ot.id,Z.environments)??[],oe)});let pe=O.hasNoAudiences()?void 0:O.build(),de=Ioc(Y,pe),Oe=e.definition.rootApiFile.contents.auth!=null&&Object.values(de.services).every(ot=>ot.endpoints.every(at=>at.auth)),Ue=Object.values(de.services).some(ot=>ot.endpoints.some(at=>at.response?.body?.type==="streaming")),wt=Object.values(de.services).some(ot=>ot.endpoints.some(at=>at.pagination!=null)),De=Object.values(de.services).some(ot=>ot.endpoints.some(at=>at.response?.body?.type==="fileDownload")),Te={isAuthMandatory:Oe,hasStreamingEndpoints:Ue,hasPaginatedEndpoints:wt,hasFileDownloadEndpoints:De,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:d!=null&&l!=null?{header:"User-Agent",value:`${l}/${d}`}:void 0}},xt=u!=null?kI_({readme:u,services:F.services}):void 0,Pe=o4E({...de,...V.build(pe),sdkConfig:Te,readmeConfig:xt});return{...Pe,dynamic:II_({ir:Pe,generatorConfig:b,disableExamples:c,generationLanguage:t,smartCasing:i})}}function o4E(e){let t=r=>{if(!r||typeof r!="object")return r;if(Array.isArray(r))return r.map(t);for(let i in r){let n=r[i];i==="docs"&&typeof n=="string"?r[i]=Uxa(n):n&&typeof n=="object"&&t(n)}return r};return t(e)}function u4E(e){let t={},r=[],i=e.getTypesReferencedByService();for(let[n,a]of Object.entries(i)){if(a.size===1){let u=a.values().next().value;if(u==null)break;t[u]===void 0&&(t[u]=[]),t[u]?.push(n);continue}r.push(n)}return{typesReferencedOnlyByService:t,sharedTypes:r}}function pz_(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var hz_=ui(wCn(),1);var _z_=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function bHt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,hz_.default)(e,{special:_z_}).replace(/V\s(\d)/g,"V$1")}function Yxa(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&pz_(e),r._other(e))}}}function Mir(e){return typeof e.subpackageId=="string"}function c9n(e,t){return`${e} ${tB(t)}`}function tB(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function mFe(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var Njc="__package__",gAi=class e{api;context;static create(t,r){return new e(t,r)}#e=new Map;#t=new Map;#r=new Map;#n=new Map;#i=new Map;#a=new Map;#o=new Map;#s=new Map;#f=new Map;#u=new Map;#l=new Map;static getSubpackageId(t){return Mir(t)?t.subpackageId:Njc}getSubpackageByIdOrLocator(t){if(t==null)return;let r=Y6.SubpackageId(t),i=Y6.SubpackageId(`subpackage_${d_(t)}`);return r===Njc?this.api.rootPackage:this.api.subpackages[r]??this.#l.get(r)??this.api.subpackages[i]??this.#l.get(i)}resolveSubpackage(t){if(t!=null){for(;t?.pointsTo!=null;)t=this.api.subpackages[t.pointsTo];return t}}constructor(t,r){this.api=t,this.context=r,[t.rootPackage,...Object.values(t.subpackages)].forEach(i=>{let n=Y6.SubpackageId(e.getSubpackageId(i)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map};this.#o.set(n,a),i.endpoints.forEach(u=>{a.endpoints.set(u.id,u);let l=e.createEndpointId(u,n);this.#e.set(l,u);let d=[],s=[u.method];u.response?.type.type==="stream"&&s.push("STREAM"),s.forEach(o=>{d.push(`${o} ${tB(u.path.parts)}`),d.push(`${o} ${mFe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${lb(c.baseUrl,tB(u.path.parts))}`),d.push(`${o} ${lb(c.baseUrl,mFe(u.path.parts))}`);let b=meu(c);b!=null&&(d.push(`${o} ${lb(b,tB(u.path.parts))}`),d.push(`${o} ${lb(b,mFe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering endpoint locator: ${o}`),this.#s.set(o,u)})}),i.websockets.forEach(u=>{a.webSockets.set(u.id,u);let l=e.createWebSocketId(u,n);this.#t.set(l,u);let d=[];["GET","WSS"].forEach(o=>{d.push(`${o} ${tB(u.path.parts)}`),d.push(`${o} ${mFe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${lb(c.baseUrl,tB(u.path.parts))}`),d.push(`${o} ${lb(c.baseUrl,mFe(u.path.parts))}`);let b=meu(c);b!=null&&(d.push(`${o} ${lb(b,tB(u.path.parts))}`),d.push(`${o} ${lb(b,mFe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering websocket locator: ${o}`),this.#f.set(o,u)})}),i.webhooks.forEach(u=>{a.webhooks.set(u.id,u),this.#r.set(e.createWebhookId(u,n),u)})}),this.#e.forEach((i,n)=>{this.#n.set(i,n)}),this.#t.forEach((i,n)=>{this.#i.set(i,n)}),this.#r.forEach((i,n)=>{this.#a.set(i,n)}),this.#c(t.rootPackage,[])}#c(t,r){if(t==null)return;let i=Mir(t)?[...r,t.name]:r,n=i.length===0?[Njc]:i;if([n.join("."),n.join("/"),`${n.join(".")}.yml`].forEach(u=>{this.context?.logger.trace(`Registering subpackage locator: ${u}`),this.#l.set(u,t)}),t.pointsTo!=null)return this.#c(this.api.subpackages[t.pointsTo],i);t.endpoints.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering endpoint locator: ${s}`),this.#s.set(s,u)})}),t.websockets.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering websocket locator: ${s}`),this.#f.set(s,u)})}),t.webhooks.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering webhook locator: ${s}`),this.#u.set(s,u)})}),t.subpackages.forEach(u=>{this.#c(this.api.subpackages[u],i)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#r}get endpointsByLocator(){return this.#s}get webSocketsByLocator(){return this.#f}get webhooksByLocator(){return this.#u}get subpackages(){return this.#o}get subpackagesByLocator(){return this.#l}getEndpointId(t){return this.#n.get(t)}getWebSocketId(t){return this.#i.get(t)}getWebhookId(t){return this.#a.get(t)}static createEndpointId(t,r){return So.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return So.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return So.WebhookId(`${r}.${t.id}`)}};function meu(e){if(e!=null){if(e.baseUrl.startsWith("/"))return e.baseUrl;if(e.baseUrl.startsWith("http")||e.baseUrl.startsWith("ws"))try{return new URL(e.baseUrl).pathname}catch{return}}}var l9n=ui(lZo(),1),vz_=ui(fZo(),1);function yz_(e){let t=e.split(".")[0];if(t==null)return;let i=/(^\d{1,4})-(\d{1,2})-(\d{1,4})/.exec(t)?.[0];if(i!=null)try{return new Date(i)}catch{}}l9n.default.extend(vz_.default);var s4E="Changelog",c4E=["summary","index","overview"],fpi=class{markdownToFullSlug;markdownToNoIndex;changelogFiles;docsWorkspace;idgen;constructor(t,r,i,n,a){this.markdownToFullSlug=t,this.markdownToNoIndex=r,this.changelogFiles=i,this.docsWorkspace=n,this.idgen=a}toChangelogNode(t){let r=t.title??s4E,i=[],n;for(let b of this.changelogFiles??[]){let g=QBs(b.split("/"));if(g==null)continue;let O=yz_(g);if(O==null){let w=g.split(".")[0]?.toLowerCase();w!=null&&c4E.includes(w)&&(n=b);continue}let m=this.toRelativeFilepath(b);i.push({date:O,pageId:So.PageId(m),absoluteFilepath:b})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??Tq(r)}),u=n!=null?this.markdownToNoIndex.get(n):void 0,l=i.map(b=>{let g=l9n.default.utc(b.date);return{id:this.idgen.get(b.pageId),type:"changelogEntry",title:g.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(b.absoluteFilepath)?.split("/"),urlSlug:g.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:b.date.toISOString(),pageId:b.pageId,noindex:this.markdownToNoIndex.get(b.absoluteFilepath),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),d=Fjc(l,b=>b.date,"desc"),s=n!=null?So.PageId(this.toRelativeFilepath(n)):void 0,o=this.idgen.get(s??"changelog"),c=this.groupByYear(o,d,a);return{id:o,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:c,overviewPageId:s,noindex:u,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:void 0}}orUndefined(){return this.changelogFiles!=null&&this.changelogFiles.length>0?this:void 0}groupByYear(t,r,i){let n=new Map;for(let a of r){let u=l9n.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return Fjc(Array.from(n.entries()).map(([a,u])=>{let l=i.append(a.toString()).get(),d=this.idgen.get(`${t}/year/${a}`);return{id:d,type:"changelogYear",title:a.toString(),year:a,slug:l,icon:void 0,hidden:void 0,children:this.groupByMonth(d,u,i),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),"year","desc")}groupByMonth(t,r,i){let n=new Map;for(let a of r){let u=l9n.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return Fjc(Array.from(n.entries()).map(([a,u])=>{let l=(0,l9n.default)(new Date(0,a-1));return{id:this.idgen.get(`${t}/month/${a}`),type:"changelogMonth",title:l.format("MMMM YYYY"),month:a,slug:i.append(a.toString()).get(),icon:void 0,hidden:void 0,children:u,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),"month","desc")}toRelativeFilepath(t){if(t!=null)return Bq(this.docsWorkspace.absoluteFilePath,t)}};function Fjc(e,t,r="asc"){return e.concat().sort((i,n)=>{let a=typeof t=="function"?t(i):i[t],u=typeof t=="function"?t(n):n[t];return a<u?r==="asc"?-1:1:a>u?r==="asc"?1:-1:0})}function Peu(e){if(e)return{environments:e.environments!=null&&e.environments.length>0?e.environments.map(t=>So.V1.EnvironmentId(t)):void 0,button:e.button!=null&&e.button.href?{href:So.V1.Url(e.button.href)}:void 0,"limit-websocket-messages-per-connection":e.limitWebsocketMessagesPerConnection!=null?e.limitWebsocketMessagesPerConnection:void 0}}function Xxa({child:e,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i}){if(e.type==="apiPackage"){let n=So.V1.SlugGenerator.init(e.slug),u=(t.get(e.id)??[]).flatMap(s=>r(s,n)),l=e.children.map(s=>Xxa({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),d=i(l,u);return{...e,children:d,pointsTo:void 0}}return e}function f9n({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)return e;let a=[],u=new Map;return e.forEach(l=>{if(l.type!=="endpoint"){a.push(l);return}let d=t(l.endpointId);if(d==null)throw new Error(`Endpoint ${l.endpointId} not found`);let s=`${d.method} ${r(d)}`,o=u.get(s);if(u.set(s,l),o==null||o.isResponseStream===l.isResponseStream){a.push(l);return}let c=a.indexOf(o),b=l.isResponseStream?l:o,g=l.isResponseStream?o:l,O={id:So.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[c]=O}),a}function jeu({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return f9n({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function Air(e,t){if(t!=null)return Bq(e.absoluteFilePath,t)}function weu({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let l=So.V1.PageId(Air(e,t.absolutePath)),d=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??Tq(t.title)});return{id:i.get(l),type:"page",pageId:l,title:t.title,slug:d.get(),icon:t.icon,hidden:u||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var Seu=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;workspace;hideChildren;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Map;#o=[];#s;#f;#u;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=u,this.markdownFilesToNoIndex=l,this.workspace=s,this.hideChildren=o,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=So.V1.ApiDefinitionId(r.id),this.#e=gAi.create(r,a),this.#u=d,this.#s=this.apiSection.overviewAbsolutePath!=null?So.V1.PageId(Air(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#f=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Tq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#l(this.apiSection.navigation,this.#e.api.rootPackage,this.#f)),this.#o=this.#O(this.#o.map(b=>this.#v(b)),this.#P(this.#e.api.rootPackage,this.#f))}get(){let t=So.V1.followRedirects(this.#o),r=new fpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#u).orUndefined();return{id:this.#u.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#s,paginated:this.apiSection.paginated,slug:this.#f.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#f,viewers:void 0,hidden:this.hideChildren}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#g(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#l(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?gAi.getSubpackageId(r):void 0;return t.map(a=>Yxa(a)._visit({link:u=>({id:this.#u.get(u.url),type:"link",title:u.text,icon:u.icon,url:So.Url(u.url)}),page:u=>this.#c(u,i),package:u=>this.#p(u,i),section:u=>this.#h(u,i),item:({value:u})=>this.#_(u,n,i),endpoint:u=>this.#y(u,n,i)})).filter(yv)}#c(t,r){return weu({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#u,hideChildren:this.hideChildren})}#p(t,r){let i=t.overviewAbsolutePath!=null?So.V1.PageId(Air(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=gAi.getSubpackageId(a),l=this.#u.get(i??`${this.apiDefinitionId}:${u}`);this.#i.has(u)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${u}`),this.#i.add(u),this.#a.set(l,[u]);let d=t.slug??(Mir(a)?a.urlSlug:this.apiSection.slug??Tq(this.apiSection.title)),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,a,s);return{id:l,type:"apiPackage",children:o,title:t.title??(Mir(a)?a.displayName??bHt(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??Tq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#l(t.contents,void 0,l);return{id:this.#u.get(i??`${this.apiDefinitionId}:${Tq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#h(t,r){let i=t.overviewAbsolutePath!=null?So.V1.PageId(Air(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,u=this.#u.get(i??n??r.get()),l=t.referencedSubpackages.map(c=>{let b=this.#e.getSubpackageByIdOrLocator(c);return b!=null?gAi.getSubpackageId(b):void 0}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(yv);this.#a.set(u,l),l.forEach(c=>{this.#i.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#i.add(c)});let d=t.slug??Tq(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#l(t.contents,void 0,s);return{id:u,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:a,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#_(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(d_(t));if(n!=null){let a=gAi.getSubpackageId(n),u=this.#u.get(`${this.apiDefinitionId}:${a}`);this.#i.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#i.add(a),this.#a.set(u,[a]);let l=Mir(n)?n.urlSlug:"",d=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:Mir(n)?n.displayName??bHt(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#y({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#y(t,r,i){let n=(r!=null?this.#e.subpackages.get(Y6.SubpackageId(r))?.endpoints.get(Y6.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let l=this.#e.getEndpointId(n);if(l==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${c9n(n.method,n.path.parts)}. Got undefined.`);else{this.#t.has(l)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${l}`),this.#t.add(l);let d=t.slug!=null?i.append(t.slug):i.apply(n);return{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"endpoint",method:n.method,endpointId:l,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??tB(n.path.parts),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let a=(r!=null?this.#e.subpackages.get(Y6.SubpackageId(r))?.webSockets.get(Y6.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let l=this.#e.getWebSocketId(a);if(l==null)this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);else return this.#r.has(l)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${l}`),this.#r.add(l),{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"webSocket",webSocketId:l,title:t.title??a.name??tB(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(a.availability),playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(Y6.SubpackageId(r))?.webhooks.get(Y6.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(So.V1.WebhookId(t.endpoint));if(u!=null){let l=this.#e.getWebhookId(u);if(l==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#n.has(l)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${l}`),this.#n.add(l),{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"webhook",webhookId:l,method:u.method,title:t.title??u.name??lb("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#O(t,r){return jeu({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>tB(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#v(t){return Xxa({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(r,i)=>this.#j(r,i),mergeAndFilterChildren:this.#O.bind(this)})}#P(t,r){let i=[];return t.endpoints.forEach(n=>{let a=this.#e.getEndpointId(n);if(a==null){this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${c9n(n.method,n.path.parts)}. Got undefined.`);return}if(this.#t.has(a))return;let u=r.apply(n);i.push({id:So.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??tB(n.path.parts),slug:u.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null){this.taskContext.logger.error(`Expected WebSocket ID for ${n.id}. Got undefined.`);return}this.#r.has(a)||i.push({id:So.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??tB(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(n.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(n=>{let a=this.#e.getWebhookId(n);if(a==null){this.taskContext.logger.error(`Expected Webhook ID for ${n.id}. Got undefined.`);return}this.#n.has(a)||i.push({id:So.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??bHt(n.id),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#i.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=Mir(a)?r.apply(a):r,l=this.#j(n,u);l.length>0&&i.push({id:So.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:l,title:Mir(a)?a.displayName??bHt(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)})),i}#j(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#P(i,r)}#g(t){return Peu(t)}mergeEndpointPairs(t){return f9n({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>tB(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Deu=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[d_(r).toLowerCase()]=i,this.#e[`subpackage_${d_(r).toLowerCase()}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${lb(a.baseUrl,tB(i.path))}`]=i,this.#r[`${n} ${lb(a.baseUrl,mFe(i.path))}`]=i;let u=meu(a);u!=null&&(this.#r[`${n} ${lb(u,tB(i.path))}`]=i,this.#r[`${n} ${lb(u,mFe(i.path))}`]=i)}),this.#r[`${i.method} ${tB(i.path)}`]=i,this.#r[`${i.method} ${mFe(i.path)}`]=i}for(let[r,i]of Object.entries(t.webhooks))this.#t[r]=i,this.#t[r.replace("webhook_","")]=i,this.#t[r.replace("webhook_","subpackage_")]=i,this.#t[`${i.method} ${i.path.join("/")}`]=i;for(let[r,i]of Object.entries(t.websockets))this.#n[r]=i,this.#n[r.replace("websocket_","")]=i,this.#n[r.replace("websocket_","subpackage_")]=i,this.#n[`STREAM ${tB(i.path)}`]=i,this.#n[`STREAM ${mFe(i.path)}`]=i}getSubpackageByLocator(t){if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"].some(i=>t.includes(i)))return;let r=t.replace(".yml","").replace(".yaml","");return this.#e[r]}getWebhookByLocator(t,r){return this.#t[t]??this.#t[`${r}.${t}`]??this.#t[`webhook_${r}.${t}`]}getEndpointByLocator(t,r){return this.#r[t]??this.#r[`${r}.${t}`]??this.#r[`endpoint_${r}.${t}`]}getWebSocketByLocator(t,r){return this.#n[t]??this.#n[`${r}.${t}`]??this.#n[`websocket_${r}.${t}`]}};function Zxa({item:e,parentSlug:t}){return t.apply({urlSlug:Tq(e.id.split(".").pop()??"")}).get()}var kxa=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;hideChildren;apiDefinitionId;#e;#t;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#f;#u;#l;#c=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.markdownFilesToNoIndex=d,this.hideChildren=o,this.#e=r,this.#t=new Deu(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=So.V1.ApiDefinitionId(r.id),this.#l=s,this.#f=this.apiSection.overviewAbsolutePath!=null?So.V1.PageId(Air(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Tq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#s=this.#p(this.apiSection.navigation,void 0,this.#u)),this.#s=this.#P(this.#s.map(b=>this.#j(b)),this.#g(this.#e,this.#u))}get(){let t=So.V1.followRedirects(this.#s),r=new fpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#l).orUndefined();return{id:this.#l.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#f,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#S(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#p(t,r,i){return t.map(n=>Yxa(n)._visit({link:a=>({id:this.#l.get(a.url),type:"link",title:a.text,icon:a.icon,url:So.Url(a.url)}),page:a=>this.#h(a,i),package:a=>this.#_(a,i),section:a=>this.#y(a,i),item:({value:a})=>this.#O(a,r,i),endpoint:a=>this.#v(a,r,i)})).filter(yv)}#h(t,r){return weu({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#l,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#_(t,r){let i=t.overviewAbsolutePath!=null?So.V1.PageId(Air(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#t.getSubpackageByLocator(t.package);if(a!=null){let u=this.#l.get(i??`${this.apiDefinitionId}:${a.id}`);this.#a.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#a.add(a.id),this.#o.set(u,[a.id]);let l=t.slug??Tq(a.name),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#p(t.contents,a.id,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??bHt(a.name),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#c.set(a.id,o),o}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??Tq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#p(t.contents,t.package,l),s={id:this.#l.get(i??`${this.apiDefinitionId}:${Tq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#c.set(t.package,s),s}}#y(t,r){let i=t.overviewAbsolutePath!=null?So.V1.PageId(Air(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#l.get(i??n??r.get()),u=t.referencedSubpackages.map(c=>{let b=this.#t.getSubpackageByLocator(c);return b?.id}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(yv);this.#o.set(a,u),u.forEach(c=>{this.#a.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#a.add(c)});let l=t.slug??Tq(t.title),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#p(t.contents,t.title,d),o={id:a,type:"apiPackage",children:s,title:t.title,slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return u.forEach(c=>{this.#c.set(c,o)}),o}#O(t,r,i){t=t.trim();let n=this.#t.getSubpackageByLocator(t);if(n!=null){let a=n.id,u=this.#l.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#a.add(a),this.#o.set(u,[a]);let l=Tq(n.name),d=i.apply({urlSlug:l}),s={id:u,type:"apiPackage",children:[],title:n.displayName??bHt(n.name),slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#c.set(a,s),s}return this.#v({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#v(t,r,i){let n=this.#t.getEndpointByLocator(t.endpoint,r);if(n!=null)if(this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${n.id}`),n.id==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${c9n(n.method,n.path)}. Got undefined.`);else{this.#r.add(n.id);let l=t.slug!=null?i.append(t.slug).get():Zxa({item:n,parentSlug:i});return{id:this.#l.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??tB(n.path),slug:l,icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#t.getWebSocketByLocator(t.endpoint,r);if(a!=null)if(this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${a.id}`),a.id==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}else return this.#n.add(a.id),{id:this.#l.get(`${this.apiDefinitionId}:${a.id}`),type:"webSocket",webSocketId:a.id,title:t.title??a.displayName??tB(a.path),slug:t.slug!=null?i.append(t.slug).get():Zxa({item:a,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(a.availability),playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};let u=this.#t.getWebhookByLocator(t.endpoint,r);if(u!=null)if(this.#i.has(u.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${u.id}`),u.id==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#i.add(u.id),{id:this.#l.get(`${this.apiDefinitionId}:${u.id}`),type:"webhook",webhookId:u.id,method:u.method,title:t.title??u.displayName??lb("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():Zxa({item:u,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#P(t,r){return jeu({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>tB(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#j(t){return Xxa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#E(r,i),mergeAndFilterChildren:this.#P.bind(this)})}#g(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(!this.#a.has(n)){let u=this.#w(n,a,r);u!=null&&i.push(u)}}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Endpoint ID for ${a.id} at path: ${c9n(a.method,a.path)}. Got undefined.`);return}!this.#r.has(JA.EndpointId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#m(n,a,r,i)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}!this.#n.has(JA.WebSocketId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#A(n,a,r,i)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}!this.#i.has(JA.WebhookId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#d(n,a,r,i)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)}),i}#w(t,r,i){let n=So.V1.SlugGenerator.init(i.get()).apply({urlSlug:Tq(r.name)}),a=this.#E(t,n),u={id:So.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??bHt(r.name),slug:n.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#c.set(t,u),a.length>0?u:void 0}#D(t,r,i,n){r.slug=Zxa({item:t,parentSlug:i}),n.push(r)}#m(t,r,i,n){let a={id:So.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"endpoint",method:r.method,endpointId:JA.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??tB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#A(t,r,i,n){let a={id:So.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webSocket",webSocketId:JA.WebSocketId(t),title:r.displayName??tB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(r.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#d(t,r,i,n){let a={id:So.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webhook",webhookId:JA.WebhookId(t),method:r.method,title:r.displayName??bHt(r.id),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#D(r,a,i,n)}#T(t){let r=Object.fromEntries(Object.entries(this.#e?.subpackages??{}).filter(([u,l])=>t===this.#e.id?l.id.split(".").length===1:l.id!=null&&l.id.includes(t)&&l.id!==t&&l.id.split(".").length===t.split(".").length+1)),i=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===JA.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===JA.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===JA.api.v1.SubpackageId(t)));return{id:JA.ApiDefinitionId(t),endpoints:i,websockets:n,webhooks:a,types:{},subpackages:r,auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#E(t,r){let i=t!=null?this.#T(t):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#g(i,r)}#S(t){return Peu(t)}mergeEndpointPairs(t){return f9n({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>tB(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var bz_=ui(require("crypto"),1);function l4E(e){return bz_.default.createHash("sha256").update(e).digest("hex")}var Eeu=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),l4E(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return So.V1.NodeId(this.#n(t))}};function Meu(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0}}var Aeu=ui(PEe(),1);var Ljc=ui(PEe(),1);function gz_(e,t,r){if(e.schemes.length>0&&e.schemes[0]!=null){let i=e.schemes[0];switch(i.type){case"basic":return{type:"basicAuth",passwordName:i.password.originalName,usernameName:i.username.originalName,description:e.docs};case"bearer":return{type:"bearerAuth",tokenName:i.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:i.name.wireValue,nameOverride:i.name.name.originalName,prefix:i.prefix,description:e.docs};case"oauth":{let n=i.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(a=>a.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Ljc.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:Ljc.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:jo(i)}}}var cm=ui(PEe(),1);var OAi=ui(PEe(),1);function mz_(e){return e._visit({alias:t=>({type:"alias",value:jE(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:e4(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>OAi.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:OAi.FernRegistry.PropertyKey(r.name.wireValue),valueType:jE(r.valueType),availability:e4(r.availability),propertyAccess:r.propertyAccess})),extraProperties:p4E(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:OAi.FernRegistry.PropertyKey(i.name.wireValue),valueType:jE(i.valueType),availability:e4(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?e4(i.availability):void 0,additionalProperties:Gs.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[OAi.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:OAi.FernRegistry.PropertyKey(n.name.wireValue),valueType:jE(n.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:jE(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function jE(e){return e._visit({container:t=>Gs.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:jE(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:jE(r),valueType:jE(i)}),optional:r=>({type:"optional",itemType:jE(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:jE(r)}),set:r=>({type:"set",itemType:jE(r)}),literal:r=>Gs.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:OAi.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Gs.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>d4E(t.v2),float:()=>Oz_(t.v2),double:()=>Oz_(t.v2),string:()=>f4E(t.v2),long:()=>({type:"long",default:t.v2?.type==="long"?t.v2.default:void 0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),uint:()=>({type:"uint"}),uint64:()=>({type:"uint64"}),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function f4E(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function d4E(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="integer"?e.default:void 0}}function Oz_(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="double"?e.default:void 0}}function p4E(e){return typeof e=="boolean"?e?Kc.unknown():void 0:typeof e=="string"?{type:"id",value:OAi.FernRegistry.TypeId(e),default:void 0}:jE(e)}function Vjc(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?h4E(r,t):[],webhooks:i!=null?_4E(i):[],websockets:n!=null?[y4E(n,t)]:[],types:e.types.map(a=>cm.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>cm.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?cm.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function _4E(e){return e.map(t=>{let r=[];return t.v2Examples!=null?(r.push(...Object.values(t.v2Examples.userSpecifiedExamples)),r.push(...Object.values(t.v2Examples.autogeneratedExamples))):r.push(...t.examples?.map(i=>({payload:i.payload.jsonExample}))??[]),{description:t.docs??void 0,id:cm.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??oUi(t.name.originalName),headers:t.headers.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:jE(i.valueType),availability:e4(i.availability)})),payload:w4E(t.payload),examples:r}})}function h4E(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let l,d=i.v2Examples.userSpecifiedExamples,s=i.v2Examples.autogeneratedExamples,o=Object.keys(d).length>1;for(let[b,g]of Object.entries(d))l=Pz_({shouldUseExampleName:o,exampleName:b,example:g,irEndpoint:i}),l!=null&&a.push(l);let c=Object.keys(s).length>1;for(let[b,g]of Object.entries(s))l=Pz_({shouldUseExampleName:c,exampleName:b,example:g,irEndpoint:i}),l!=null&&a.push(l)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>Ujc({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(yv));else if(n!=null){let l=Ujc({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=ITa({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let d=Ujc({autogeneratedExample:l,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={slug:void 0,availability:e4(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:O4E(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?cm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?v4E({environmentsConfig:t.environments,endpoint:i}):void 0,id:cm.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??oUi(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:cm.FernRegistry.PropertyKey(l.name.originalName),type:jE(l.valueType),availability:void 0})),parts:[...d9n(i.basePath),...d9n(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:cm.FernRegistry.PropertyKey(l.name.originalName),type:jE(l.valueType),availability:void 0})),parts:[...t.basePath!=null?d9n(t.basePath):[],...d9n(e.basePath),...d9n(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:jE(l.valueType),availability:e4(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:jE(l.valueType),availability:e4(l.availability)})),request:i.requestBody!=null?m4E(i.requestBody):void 0,response:i.response!=null?P4E(i.response):void 0,errors:void 0,errorsV2:j4E(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:()=>({type:"grpc",methodName:i.id}),_other:()=>{}})};r.push(u)}return r}function y4E(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let i=Object.values(e.v2Examples.userSpecifiedExamples),n=Object.values(e.v2Examples.autogeneratedExamples),a=i.length>0?i[0]:n[0];a!=null&&r.push({name:"",description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(u=>({type:cm.FernRegistry.api.v1.WebSocketMessageId(u.type),body:u.body}))??[]})}else r=e.examples.map(i=>({name:i.name?.originalName,description:i.docs,path:i.url,pathParameters:i.pathParameters.reduce((n,a)=>(n[cm.FernRegistry.PropertyKey(a.name.originalName)]=a.value.jsonExample,n),{}),queryParameters:i.queryParameters.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),headers:i.headers.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),messages:i.messages.map(n=>({type:cm.FernRegistry.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}));return{auth:e.auth,availability:e4(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?cm.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?b4E({environmentsConfig:t.environments,channel:e}):[],id:cm.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??oUi(e.name.originalName),path:{pathParameters:e.pathParameters.map(i=>({description:i.docs??void 0,key:cm.FernRegistry.PropertyKey(i.name.originalName),type:jE(i.valueType),availability:void 0})),parts:d9n(e.path)},headers:e.headers.map(i=>({key:i.name.wireValue,type:jE(i.valueType),description:i.docs,availability:e4(i.availability)})),queryParameters:e.queryParameters.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:jE(i.valueType),availability:e4(i.availability)})),messages:e.messages.map(i=>({type:cm.FernRegistry.api.v1.WebSocketMessageId(i.type),displayName:i.displayName,origin:i.origin,body:S4E(i.body),description:i.docs,availability:e4(i.availability)})),examples:r}}function e4(e){if(e!=null)switch(e.status){case"DEPRECATED":return cm.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return cm.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return cm.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return cm.FernRegistry.Availability.Beta;default:jo(e.status)}}function v4E({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl,n=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:cm.FernRegistry.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(n!=null)return n.flatMap(u=>r.environments.map(l=>{let d=l.urls[u];if(d==null)throw new Error(`Expected environment ${l.id} to contain url for ${u}`);return{id:cm.FernRegistry.EnvironmentId(u),baseUrl:d}})).filter((u,l,d)=>l===d.findIndex(s=>s.id===u.id&&s.baseUrl===u.baseUrl));if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let u=a.urls[i];if(u==null)throw new Error(`Expected environment ${a.id} to contain url for ${i}`);return{id:cm.FernRegistry.EnvironmentId(a.id),baseUrl:u}});default:jo(r)}}function b4E({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:cm.FernRegistry.EnvironmentId(n.id),baseUrl:g4E(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:cm.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:jo(r)}}function g4E(e,t){return e.replace(/^[^:]+/,t)}function O4E(e){return Gs.http.HttpMethod._visit(e,{get:()=>cm.FernRegistry.HttpMethod.Get,post:()=>cm.FernRegistry.HttpMethod.Post,put:()=>cm.FernRegistry.HttpMethod.Put,patch:()=>cm.FernRegistry.HttpMethod.Patch,delete:()=>cm.FernRegistry.HttpMethod.Delete,head:()=>cm.FernRegistry.HttpMethod.Get,_other:()=>{throw new Error("Unknown http method: "+e)}})}function d9n(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:cm.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function m4E(e){let t=Gs.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??_M.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>cm.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:cm.FernRegistry.PropertyKey(i.name.wireValue),valueType:jE(i.valueType),availability:e4(i.availability),propertyAccess:void 0})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??_M.APPLICATION_JSON,shape:{type:"reference",value:jE(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:u=>({type:"file",key:cm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:cm.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:cm.FernRegistry.PropertyKey(n.name.wireValue),valueType:jE(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:e4(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(yv)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function P4E(e){if(e.body==null)return;let t,r=Gs.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:jE(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:jE(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:jE(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function j4E(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:jE(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:n.examples.map(a=>({name:a.name?.originalName,responseBody:{type:"json",value:a.jsonExample},description:a.docs}))})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:cm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0,propertyAccess:void 0}];n.type!=null&&a.push({key:cm.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:jE(n.type),description:n.docs,availability:void 0,propertyAccess:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function Pz_({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:i}){if(r==null)return;let n=r.response?.body!=null?r.response.body.value:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:r.request?.headers??{},requestBody:r.request?.requestBody,requestBodyV3:i.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:a=>{if(r.request==null)return;let u={};if(Gj(r.request.requestBody)){let l=r.request.requestBody;for(let d of a.properties)d._visit({file:s=>{let o=l[s.key.wireValue];if(s.type==="file")u[s.key.wireValue]={type:"filename",value:typeof o=="string"?o:"<file1>"};else if(s.type==="fileArray"){let c=(Array.isArray(o)?o:[o]).filter(b=>typeof b=="string");u[s.key.wireValue]={type:"filenames",value:c}}},bodyProperty:s=>{if(s.style==="exploded"){let o=l[s.name.wireValue];u[s.name.wireValue]={type:"exploded",value:Array.isArray(o)?o:[o]}}else u[s.name.wireValue]={type:"json",value:l[s.name.wireValue]}},_other:Qze})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??i.response?.statusCode??200,responseBody:n??void 0,responseBodyV3:n!=null?r.response?.body?._visit({json:a=>({type:"json",value:a}),stream:a=>({type:"stream",value:a.map(u=>({type:"json",value:u}))}),error:()=>{},_other:()=>{throw new Error("Unknown ExampleResponseBody: "+r.response?.body?.type)}}):void 0,codeSamples:r.codeSamples?.map(a=>({name:a.name,description:a.docs??void 0,install:void 0,language:a.language,code:a.code})).filter(yv)}}function Ujc({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(l=>{let d=l.valueType.type==="container"&&l.valueType.container.type==="literal"?l.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):void 0;if(d!=null)return{name:l.name,value:{jsonExample:d,shape:Gs.ExampleTypeReferenceShape.primitive(Gs.ExamplePrimitive.string({original:d}))}}}).filter(yv),a=e?.example??t?.example;if(a==null)return;let{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((l,d)=>(l[cm.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,l),{}),queryParameters:a.queryParameters.reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),requestBody:a.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,reference:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,fileUpload:l=>{if(a.request==null)return;let d={};if(Gj(a.request.jsonExample)){let s=a.request.jsonExample;for(let o of l.properties)o._visit({file:c=>{let b=s[c.key.wireValue];if(c.type==="file")d[c.key.wireValue]={type:"filename",value:typeof b=="string"?b:"<file1>"};else if(c.type==="fileArray"){let g=(Array.isArray(b)?b:[b]).filter(O=>typeof O=="string");d[c.key.wireValue]={type:"filenames",value:g}}},bodyProperty:c=>{if(c.style==="exploded"){let b=s[c.name.wireValue];d[c.name.wireValue]={type:"exploded",value:Array.isArray(b)?b:[b]}}else d[c.name.wireValue]={type:"json",value:s[c.name.wireValue]}},_other:Qze})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Gs.http.ExampleResponse._visit(a.response,{ok:l=>l._visit({body:d=>d!=null?200:204,stream:d=>d.length>0?200:204,sse:d=>d.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:({error:l})=>{let d=i.errors[l.errorId];if(d==null)throw new Error("Cannot find error "+l.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:l=>l._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:l=>l.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:l=>l._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(s=>s.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:s,data:o})=>({event:s,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:l=>l.body!=null?{type:"json",value:l.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(l=>wEe._visit(l,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter(yv)}}function w4E(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>cm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:cm.FernRegistry.PropertyKey(t.name.wireValue),valueType:jE(t.valueType),availability:e4(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:jE(e.payloadType)},description:e.docs};default:jo(e)}}function S4E(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>cm.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:cm.FernRegistry.PropertyKey(t.name.wireValue),valueType:jE(t.valueType),availability:e4(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:jE(e.bodyType)};default:jo(e)}}function ZZ({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:Vjc(e.rootPackage,e),auth:gz_(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:e4(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:jE(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[Aeu.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:mz_(a.shape),availability:e4(a.availability),displayName:a.name.displayName};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[Aeu.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:Aeu.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...Vjc(a,e)}}return i}var Wjc=ui(PEe(),1);async function Hjc({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=hR({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new _R(r,t)}),d=IWi({token:i.value}),s=ZZ({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await d.api.v1.register.registerApiDefinition({orgId:Wjc.FernRegistry.OrgId(e),apiId:Wjc.FernRegistry.ApiId(l.apiName.originalName),definition:s});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:l};switch(o.error.error){case"UnauthorizedError":case"UserNotInOrgError":return r.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return r.failAndThrow("Failed to register API",o.error)}}var D4E=new tKi({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function eRa(e,t,r){return wxa(mxa(ZZ({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r}),Y6.ApiDefinitionId(t),D4E))}var uh={};Po(uh,{AlgoliaSearchIndex:()=>jz_,ApiDefinitionId:()=>Hz_,ApiId:()=>Jz_,Availability:()=>cx_,DocsConfigId:()=>Kz_,EndpointId:()=>Xz_,EndpointPathLiteral:()=>ux_,EnvironmentId:()=>Yz_,FileId:()=>rx_,HttpMethod:()=>sx_,IndexSegmentId:()=>wz_,JqString:()=>nx_,OrgId:()=>Gz_,PageId:()=>tx_,PayloadLocation:()=>xx_,PropertyKey:()=>ax_,PullRequestState:()=>Tx_,RoleId:()=>ox_,TokenId:()=>Qz_,TypeId:()=>ex_,Url:()=>ix_,VersionId:()=>$z_,WebSocketId:()=>Zz_,WebhookId:()=>kz_,algolia:()=>$jc,api:()=>twc,commons:()=>rwc,diff:()=>lx_,docs:()=>fwc,generators:()=>pwc,git:()=>_wc,navigation:()=>vwc,sdks:()=>gwc,snippets:()=>Ix_,snippetsFactory:()=>zx_,templates:()=>Owc,tokens:()=>Rx_});var $jc={};Po($jc,{AlgoliaSearchIndex:()=>jz_,IndexSegmentId:()=>wz_});function jz_(e){return e}function wz_(e){return e}var twc={};Po(twc,{latest:()=>Jjc,v1:()=>ewc});var Jjc={};Po(Jjc,{AuthSchemeId:()=>Sz_,WebhookHttpMethod:()=>Az_,auth:()=>Gjc,commons:()=>Dz_,endpoint:()=>Ez_,type_:()=>Mz_,webhook:()=>Qjc,websocket:()=>qz_});var Gjc={};Po(Gjc,{AuthSchemeId:()=>Sz_});function Sz_(e){return e}var Dz_={};var Ez_={};var Mz_={};var Qjc={};Po(Qjc,{WebhookHttpMethod:()=>Az_});var Az_={Get:"GET",Post:"POST"};var qz_={};var ewc={};Po(ewc,{SubpackageId:()=>Lz_,WebSocketMessageId:()=>Uz_,WebSocketMessageOrigin:()=>Vz_,WebhookHttpMethod:()=>Wz_,commons:()=>kjc,db:()=>Kjc,read:()=>Xjc,register:()=>Zjc});var Kjc={};Po(Kjc,{endpoint:()=>Tz_});var Tz_={};var Xjc={};Po(Xjc,{SupportedLanguage:()=>Cz_,endpoint:()=>Yjc,type_:()=>Bz_,webhook:()=>Iz_,websocket:()=>zz_});var Yjc={};Po(Yjc,{SupportedLanguage:()=>Cz_});var Cz_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var Bz_={};var Iz_={};var zz_={};var Zjc={};Po(Zjc,{SourceId:()=>E4E,endpoint:()=>xz_,type_:()=>Rz_,webhook:()=>Nz_,websocket:()=>Fz_});var xz_={};var Rz_={};var Nz_={};var Fz_={};function E4E(e){return e}var kjc={};Po(kjc,{SubpackageId:()=>Lz_,WebSocketMessageId:()=>Uz_,WebSocketMessageOrigin:()=>Vz_,WebhookHttpMethod:()=>Wz_});function Lz_(e){return e}function Uz_(e){return e}var Vz_={Client:"client",Server:"server"};var Wz_={Get:"GET",Post:"POST"};var rwc={};Po(rwc,{ApiDefinitionId:()=>Hz_,ApiId:()=>Jz_,Availability:()=>cx_,DocsConfigId:()=>Kz_,EndpointId:()=>Xz_,EndpointPathLiteral:()=>ux_,EnvironmentId:()=>Yz_,FileId:()=>rx_,HttpMethod:()=>sx_,JqString:()=>nx_,OrgId:()=>Gz_,PageId:()=>tx_,PropertyKey:()=>ax_,RoleId:()=>ox_,TokenId:()=>Qz_,TypeId:()=>ex_,Url:()=>ix_,VersionId:()=>$z_,WebSocketId:()=>Zz_,WebhookId:()=>kz_});function Hz_(e){return e}function $z_(e){return e}function Gz_(e){return e}function Qz_(e){return e}function Jz_(e){return e}function Kz_(e){return e}function Yz_(e){return e}function Xz_(e){return e}function Zz_(e){return e}function kz_(e){return e}function ex_(e){return e}function tx_(e){return e}function rx_(e){return e}function ix_(e){return e}function nx_(e){return e}function ax_(e){return e}function ox_(e){return e}function ux_(e){return e}var sx_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var cx_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var lx_={};var fwc={};Po(fwc,{latest:()=>awc,v1:()=>cwc,v2:()=>lwc});var awc={};Po(awc,{Layout:()=>dx_,MdxEngine:()=>M4E,TwitterCardSetting:()=>px_,commons:()=>fx_,frontmatter:()=>iwc,seo:()=>nwc});var M4E={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var fx_={};var iwc={};Po(iwc,{Layout:()=>dx_});var dx_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var nwc={};Po(nwc,{TwitterCardSetting:()=>px_});var px_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var cwc={};Po(cwc,{commons:()=>swc,db:()=>_x_,read:()=>hx_,write:()=>owc});var _x_={};var hx_={};var owc={};Po(owc,{DocsRegistrationId:()=>q4E,FilePath:()=>A4E});function A4E(e){return e}function q4E(e){return e}var swc={};Po(swc,{ContentAlignment:()=>gx_,FontDisplay:()=>wx_,FontStyle:()=>jx_,HeaderPosition:()=>Ox_,JsScriptStrategy:()=>Px_,ProgrammingLanguage:()=>yx_,SearchbarPlacement:()=>vx_,TabsPlacement:()=>bx_,TwitterCardSetting:()=>mx_,commons:()=>uwc});var uwc={};Po(uwc,{ContentAlignment:()=>gx_,FontDisplay:()=>wx_,FontStyle:()=>jx_,HeaderPosition:()=>Ox_,JsScriptStrategy:()=>Px_,ProgrammingLanguage:()=>yx_,SearchbarPlacement:()=>vx_,TabsPlacement:()=>bx_,TwitterCardSetting:()=>mx_});var yx_={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var vx_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var bx_={Header:"HEADER",Sidebar:"SIDEBAR"};var gx_={Center:"CENTER",Left:"LEFT"};var Ox_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var mx_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Px_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var jx_={Normal:"normal",Italic:"italic"};var wx_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var lwc={};Po(lwc,{read:()=>Sx_,write:()=>Dx_});var Sx_={};var Dx_={};var pwc={};Po(pwc,{ChangelogEntryType:()=>Mx_,GeneratorId:()=>T4E,GeneratorLanguage:()=>C4E,ReleaseType:()=>Ax_,cli:()=>Ex_,commons:()=>dwc,versions:()=>qx_});var Ex_={};var dwc={};Po(dwc,{ChangelogEntryType:()=>Mx_,ReleaseType:()=>Ax_});var Mx_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var Ax_={Ga:"GA",Rc:"RC"};var qx_={};function T4E(e){return e}var C4E={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var _wc={};Po(_wc,{PullRequestState:()=>Tx_});var Tx_={Open:"open",Closed:"closed",Merged:"merged"};var vwc={};Po(vwc,{latest:()=>hwc,v1:()=>ywc});var hwc={};Po(hwc,{NodeId:()=>z4E,ProductId:()=>x4E,Slug:()=>B4E,TabId:()=>I4E});function B4E(e){return e}function I4E(e){return e}function z4E(e){return e}function x4E(e){return e}var ywc={};Po(ywc,{NavigationV1Availability:()=>U4E,NodeId:()=>F4E,ProductId:()=>L4E,Slug:()=>R4E,TabId:()=>N4E});function R4E(e){return e}function N4E(e){return e}function F4E(e){return e}function L4E(e){return e}var U4E={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var gwc={};Po(gwc,{Language:()=>Cx_,VersionBump:()=>Bx_,versions:()=>bwc});var bwc={};Po(bwc,{Language:()=>Cx_,VersionBump:()=>Bx_});var Cx_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var Bx_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var Ix_={};var zx_={};var Owc={};Po(Owc,{PayloadLocation:()=>xx_});var xx_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var Rx_={};var p9n=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Gd(e){return e!=null}var Fx_=ui(wCn(),1);var Nx_=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function qir(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,Fx_.default)(e,{special:Nx_}).replace(/V\s(\d)/g,"V$1")}function qeu({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let u=[...n,a],l=uh.api.v1.SubpackageId(u.join("."));r[l]={id:l,name:a,displayName:qir(a)},n.push(a)})}),r}var Teu=class{errors=new p9n},_9n=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function Lx_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var Ceu=class extends Teu{},n_=class extends _9n{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((u,l)=>u===this.accessPath[this.accessPath.length-a.length+l])||this.accessPath.push(...a)}r.logger.debug(`Processing ${Lx_(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},z3=class extends n_{},Qae=class extends z3{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var Ux_="x-fern-base-path",Vx_="x-fern-availability",Beu="x-fern-sdk-group-name",Wx_="x-fern-global-headers",Hx_="x-fern-sdk-method-name";var $x_="x-fern-webhook",Gx_="x-fern-access-token-locator",Qx_="x-fern-basic",Jx_="x-fern-username-variable-name",Kx_="x-fern-password-variable-name",Yx_="x-fern-bearer",Xx_="x-fern-token-variable-name",Zx_="x-fern-header",kx_="x-fern-header-variable-name",eR_="x-fern-server-name",tR_="x-fern-examples";var Ieu=class extends n_{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[eR_]}convert(){if(this.serverName!=null)return this.serverName}};var zeu=class extends n_{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new Ieu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:uh.EnvironmentId(t),baseUrl:this.url}}};function Tir(e,t,r,i){let n=e??[],a=new Set(n.map(l=>l.url)),u=(t??[]).filter(l=>!a.has(l.url)).map((l,d)=>new zeu({input:l,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...u]}function LS(e){return typeof e=="object"&&Gd(e)&&"$ref"in e&&typeof e.$ref=="string"}function iH(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(LS(n)&&(n=iH(n,t,r)),n)}function xeu(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return LS(r)?iH(r,t,void 0):r}var pR_=ui(lz());var Reu=class extends n_{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[Qx_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var Neu=class extends n_{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[Kx_]}convert(){return this.passwordVariableName}};var Feu=class extends n_{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[Jx_]}convert(){return this.usernameVariableName}};var Leu=class extends n_{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[Yx_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var Ueu=class extends n_{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[Xx_]}convert(){return this.tokenVariableName}};function rR_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var iR_="x-bearer-format",nR_="x-code-samples",aR_="x-codeSamples";var Veu=class extends n_{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[iR_]}convert(){return this.bearerFormat}};var Weu=class extends n_{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[Zx_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var Heu=class extends n_{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[kx_]}convert(){return this.headerVariableName}};function oR_(e){return e.type==="apiKey"}var h9n=class extends n_{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){oR_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new Weu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new Heu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new Veu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function uR_(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function sR_(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function cR_(e){let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",u=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let l=e[i];a?l==="\\"&&i+1<r?(i++,n+=e[i]):l===a?a="":n+=l:u?l==='"'||l==="'"?a=l:l==="]"?(u=!1,t.push(n),n=""):n+=l:l==="["?(u=!0,n&&(t.push(n),n="")):l==="."?n&&(t.push(n),n=""):n+=l,i++}return n&&t.push(n),t}function mwc(e,t,r){if(e==null)return r;switch(typeof t){case"string":{let i=e[t];return i===void 0?uR_(t)?mwc(e,cR_(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=sR_(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return V4E(e,t,r);Object.is(t?.valueOf(),-0)?t="-0":t=String(t);let i=e[t];return i===void 0?r:i}}}function V4E(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null)return r;i=i[t[n]]}return i===void 0?r:i}function lR_(e){return function(t){return mwc(t,e)}}function Pwc(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Pwc).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function $eu(e,t){switch(t=t??yT_,typeof t){case"string":case"symbol":case"number":case"object":return nL(e,lR_(t));case"function":return nL(e,t)}}function fR_(e){return typeof e!="string"&&(e=Pwc(e)),e.replace(/['\u2019]/g,"")}function gHt(e){return GD_(fR_(e))}function yA(e){if(e!=null)return Array.isArray(e)?e:[e]}function Geu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:u}){if(t==null)return;let l=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&l==null))return`${W4E(u)}${H4E(e)}.${$4E(i,n,a,l)}`}function W4E(e){return e?"webhook_":"endpoint_"}function H4E(e){return e!=null?yA(e)?.map(t=>gHt(t)).join("/"):""}function $4E(e,t,r,i){return e||t||gHt(r??"")||gHt(i??"")}function dR_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var Qeu=class extends n_{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[Gx_],this.accessTokenLocator!=null&&(dR_(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var Jeu=class extends n_{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new h9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new Qeu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=Geu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:uh.EndpointId(r),accessTokenLocator:uh.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var y9n=class extends n_{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new Reu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new Feu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new Neu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new Leu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new Ueu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{rR_(this.input)?(this.authScheme="header",this.headerAuthNode=new h9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new Jeu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new pR_.UnreachableCaseError(this.authScheme);return}}};var v9n=class extends n_{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=xeu(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new y9n({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(Gd))}};var Keu=class extends n_{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[Ux_],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function _R_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function hR_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function b9n(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>yA(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!_R_(n))&&(u=hR_(u,u.type==="enum"?u.default:void 0)),{key:uh.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(Gd)).filter(Gd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function Yeu(e,t){return LS(e)?iH(e,t,void 0):e}function mAi(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function yR_(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function vR_(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var bR_=ui(lz());var jwc=["decimal","decimal128","double-int","double","float","sf-decimal"],wwc=["int16","int32","int64","int8","sf-integer","uint8"],Swc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],Dwc=["beta","pre-release","in-development","generally-available","deprecated"];function x3(e,t){return LS(e)?iH(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var PFe=class extends n_{availability;constructor(t){super(t),this.safeParse()}parse(){if(x3(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[Vx_];r!=null&&(Dwc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${Dwc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return uh.Availability.Beta;case"in-development":return uh.Availability.InDevelopment;case"generally-available":return uh.Availability.GenerallyAvailable;case"deprecated":return uh.Availability.Deprecated;case void 0:return;default:new bR_.UnreachableCaseError(this.availability);return}}};var Zeu=ui(lz());function gR_(e){return typeof e=="object"&&e!=null&&"language"in e}function OR_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function mR_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function PR_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function Xeu(e){return typeof e=="object"&&e!=null&&"event"in e}function Ewc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(Xeu)}function PAi(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function jR_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var keu=class extends n_{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[tR_]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let u=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return PAi(u)?[n,{type:"filenameWithData",filename:u.filename,data:uh.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(l=>PAi(l)))return[n,{type:"filenamesWithData",value:u.map(l=>({filename:l.filename,data:uh.FileId(l.data)}))}];if(u.every(l=>typeof l=="string"))return[n,{type:"filenames",value:u}]}return}case"property":return[n,{type:"json",value:u}];case void 0:return;default:new Zeu.UnreachableCaseError(a.multipartType);return}}).filter(Gd))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=jR_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new Zeu.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{mR_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{Ewc(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!Ewc(r.response)&&PR_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new Zeu.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{gR_(c)?c.language!=null&&(l[c.language]??=[],l[c.language]?.push({name:c.name,language:c.language,install:c.install,code:c.code,generated:!1,description:c.docs})):OR_(c)&&c.sdk!=null&&(l[c.sdk]??=[],l[c.sdk]?.push({name:c.name,language:c.sdk,install:void 0,code:c.code,generated:!1,description:c.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([c,b])=>[uh.PropertyKey(c),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([c,b])=>[uh.PropertyKey(c),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([c,b])=>[uh.PropertyKey(c),b]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(o).length>0?o:void 0,requestBody:a,responseBody:u,snippets:l}}))}};var tRa=class extends n_{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[Beu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>uh.api.v1.SubpackageId(gHt(r)))}};var etu=class extends n_{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[Hx_]}convert(){return this.sdkMethodName}};var ttu=class extends n_{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[$x_]}convert(){return this.isWebhook}};var rtu=class extends n_{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[nR_]??[],...this.input[aR_]??[]],this.codeSamples.forEach(t=>{[...Object.values(uh.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var dKi=ui(lz());function Mwc(e,t){return LS(e)?iH(e,t,void 0):e}function wR_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var cL="",Cir=class extends n_{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(PAi(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>PAi(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new dKi.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=Mwc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=Mwc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new dKi.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(Xeu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new dKi.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return PAi(n)?[r,{type:"filenameWithData",filename:n.filename,data:uh.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>PAi(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:uh.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new dKi.UnreachableCaseError(i.multipartType);return}}).filter(Gd))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new dKi.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new dKi.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,l])=>[u,l.example({includeOptionals:!1,override:u})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Gd));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Gd));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:wR_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?qir(this.name):this.summary!=null?qir(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function SR_(e,t){return LS(e)?iH(e,t,void 0):e}var NR_=ui(lz());var DR_="#/components/schemas/";function g9n(e){if(e.$ref.startsWith(DR_))return e.$ref.replace(DR_,"")}function dpi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function jAi(e){return typeof e.type=="string"&&e.type==="array"}function ER_(e){return e.type==="boolean"}function MR_(e){return e.type==="integer"}function wAi(e){return!Array.isArray(e.type)&&!jAi(e)}function AR_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||wAi(t)||jAi(t))}function qR_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function TR_(e){return e.type==="null"}function CR_(e){return e.type==="number"}function Awc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function BR_(e){return e.type==="string"}var itu=class extends Qae{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new Gq({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return yA(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var ntu=class extends z3{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new PFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var atu=class extends Qae{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new Gq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Gd)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>yA(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(Gd).reduce((n,a)=>n.flatMap(u=>a.length>0?a.map(l=>[...u,l]):[[...u]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(dpi).filter(Gd):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function otu(e){return e!=null&&e.length>0?e:[void 0]}var O9n=class extends Qae{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new Gq({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new Gq({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(LS(t))return g9n(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new Gq({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Gd))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return b9n(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:yA(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(Gd)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>otu(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>uh.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=x3(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new Gq({input:u,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var utu=class extends Qae{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>x3(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>x3(t,this.context.document)?.type!=="null"?new Gq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Gd);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=x3({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new Gq({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(Gd);return this.isNullable&&n!=null?n.map(dpi).filter(Gd):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:uh.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>yA(a.convert())?.map(l=>{if(!(l==null||l.type!=="object"))return{discriminantValue:n,displayName:a.name??qir(n),availability:a.availability?.convert(),description:a.description,...l}}).filter(Gd)).filter(Gd)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>yA(n.convert())?.map(u=>{if(u==null)return;t+=1;let l=u.type==="object"?qir(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?qir(u.value.id):l),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(Gd)).filter(Gd)}:void 0,i=this.isNullable?dpi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var stu=class extends z3{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var SAi=class extends z3{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(LS(r)){let n=x3(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(Gd),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var IR_=ui(lz());function G4E(e){return wwc.includes(e)}var ctu=class extends z3{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(G4E(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${wwc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new IR_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var ltu=class extends z3{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return dpi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var zR_=ui(lz());function Q4E(e){return jwc.includes(e)}var ftu=class extends z3{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(Q4E(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${jwc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new zR_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var xR_=ui(lz());function J4E(e){return Swc.includes(e)}var dtu=class extends z3{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new xR_.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(J4E(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Swc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new SAi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var RR_=ui(lz());var ptu=class extends z3{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,RR_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var pKi=class extends Qae{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=g9n(this.input);let t=x3(this.input,this.context.document);t?.enum!=null&&wAi(t)&&(this.maybeEnumConverterNode=new SAi({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:uh.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=x3(this.input,this.context.document);if(r!=null)return new Gq({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var Gq=class e extends Qae{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new PFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),wAi(this.input)&&qR_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),LS(this.input)){let t=g9n(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new pKi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new ntu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(AR_(this.input))this.typeShapeNode=new atu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(wAi(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new utu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Awc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new O9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(wAi(this.input)&&this.input.enum!=null)this.typeShapeNode=new SAi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":Awc(this.input)&&(this.typeShapeNode=new O9n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":jAi(this.input)&&(this.typeShapeNode=new itu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":ER_(this.input)&&(this.typeShapeNode=new stu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":MR_(this.input)&&(this.typeShapeNode=new ctu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":CR_(this.input)&&(this.typeShapeNode=new ftu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":BR_(this.input)&&(this.typeShapeNode=new dtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":TR_(this.input)&&(this.typeShapeNode=new ltu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new NR_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new O9n({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new ptu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!LS(this.input)&&(!jAi(this.input)&&this.input==null||jAi(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=yA(t)?.map(i=>this.nullable?dpi(i):i).filter(Gd);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function DAi(e){if(e!=null)return b9n(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Gd))}var Bir=class extends z3{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;LS(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new PFe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new Gq({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=SR_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function FR_(e,t){return LS(e)?iH(e,t,void 0):e}var qwc=ui(lz());function _tu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[uh.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var LR_=ui(RBs(),1),m9n=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,u){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=u}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=LR_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function K4E(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var P9n=class extends n_{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new Gq({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),K4E(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(LS(r)?n=xeu(r.$ref,this.context.document):n=r,n!=null)return[t,new y9n({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Gd)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[uh.api.latest.AuthSchemeId(t),i]}).filter(Gd)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=yA(r.convert());return n==null?[t,void 0]:[uh.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Gd(r))):void 0}}};var htu=class extends Gq{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=x3(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${LS(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=x3(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var ytu=class extends n_{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=x3(this.input.schema,this.context.document);this.availability=new PFe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=LS(this.input.schema)?new pKi({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=m9n.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new Gq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,u])=>{if(u!=null)return[a,new htu({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Gd))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[cL]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[cL]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:yA(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=gHt([this.method,this.path,this.contentType,"request"].join("_"));return _tu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uh.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new qwc.UnreachableCaseError(n);return}}).filter(Gd)}convert(){if(this.schema instanceof pKi)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:uh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:uh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=yA(n.convert()),u=n.multipartType;return a?.map(l=>({type:u,key:uh.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:l,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new qwc.UnreachableCaseError(n.multipartType),[]}}).filter(Gd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var vtu=class extends n_{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=FR_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new ytu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>yA(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Gd)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>yA(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Gd)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var UR_={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function VR_(e,t){if(LS(e)){let r=iH(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var btu=ui(lz());var WR_="application/json";var HR_="application/octet-stream";function $R_(e,t){return e===t||t===cL||e===cL}var rRa=class extends n_{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,l,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=l,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[l,d]of Object.entries(r))for(let s of d)$R_(l,a)&&(i.add(l),this.examples?.push(new Cir({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,mAi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[u,l]of r){if(a===i){let[d,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...l.map(c=>new Cir({input:{requestExample:o,responseExample:c},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,mAi(s,u),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,u]=r[r.length-1]??[void 0,void 0],[l,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new Cir({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,mAi(d,a),{requestBody:l,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,u]=t[t.length-1]??[void 0,void 0,void 0];for(let[l,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new Cir({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,mAi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[cL];if(a!=null)for(let u of a)this.examples?.push(new Cir({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,mAi(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let l=m9n.parse(t);if(l?.isJSON()||l?.isEventStream())this.contentType=WR_,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new Gq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(l?.isOctetStream())this.contentType=HR_,this.contentSubtype=x3(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new Gq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=$eu(this.input.examples,l=>[l])),this.input.example!=null&&Object.keys(r).length===0&&(r[cL]??=[],r[cL]=[{value:this.input.example}]);let i=x3(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=$eu(i.examples,l=>[l])),i.example!=null&&Object.keys(r).length===0&&(r[cL]??=[],r[cL]?.push({value:i.example}))),Object.keys(r).length===0){let l=this.schema?.example({includeOptionals:!0,override:void 0});r[cL]??=[],r[cL]?.push(l!=null?{value:l}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let l of this.requests)a.push(...Object.entries(l.examples??{}).filter(([d])=>!n.has(d)&&d!==cL).map(([d,s])=>[l,d,s]));let u=Object.entries(r).filter(([l,d])=>!n.has(l)&&Gd(d)&&l!==cL);Object.keys(r).every(l=>l===cL)||this.matchExamplesByIndex(a,u),!n.has(cL)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return yA(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new btu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return yA(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=gHt([this.method,this.path,this.statusCode,"response"].join("_"));return _tu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:uh.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new btu.UnreachableCaseError(i);return}}).filter(Gd)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new btu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var iRa=class extends n_{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,u){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=u,this.safeParse()}parse(t){this.description=this.input.description;let r=VR_(this.input,this.context.document);if(r==null){this.context.errors.error({message:LS(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new Bir({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new rRa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new rRa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(Gd)}};var gtu=class extends n_{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new iRa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new iRa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return otu(DAi(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(u=>(u.examples??[]).map(l=>l.convert()).filter(Gd))})))}).filter(Gd)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=yA(n?.convert());if(n!=null)return a?.map(u=>({statusCode:parseInt(t),shape:u,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??UR_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(l=>{let d=l.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(Gd)})).filter(Gd)})).filter(Gd)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var EAi=class extends n_{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new Cir({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,mAi(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new PFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=Tir(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new ttu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(LS(i)){let a=Yeu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new Bir({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new Bir({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new Bir({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new rtu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new vtu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new gtu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,u])=>{this.pushEmptyResponseExample(u,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new v9n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new tRa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new tRa({input:{[Beu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new etu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>Geu({namespace:yA(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(Gd),this.xFernExamplesNode=new keu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(Gd)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:uh.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(o=>o.convert()).filter(Gd),n=vR_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:yR_(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,c)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:uh.WebhookId(o),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[c]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(b=>b.value.toString())??[],queryParameters:DAi(this.queryParameters)?.flat(),headers:DAi(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Gd)}}).filter(Gd);let a=this.servers?.map(o=>o.convert()).filter(Gd),u=this.convertPathToPathParts();if(u==null)return;let l,d=this.auth?.convert();d!=null&&(l=Object.keys(d));let s=t?.flatMap(o=>o.headers).filter(Gd);return this.endpointIds.map((o,c)=>({id:uh.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[c]?.convert()?.map(b=>uh.api.v1.SubpackageId(b)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:l?.map(b=>uh.api.latest.AuthSchemeId(b)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:DAi(this.pathParameters)?.flat(),queryParameters:DAi(this.queryParameters)?.flat(),requestHeaders:DAi(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(b=>b.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var j9n=class extends n_{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=Tir(t,this.input.servers,this.context,this.accessPath),u=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new EAi({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:u,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new EAi({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:u,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new EAi({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:u,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new EAi({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:u,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new EAi({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:u,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(Gd)}};function Otu(e){return"payloads"in e}var mtu=class extends n_{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new j9n({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:Tir(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Gd)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{Otu(a)?r[uh.WebhookId(a.id)]=a:t[uh.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var Ptu=class extends n_{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[Wx_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||Yeu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new Bir({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return b9n(this.globalHeaders,this.requiredProperties)?.flat()}};function GR_(e,t){if(LS(e)){let r=iH(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var jtu=class extends n_{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let u=GR_(a,this.context.document);if(u!=null)return new j9n({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Gd)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{Otu(i)&&(t[uh.WebhookId(i.id)]=i)}),t),{})}};var wtu=class extends n_{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=Tir(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new v9n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new Keu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new mtu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new jtu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new P9n({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new Ptu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=lae(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=qeu({endpoints:i,webhookEndpoints:n}),{types:u,auths:l}=this.components?.convert()??{};return{id:uh.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...u,...this.context.generatedTypes},subpackages:a,auths:{...l,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var w9n=class extends _9n{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,this.pathId&&this.pathId!==this.accessPath[this.accessPath.length-1]&&(this.accessPath.push(this.pathId),r.logger.debug(`Processing #/${this.accessPath.join("/")}`))}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}};function jFe(e){return typeof e=="object"&&Gd(e)&&"$ref"in e&&typeof e.$ref=="string"}function OHt(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(jFe(n)&&(n=OHt(n,t,r)),n)}function QR_(e,t){return jFe(e)?OHt(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var XR_=ui(lz());function ppi(e){if(typeof e=="boolean")return e;if(e.enum!=null&&e.enum.length>0)return e.enum[0];if(e.const!=null)return e.const;if(e.examples!=null&&e.examples.length>0)return e.examples[0];if(e.type==="object"){let t={};if(e.properties!=null)for(let[r,i]of Object.entries(e.properties))t[r]=ppi(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>ppi(t)):[ppi(e.items)];if(e.type==="string")return e.default??"string";if(e.type==="number"||e.type==="integer")return e.default??0;if(e.type==="boolean")return e.default??!1;if(e.type==="null")return null;if(e.oneOf?.[0]!=null)return ppi(e.oneOf[0]);if(e.anyOf?.[0]!=null)return ppi(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,ppi(r));return t}}function nRa(e,t){return jFe(e)?OHt(e,t,{name:"",schema:{type:"object"}}):e}function JR_(e,t){return jFe(e)?OHt(e,t,void 0):e}function KR_(e,t){return jFe(e)?OHt(e,t,void 0):e}function YR_(e,t){return jFe(e)?OHt(e,t,void 0):e}var Y4E={key:uh.PropertyKey("apiKey"),description:void 0,availability:void 0,valueShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}},Stu=class extends w9n{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?nRa(this.method.result,this.context.openrpc):void 0,r=t?new Gq({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result",seenSchemas:new Set,nullable:void 0,schemaName:"Result"}).convert():void 0,n=this.method.params?.map(l=>nRa(l,this.context.openrpc)).filter(Gd)?.map(l=>{let d=new Gq({input:l.schema,context:this.context,accessPath:this.accessPath,pathId:["params",l.name],seenSchemas:new Set,nullable:void 0,schemaName:l.name}).convert();if(!d)return;let s=Array.isArray(d)?d[0]:d;if(s)return{key:uh.PropertyKey(l.name),valueShape:l.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:l.description,availability:void 0}}).filter(Gd),a=n.length>0?{contentType:"application/json",body:{type:"object",extends:[],properties:n,extraProperties:void 0},description:void 0}:void 0,u=this.method.examples?.map(l=>{let d=KR_(l,this.context.openrpc);if(d)return{name:d.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:d.params.length>0?{type:"json",value:Object.fromEntries(d.params.map(s=>{let o=JR_(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(Gd))}:void 0,responseStatusCode:200,responseBody:d.result?{type:"json",value:d.result}:void 0}}).filter(Gd)??[];if(u.length<=0){let l=ppi({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=nRa(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:l},responseStatusCode:200,responseBody:{type:"json",value:ppi(nRa(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}return{protocol:{type:"openrpc",methodName:this.input.name},id:uh.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:uh.PropertyKey("apiKey")}],auth:void 0,pathParameters:[Y4E],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(Gd):[],errors:[],examples:u,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(l=>l.convert()).filter(Gd),availability:this.method.deprecated?"Deprecated":void 0,requestHeaders:[],responseHeaders:[],snippetTemplates:void 0,namespace:this.getNamespace()}}catch{this.context.errors.error({message:"Failed to convert method",path:this.accessPath});return}}getNamespace(){if(this.method.tags?.[0]==null)return;let t=YR_(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[uh.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=yA(t)?.map(a=>{let u=a.type;switch(u){case"alias":return a;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":return;case"object":return a;default:new XR_.UnreachableCaseError(u);return}}).filter(Gd)[0];if(n)return{statusCode:200,body:n,description:r}}};var aRa=class extends w9n{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=Tir(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=QR_(t,this.context.openrpc);r!=null&&this.methods.push(new Stu({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new P9n({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=lae(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(Gd),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=qeu({endpoints:n});return{id:uh.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var oRa=class extends Ceu{openrpc;logger;generatedTypes;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger,this.generatedTypes={}}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function uRa(e,t){if(e instanceof nir){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof fR))return;let r=new eHt(e.absoluteFilePath),i=await sFe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let u of n){if(u.type!=="openapi")continue;let l={document:u.value,logger:t.logger,errors:new p9n,generatedTypes:{}},d=new wtu({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=kBs(a,d.convert())}return a}var ZR_=require("fs/promises");async function kR_(e,t){let r=await(0,ZR_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new oRa({openrpc:i,logger:t.logger});return new aRa({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function X4E(e){return e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function Z4E(e){return/^(https?:)?\/\//.test(e)}async function k4E({pathToImage:e,absolutePathToFernFolder:t}){if(e==null||Z4E(e))return;let r=Gv(t,Na.of(e));if(await mf(r))return r}async function S9n({iconPath:e,filepaths:t,docsWorkspace:r}){if(X4E(e)){let i=await k4E({pathToImage:e,absolutePathToFernFolder:r.absoluteFilePath});i&&t.add(i)}}async function eN_({parsedDocsConfig:e,docsWorkspace:t}){let r=new Set;return e.logo?.dark!=null&&r.add(e.logo.dark),e.logo?.light!=null&&r.add(e.logo.light),e.favicon!=null&&r.add(e.favicon),e.backgroundImage?.dark!=null&&r.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&r.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&r.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&r.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&r.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(n=>{r.add(n.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(n=>{n.image!=null&&r.add(n.image)}),(await Twc({navigation:e.navigation,docsWorkspace:t})).forEach(n=>{r.add(n)}),e.js!=null&&e.js.files.forEach(n=>{r.add(n.absolutePath)}),r}async function Twc({navigation:e,docsWorkspace:t}){let r=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(i=>sRa({item:i,filepaths:r,docsWorkspace:t})));break;case"tabbed":await Promise.all(e.items.map(async i=>{i.icon!=null&&await S9n({iconPath:i.icon,filepaths:r,docsWorkspace:t}),i.child.type==="layout"&&i.child.layout!=null&&await Promise.all(i.child.layout.map(n=>sRa({item:n,filepaths:r,docsWorkspace:t})))}));break;case"versioned":await Promise.all(e.versions.map(async i=>{i.landingPage!=null&&await sRa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await Twc({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break;case"productgroup":await Promise.all(e.products.map(async i=>{i.landingPage!=null&&await sRa({item:i.landingPage,filepaths:r,docsWorkspace:t}),(await Twc({navigation:i.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break}return r}async function sRa({item:e,filepaths:t,docsWorkspace:r}){switch(e.type){case"page":e.icon!=null&&await S9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"section":e.icon!=null&&await S9n({iconPath:e.icon,filepaths:t,docsWorkspace:r}),await Promise.all(e.contents.map(i=>sRa({item:i,filepaths:t,docsWorkspace:r})));break;case"apiSection":e.icon!=null&&await S9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"link":e.icon!=null&&await S9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"changelog":e.icon!=null&&await S9n({iconPath:e.icon,filepaths:t,docsWorkspace:r});break}}async function tN_({navigation:e,apiWorkspaces:t,visitor:r,context:i}){t2E(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await Cwc({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await Cwc({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function Cwc({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await UYt(e,{alphabetized:Go,api:Go,apiName:Go,audiences:Go,displayErrors:Go,snippets:Go,summary:Go,title:Go,layout:Go,icon:Go,slug:Go,hidden:Go,skipSlug:Go,paginated:Go,playground:Go,flattened:Go,path:Go,page:Go,featureFlag:Go,openrpc:Go,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await Cwc({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:Go,orphaned:Go}),e2E(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function e2E(e){return e.api!=null}function t2E(e){return e[0]?.tab!=null}function kZ(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}rN_.default.extend(iN_.default);var r2E=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),Dtu=0,i2E=async({ir:e})=>(Dtu++,`${e.apiName.snakeCase.unsafeName}-${Dtu}`),n2E=async({api:e})=>(Dtu++,`${e.id}-${Dtu}`),mHt=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=r2E,d=i2E,s=n2E){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=d,this.registerApiV2=s}#e=Eeu.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;async resolve(){this._parsedDocsConfig=await J7s({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});let t=this.parsedDocsConfig.experimental?.openapiParserV3,r=t!=null&&!t;this.docsWorkspace.config.navigation!=null&&r&&await tN_({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:o})=>{(await o.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(b=>{let g=Bq(this.docsWorkspace.absoluteFilePath,b.absoluteFilepath);this.parsedDocsConfig.pages[g]=b.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages);for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Na.of(o)]=await fgc({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Na.of(o)]=await lgc({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});let i=await eN_({parsedDocsConfig:this.parsedDocsConfig,docsWorkspace:this.docsWorkspace});for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:b,markdown:g}=kza(c,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Na.of(o)]=g;for(let O of b)i.add(O)}catch(b){throw this.taskContext.logger.error(`Failed to parse ${o}: ${b instanceof Error?b.message:String(b)}`),b}let n=Array.from(i).map(o=>({absoluteFilePath:o,relativeFilePath:this.toRelativeFilepath(o)}));(await this.uploadFiles(n)).forEach(o=>{this.collectedFileIds.set(o.absoluteFilePath,o.fileId)});let u=await this.getMarkdownFilesToFullyQualifiedPathNames();for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Na.of(o)]=cgc(c,this.collectedFileIds,u,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let l={};Object.entries(this.parsedDocsConfig.pages).forEach(([o,c])=>{let b=a2E(this.editThisPage,o);l[dHt.PageId(o)]={markdown:c,editThisPageUrl:b?dHt.Url(b):void 0}});let d=await this.convertDocsConfiguration(),s={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let o=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async c=>{let b=Gv(this.docsWorkspace.absoluteFilePath,c);(await(0,Etu.stat)(b)).isDirectory()?(await cxe(b,"{js,ts,jsx,tsx,md,mdx}")).forEach(m=>{o.add(m)}):b.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&o.add(b)})),s=Object.fromEntries(await Promise.all([...o].map(async c=>{let b=this.toRelativeFilepath(c),g=(await(0,Etu.readFile)(c)).toString();return[b,g]})))}return{config:d,pages:l,jsFiles:s}}resolveFilepath(t){if(t!=null)return Gv(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return Bq(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,Bwc.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,Bwc.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(){let t={},r=So.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return So.NodeCollector.collect(r).slugMap.forEach((n,a)=>{if(n==null||!So.isPage(n))return;let u=So.getPageId(n);if(u==null)return;let l=Ru(this.docsWorkspace.absoluteFilePath,Na.of(u));t[l]=a}),t}getDocsBasePath(){return new URL(kZ(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?dHt.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>({...i,url:dHt.Url(i.url)})),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:dHt.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}getOpenApiWorkspaceForApiSection(t){if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];if(t.apiName!=null){let i=this.ossWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}async toRootNode(){let t=So.V1.SlugGenerator.init(So.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>So.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return rCn(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=So.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??Tq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((n,a)=>this.toVersionNode(n,r,a===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(u=>this.toProductNode(u,i)))}}async toProductNode(t,r){let i=r.setProductSlug(t.slug??Tq(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:jo(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:So.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:t.icon,image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??Tq(t.version)),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:So.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?o2E(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(l=>this.toNavigationChild(n,l,i))),u=[];return a.forEach(l=>{if(l.type==="apiReference"){u.push(l);return}if(l.type==="section"&&!l.collapsed){u.push(l);return}let d=u.length>0?u[u.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(s)),s.children.push(l)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i,n){return rCn(r)._visit({page:async a=>this.toPageNode(a,i,n),apiSection:async a=>this.toApiSectionNode(a,i,n),section:async a=>this.toSectionNode(t,a,i,n),link:async a=>this.toLinkNode(a),changelog:async a=>this.toChangelogNode(a,i,n)})}async toApiSectionNode(t,r,i){if(t.openrpc!=null){let b=Gv(this.docsWorkspace.absoluteFilePath,Na.of(t.openrpc));if(!await mf(b))throw new Error(`OpenRPC file does not exist at path: ${b}`);let g=await kR_(b,this.taskContext);if(g==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:g,apiName:t.apiName,snippetsConfig:Meu(t.snippetsConfiguration)}),new kxa(t,g,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let b=this.getOpenApiWorkspaceForApiSection(t),g=Meu(t.snippetsConfiguration),O=await uRa(b,this.taskContext);if(O==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:O,snippetsConfig:g,apiName:t.apiName}),new kxa(t,O,r,b,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}let n=Meu(t.snippetsConfiguration),a,u,l=this.parsedDocsConfig.experimental?.openapiParserV3;if(l==null||l)try{a=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1})}catch{}a==null&&(u=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),a=hR({workspace:u,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new _R(this.taskContext,u)}));let s=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),o=eRa(a,s,{oauth:t.playground?.oauth});return new Seu(t,o,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,u,i).get()}async toChangelogNode(t,r,i){return new fpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:So.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r,i){let n=So.PageId(this.toRelativeFilepath(t.absolutePath)),a=r.apply({urlSlug:t.slug??Tq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:a.get(),title:t.title,icon:t.icon,hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toSectionNode(t,r,i,n){let a=this.toRelativeFilepath(r.overviewAbsolutePath),u=a?So.PageId(a):void 0,l=this.#e.get(u??`${t}/section`),d=i.apply({urlSlug:r.slug??Tq(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),s=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,o=n||r.hidden;return{id:l,type:"section",overviewPageId:u,slug:d.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:o,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(c=>this.toNavigationChild(l,c,d,o))),authed:void 0,pointsTo:void 0,noindex:s,featureFlags:r.featureFlags}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return rCn(r.child)._visit({link:({href:n})=>this.toTabLinkNode(r,n),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i)})}async toTabChangelogNode(t,r,i){return new fpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:So.V1.Url(r),icon:t.icon}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),u=n.apply({urlSlug:r.slug??Tq(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:u.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,u),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):dHt.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(yv),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:dHt.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return rCn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:dHt.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function a2E(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${kZ(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function o2E(e){switch(e){case"beta":return So.V1.NavigationV1Availability.Beta;case"deprecated":return So.V1.NavigationV1Availability.Deprecated;case"ga":return So.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return So.V1.NavigationV1Availability.Stable;default:jo(e)}}async function nH(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof fR?t:null))).filter(yv)}async function Iwc(e,t,r){if(e instanceof nir){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof fR))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1});return ZZ({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:{oauth:!0}})}var t6_=ui(ktu(),1),SMe=require("fs/promises"),yru=require("os"),r6_=ui(QX(),1),i6_=ui(e6_(),1);var k5E="etag",q1c="preview",T1c="app-preview",e9E="bundle",t9E=".next",C1c=".fern";function r9E({app:e=!1}){return Ru(ll.of((0,yru.homedir)()),Na.of(C1c),Na.of(e?T1c:q1c))}function gKi({app:e=!1}){return Ru(ll.of((0,yru.homedir)()),Na.of(C1c),Na.of(e?T1c:q1c),Na.of(e?t9E:e9E))}function i9E({app:e=!1}){return Ru(ll.of((0,yru.homedir)()),Na.of(C1c),Na.of(e?T1c:q1c),Na.of(k5E))}async function MRa({bucketUrl:e,logger:t,preferCached:r,app:i=!1,tryTar:n=!1}){t.debug("Setting up docs preview bundle...");let a=await fetch(e);if(!a.ok)return{type:"failure"};let u=await a.text(),d=await new i6_.default.Parser().parseStringPromise(u),s=d?.ListBucketResult?.Contents?.[0]?.ETag?.[0],o=d?.ListBucketResult?.Contents?.[0]?.Key?.[0],c=i9E({app:i});if(r){let m=await mf(c),w;if(m&&(t.debug("Reading existing ETag"),w=(await(0,SMe.readFile)(c)).toString()),w!=null&&w===s)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle"),i&&t.info(`Setting up docs preview bundle...
|
|
2043
2045
|
Please wait while the installation completes. This may take a few minutes depending on your connection speed.`)}t.debug("Creating tmp directory to download docs preview bundle");let b=await r6_.default.dir({prefix:"fern"}),g=ll.of(b.path),O=new URL(o,e).href;t.debug(`Downloading docs preview bundle from ${O}`);try{let m=await fetch(O);if(!m.ok)return t.error(`Failed to download docs preview bundle. Status code: ${m.status}`),{type:"failure"};let w=Ru(g,Na.of(n?"output.tar.gz":"output.zip"));if(m.body==null)return{type:"failure"};let E=Buffer.from(await m.arrayBuffer());await(0,SMe.writeFile)(w,new Uint8Array(E)),t.debug(`Wrote ${n?"output.tar.gz":"output.zip"} to ${w}`);let q=r9E({app:i});await mf(q)&&await(0,SMe.rm)(q,{recursive:!0}),await(0,SMe.mkdir)(q,{recursive:!0}),t.debug(`rm -rf ${q}`);let A=gKi({app:i});if(await(0,SMe.mkdir)(A,{recursive:!0}),await(0,t6_.default)(w,A),await(0,SMe.writeFile)(c,s),t.debug(`Downloaded bundle to ${A}`),i){t.debug("Checking if pnpm is installed");try{await ZN(t,process.platform==="win32"?"where":"which",["pnpm"],{cwd:A,doNotPipeOutput:!0})}catch{t.debug("pnpm not found, installing pnpm"),await ZN(t,"npm",["install","-g","pnpm"],{doNotPipeOutput:!0})}try{await ZN(t,process.platform==="win32"?"where":"which",["pnpm"],{cwd:A,doNotPipeOutput:!0})}catch{return t.error("Requires [pnpm] to run local development. Please run: npm install -g pnpm, and then: fern docs dev"),await mf(q)&&await(0,SMe.rm)(q,{recursive:!0}),t.debug(`rm -rf ${q}`),{type:"failure"}}try{t.debug("Installing esbuild"),await ZN(t,"pnpm",["i","esbuild"],{cwd:A,doNotPipeOutput:!0})}catch{return t.error("Failed to install required package. Please reach out to support@buildwithfern.com."),await mf(q)&&await(0,SMe.rm)(q,{recursive:!0}),t.debug(`rm -rf ${q}`),{type:"failure"}}try{t.debug("Resolve esbuild imports"),await ZN(t,"node",["install-esbuild.js"],{cwd:A,doNotPipeOutput:!0})}catch{return t.error("Failed to resolve imports. Please reach out to support@buildwithfern.com."),await mf(q)&&await(0,SMe.rm)(q,{recursive:!0}),t.debug(`rm -rf ${q}`),{type:"failure"}}}return{type:"success"}}catch(m){return t.error(`Failed to download docs preview bundle. Error: ${m}`),{type:"failure"}}}var b6_=require("fs/promises");var x1c=ui(Jtr(),1),l6_=require("path");var N9n=ui(PEe(),1);function vru(e){if(e==null)return;let t=[],r=!1;if(pir(e,{enter(i){(i.type==="FunctionDeclaration"||i.type==="ArrowFunctionExpression"||i.type==="JSXOpeningElement"||i.type==="JSXOpeningFragment"||i.type==="Identifier")&&(r=!0,this.skip()),i.type==="Literal"&&t.push(i.value)}}),!r)return t.length===1?t[0]:void 0}function B1c(e){if(typeof e=="string")return e;if(e?.type==="mdxJsxAttributeValueExpression")return vru(e.data?.estree)}function n6_(e){return e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement"}function a6_(e){return e.type==="mdxFlowExpression"||e.type==="mdxTextExpression"}function I1c(e){return e.type==="mdxJsxAttribute"}function o6_(e){return e.type==="mdxJsxExpressionAttribute"}var u6_=ui(Jtr(),1);function s6_(e){let{content:t}=(0,u6_.default)(e);return Kza(t,{extensions:[o3n(),kFn(),Xza()],mdastExtensions:[h$i(),l$i(),Yza()]})}function c6_(e,t){pir(e,{enter(r){r.type==="JSXElement"&&r.openingElement.attributes.forEach(i=>{i.type==="JSXAttribute"&&i.name.type==="JSXIdentifier"&&t[i.name.name]&&t[i.name.name]?.(i,r)})}})}function f6_(e,{absolutePathToFernFolder:t,absolutePathToMarkdownFile:r}){return e==null||d6_(e)||p6_(e)?void 0:Gv(e.startsWith("/")?t:Cd(r),Na.of(e.replace(/^\//,"")))}function d6_(e){return/^(https?:)?\/\//.test(e)}function p6_(e){return e.startsWith("data:")}function _6_({href:e,metadata:t,markdownFilesToPathName:r}){if(e!=null&&(e.endsWith(".md")||e.endsWith(".mdx"))){let i=f6_(e,t);if(i!=null){let n=r[i];return n!=null?{type:"replace",slug:n.startsWith("/")?n:"/"+n,href:e}:{type:"missing-reference",path:i,href:e}}}}function R1c(e,t,r,i,n){let{content:a,data:u}=(0,x1c.default)(e,{}),l=a,d=s6_(a),s=0;function o(c){if(c==null||d6_(c)||p6_(c))return;if((0,l6_.isAbsolute)(c)){let g=ll.of(c),O=t.get(g);return O?`file:${O}`:void 0}let b=f6_(c,i);if(b){let g=t.get(b);return g?`file:${g}`:void 0}}return a9E(u,["image","og:image","og:logo","twitter:image"],o),u9E(u,o),Ff(d,c=>{if(c.position==null)return;let{start:b,length:g}=n9E(a,c.position),O=l.slice(b+s,b+s+g),m=O;function w(A){let D=o(A);A&&D&&(m=m.replace(A,D))}function E(A){let D=_6_({href:A,markdownFilesToPathName:r,metadata:i});A!=null&&D!=null&&D.type==="replace"&&(m=m.replace(A,D.slug))}function q(A){c6_(A,{src:D=>w(BAi(vru(D.value))),href:D=>E(BAi(vru(D.value)))})}if(c.type==="image"){let A=BAi(c.url);w(BAi(A))}if(c.type==="link"&&E(BAi(c.url)),n6_(c)){let A=c.attributes.filter(I1c).find(C=>C.name==="src");w(BAi(B1c(A?.value)));let D=c.attributes.find(C=>C.type==="mdxJsxAttribute"&&C.name==="href");E(BAi(B1c(D?.value))),c.attributes.forEach(C=>{I1c(C)&&typeof C.value!="string"&&C.value!=null&&C.value.data?.estree?q(C.value.data.estree):o6_(C)&&C.data?.estree&&q(C.data.estree)})}if(a6_(c)&&c.data?.estree&&q(c.data.estree),m!==O)return l=l.slice(0,b+s)+m+l.slice(b+s+g),s+=m.length-g,_p}),x1c.default.stringify(l,u)}function n9E(e,t){let r=e.split(`
|
|
2044
2046
|
`),i=t.start.column-1;for(let a=0;a<t.start.line-1;a++){let u=r[a];if(u==null)break;i+=u.length+1}let n=0-t.start.column+t.end.column;for(let a=t.start.line-1;a<t.end.line-1;a++){let u=r[a];if(u==null)break;n+=u.length+1}return{start:i,length:n}}function BAi(e){if(typeof e=="string")return e.replace(/#.*$/,"")}function a9E(e,t,r){for(let i of t){let n=e[i];if(n!=null){if(typeof n=="object")n.type==="fileId"&&(e[i]={type:"fileId",value:N9n.FernRegistry.FileId(r(n.value)??n.value)});else if(typeof n=="string"){let a=r(n);e[i]=a?{type:"fileId",value:N9n.FernRegistry.FileId(a)}:{type:"url",value:N9n.FernRegistry.Url(n)}}}}}var o9E=du.union([du.string(),du.object({light:du.string().optional(),dark:du.string().optional()})]);function z1c(e,t){let r=t(e);return r?{type:"fileId",value:N9n.FernRegistry.FileId(r)}:{type:"url",value:N9n.FernRegistry.Url(e)}}function u9E(e,t){let r=o9E.safeParse(e.logo);if(!r.success)return;let i=r.data;typeof i=="string"?e.logo=z1c(i,t):(i.light!=null&&(e.logo.light=z1c(i.light,t)),i.dark!=null&&(e.logo.dark=z1c(i.dark,t)))}var h6_=require("fs/promises");async function s9E(e){return(await(0,h6_.readFile)(e)).toString()}async function N1c({markdown:e,absolutePathToFernFolder:t,absolutePathToMarkdownFile:r,context:i,fileLoader:n=s9E}){if(!e.includes("<Code "))return e;let a=/([ \t]*)<Code(?:\s+[^>]*?)?\s+src={?['"]([^'"]+)['"](?! \+)}?((?:\s+[^>]*)?)\/>/g,u=e,l;for(;(l=a.exec(e))!=null;){let d=l[0],s=l[1],o=l[2];if(d==null||o==null)throw new Error(`Failed to parse regex "${l}" in ${r}`);let c=Gv(o.startsWith("/")?t:Cd(r),Na.of(o.replace(/^\//,"")));try{let b=await n(c),g="",O=c.split(".").pop();O!=null&&(g+=O);let m=c.split("/").pop();m!=null&&(g+=` title={"${m}"}`);let w=l[3]?.trim()||"";if(w){let q=/(\w+)=(?:{([^}]+)}|"([^"]+)")/g,A;for(;(A=q.exec(w))!==null;){let D=A[1],C=A[2]||A[3];D&&C&&D!=="src"&&(g+=` ${D}=${C.includes("{")?C:`{${C}}`}`)}}let E=d?.split("src=")[0]?.trim()??"";if(E){let q=/(\w+)=(?:{([^}]+)}|"([^"]+)")/g,A;for(;(A=q.exec(E))!==null;){let D=A[1],C=A[2]||A[3];D&&C&&D!=="src"&&(g+=` ${D}=${C.includes("{")?C:`{${C}}`}`)}}b=`\`\`\`${g}
|
|
2045
2047
|
${b}
|