fern-api 0.65.41 → 0.65.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +3 -3
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1712,7 +1712,7 @@ ${fTp.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&bKs(th
|
|
|
1712
1712
|
`+h$i.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?h$i.default.cyan(OTp(t,this.opt.mask)):h$i.default.italic(h$i.default.dim("[hidden]")):this.opt.mask?OTp(t,this.opt.mask):h$i.default.italic(h$i.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 a7o=ui(J2(),1),$Cp=ui(lYs(),1),GCp=ui(rMe(),1);var sMa=class extends K2{_run(t){this.done=t,this.editorResult=new GCp.Subject;let r=xW(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"?a7o.default.dim("Received"):a7o.default.dim("Press <enter> to launch your preferred editor."),t&&(r=a7o.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,$Cp.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 XCp=require("stream");var KCp=ui(require("readline"),1),YCp=ui(JCp(),1),j$i=class{constructor(t){this.rl||=KCp.default.createInterface(uyD(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 uyD(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 YCp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var cMa=class extends j$i{constructor(t={}){super(t),this.log=new XCp.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return HEa(this.rl,this.bottomBar.split(`
|
|
1713
1713
|
`).length),this}updateBottomBar(t){return HEa(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&&B3o(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var YE=ui(rMe(),1),eBp=ui(dEa(),1);var o7o=ui(rMe(),1),ZCp=ui(dEa(),1),u7o=function(e,t,r){return typeof e[t]!="function"?(0,o7o.of)(e):(0,o7o.from)((0,ZCp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var kCp={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}},f3n=class extends j$i{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,YE.from)(t):(0,YE.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,YE.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,YE.from)([t]),this.process=i.pipe((0,YE.concatMap)(this.processQuestion.bind(this)),(0,YE.publish)()),this.process.connect(),this.process.pipe((0,YE.reduce)((n,a)=>(kCp.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,YE.defer)(()=>(0,YE.of)(t).pipe((0,YE.concatMap)(this.setDefaultType.bind(this)),(0,YE.concatMap)(this.filterIfRunnable.bind(this)),(0,YE.concatMap)(()=>u7o(t,"message",this.answers)),(0,YE.concatMap)(()=>u7o(t,"default",this.answers)),(0,YE.concatMap)(()=>u7o(t,"choices",this.answers)),(0,YE.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,YE.defer)(()=>(0,YE.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,YE.defer)(()=>(0,YE.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&kCp.get(this.answers,t.name)!==void 0)return YE.EMPTY;if(t.when===!1)return YE.EMPTY;if(typeof t.when!="function")return(0,YE.of)(t);let{answers:r}=this;return(0,YE.defer)(()=>(0,YE.from)((0,eBp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,YE.filter)(i=>i!=null)))}};function tBp(e){let t=function(r,i){let n;try{n=new f3n(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",GEa),this.registerPrompt("input",_$i),this.registerPrompt("number",QEa),this.registerPrompt("confirm",JEa),this.registerPrompt("rawlist",KEa),this.registerPrompt("expand",YEa),this.registerPrompt("checkbox",XEa),this.registerPrompt("password",ZEa),this.registerPrompt("editor",sMa)},t.restoreDefaultPrompts(),t}var dYs=tBp();function cyD(e,t){dYs.registerPrompt(e,t)}function lyD(){dYs.restoreDefaultPrompts()}var fyD={prompt:dYs,ui:{BottomBar:cMa,Prompt:f3n},createPromptModule:tBp,registerPrompt:cyD,restoreDefaultPrompts:lyD,Separator:mae},s7o=fyD;var j3n=require("path"),zIp=require("fs"),xIp=require("readline"),oIp="posthog-node";function GbD(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[q7o.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 q7o=class{constructor(t,r,i,n){this.name=oIp,this.name=oIp,this.setupOnce=function(a,u){let l=u()?.getClient()?.getDsn()?.projectId;a(GbD(t,{organization:r,projectId:l,prefix:i,severityAllowList:n}))}}};q7o.POSTHOG_ID_TAG="posthog_distinct_id";var S7o="0123456789abcdef",T7o=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+=S7o.charAt(this.bytes[r]>>>4),t+=S7o.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+=S7o.charAt(this.bytes[r]>>>4),t+=S7o.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}},tXs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??QbD()}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 T7o.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,T7o.ofInner(t)}},QbD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),uIp,rXs=()=>JbD().toString(),JbD=()=>(uIp||(uIp=new tXs)).generate();function KbD(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 YbD(e,t){global.process.on("uncaughtException",KbD(e,t))}function XbD(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var D7o,sIp,E7o;function ZbD(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return E7o&&r.length===sIp||(sIp=r.length,E7o=r.reduce((i,n)=>{D7o||(D7o={});let a=D7o[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,D7o[n]=[s,o];break}}}return i},{})),E7o}function kbD(e){return typeof Event<"u"&&RIp(e,Event)}function e0D(e){return NIp(e,"Object")}function lXs(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return RIp(e,Error)}}function RIp(e,t){try{return e instanceof t}catch{return!1}}function t0D(e){return NIp(e,"ErrorEvent")}function NIp(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function r0D(e,t,r,i){let a=i&&i.mechanism||{handled:!0,type:"generic"},u=FIp(a,r,i);return{$exception_list:await Promise.all(u.map(async s=>{let o=await c0D(e,t,s);return o.value=o.value||"",o.type=o.type||"Error",o.mechanism=a,o}))}}function FIp(e,t,r){let i=i0D(e,t,r);return i.cause?[i,...FIp(e,i.cause,r)]:[i]}function i0D(e,t,r){if(lXs(t))return t;if(e.synthetic=!0,e0D(t)){let n=n0D(t);if(n)return n;let a=a0D(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 n0D(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(lXs(r))return r}}function a0D(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=u0D(e);if(t0D(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=o0D(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function o0D(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function u0D(e,t=40){let r=Object.keys(s0D(e));r.sort();let i=r[0];if(!i)return"[object has no keys]";if(i.length>=t)return cIp(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:cIp(a,t)}return""}function cIp(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function s0D(e){return lXs(e)?{message:e.message,name:e.name,stack:e.stack,...lIp(e)}:kbD(e)?{type:e.type,target:fIp(e.target),currentTarget:fIp(e.currentTarget),...lIp(e)}:e}function lIp(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 fIp(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function c0D(e,t,r){let i={type:r.name||r.constructor.name,value:r.message},n=l0D(e,r);for(let a of t)n=await a(n);return n.length&&(i.stacktrace={frames:n,type:"raw"}),i}function l0D(e,t){return f0D(e(t.stack||"",1),e)}function f0D(e,t){let r=ZbD(t);return e.forEach(i=>{i.filename&&(i.chunk_id=r[i.filename])}),e}var d0D=2e3,O3n=class e{static async captureException(t,r,i,n,a){let u={...a};n||(u.$process_person_profile=!1);let l=await r0D(this.stackParser,this.frameModifiers,r,i);t.capture({event:"$exception",distinctId:n||rXs(),properties:{...l,...u}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(YbD(this.onException.bind(this),this.onFatalError.bind(this)),XbD(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(d0D)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function p0D(e=process.argv[1]?(0,j3n.dirname)(process.argv[1]):process.cwd(),t=j3n.sep==="\\"){let r=t?dIp(e):e;return i=>{if(!i)return;let n=t?dIp(i):i,{dir:a,base:u,ext:l}=j3n.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 dIp(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var C7o=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)}}},A7o=new C7o(25),LIp=new C7o(20),fXs=7,_0D=1e3,h0D=1e4;async function y0D(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"||O0D(u)||m0D(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(LIp.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let u=j0D(a);if(u.every(d=>P0D(n,d)))continue;let l=w0D(A7o,n,{});i.push(v0D(n,u,l))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&b0D(e,A7o),A7o.reduce(),e}function v0D(e,t,r){return new Promise(i=>{let n=(0,zIp.createReadStream)(e),a=(0,xIp.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(){LIp.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]=S0D(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 b0D(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;g0D(r.lineno,r,i)}}function g0D(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=UIp(e);n<e;n++){let a=r[n];if(a===void 0){pIp(t);return}t.pre_context.push(a)}if(r[e]===void 0){pIp(t);return}t.context_line=r[e];let i=VIp(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 pIp(e){delete e.pre_context,delete e.context_line,delete e.post_context}function O0D(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function m0D(e){return e.lineno!==void 0&&e.lineno>h0D||e.colno!==void 0&&e.colno>_0D}function P0D(e,t){let r=A7o.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 j0D(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=_Ip(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+fXs:(n.push(i),i=_Ip(a)),t++}return n}function _Ip(e){return[UIp(e),VIp(e)]}function UIp(e){return Math.max(1,e-fXs)}function VIp(e){return e+fXs}function w0D(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function S0D(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 D0D="4.18.0",Eae;(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"})(Eae||(Eae={}));var hIp;(function(e){e.Left="left",e.Right="right",e.Center="center"})(hIp||(hIp={}));var yIp;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(yIp||(yIp={}));var vIp;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(vIp||(vIp={}));var bIp;(function(e){e.Html="html",e.Text="text"})(bIp||(bIp={}));var gIp;(function(e){e.Number="number",e.Emoji="emoji"})(gIp||(gIp={}));var OIp;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(OIp||(OIp={}));var mIp;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(mIp||(mIp={}));var PIp;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(PIp||(PIp={}));var jIp;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(jIp||(jIp={}));var E0D=e=>{if("flags"in e){let t=A0D(e.flags),r=q0D(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,WIp(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,M0D(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function M0D(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 A0D=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,dXs(r)]).filter(([,t])=>t!==void 0)),q0D=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?WIp(i):void 0]}))},dXs=e=>e===void 0?void 0:e.variant??e.enabled,WIp=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},T0D=1,C0D=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"]),B0D="utf8";function I0D(e,t){if(!e||typeof e!="string"||z0D(e))throw new Error(t)}function z0D(e){return e.trim().length===0}function x0D(e){return e?.replace(/\/+$/,"")}async function R0D(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 wIp(){return new Date().getTime()}function kYs(){return new Date().toISOString()}function B7o(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function N0D(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function F0D(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 L0D(e,t=0,r){let i=F0D(e);return r?.has(i)?!1:parseInt(i,16)/4294967295<t}function SIp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var gMa=String.fromCharCode,DIp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",M7o={};function U0D(e,t){if(!M7o[e]){M7o[e]={};for(let r=0;r<e.length;r++)M7o[e][e.charAt(r)]=r}return M7o[e][t]}var b3n={compressToBase64:function(e){if(e==null)return"";let t=b3n._compress(e,6,function(r){return DIp.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:b3n._decompress(e.length,32,function(t){return U0D(DIp,e.charAt(t))})},compress:function(e){return b3n._compress(e,16,function(t){return gMa(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:b3n._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=gMa(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=gMa(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++]=gMa(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++]=gMa(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++)}}},iXs=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)}},m3n=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()}},OMa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function EIp(e){if(e instanceof m3n){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 eXs(e){return typeof e=="object"&&(e instanceof m3n||e instanceof OMa)}function MIp(e){return typeof e=="object"&&e instanceof m3n&&e.status===413}var nXs;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(nXs||(nXs={}));var aXs=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new iXs,this._isInitialized=!1,I0D(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=x0D(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:eXs},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(Eae.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Eae.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Eae.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=rXs();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=L0D(this.apiKey,T0D,C0D)?`${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=>E0D(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=dXs(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(nXs.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(Eae.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(Eae.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(Eae.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(Eae.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(Eae.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=B7o(()=>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:kYs()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),u=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${wIp()}&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(b3n.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:kYs(),uuid:i?.uuid?i.uuid:rXs()};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 EIp(t)})}async flush(){let t=SIp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),SIp([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(Eae.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(Eae.Queue)||[]).slice(n.length);this.setPersistedProperty(Eae.Queue,g),t=g},l={api_key:this.apiKey,batch:a,sent_at:kYs()};this.historicalMigration&&(l.historical_migration=!0);let d=JSON.stringify(l),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${wIp()}&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(b3n.compressToBase64(d))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:d},c={retryCheck:b=>MIp(b)?!1:eXs(b)};try{await this.fetchWithRetry(s,o,c)}catch(b){if(MIp(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 OMa||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,B0D)}catch{l=new TextEncoder().encode(u).length}return await R0D(async()=>{let d=null;try{d=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(o){throw new OMa(o)}if(!(r.mode==="no-cors")&&(d.status<200||d.status>=400))throw new m3n(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(Eae.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!eXs(n))throw n;await EIp(n)}};return Promise.race([new Promise((n,a)=>{B7o(()=>{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}},oXs=N0D();if(!oXs){let e=aIp();oXs=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 HIp=oXs,I7o=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()}},$Ip=new I7o(async()=>{try{return await import("crypto")}catch{return}});async function V0D(){return await $Ip.getValue()}var W0D=new I7o(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await $Ip.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function H0D(){return await W0D.getValue()}async function $0D(e){let t=await V0D();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await H0D();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 G0D=60*1e3,Q0D=1152921504606847e3,J0D=["is_not"],g3n=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Y2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},uXs=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||HIp,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 Y2?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 Y2||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 Y2("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 Y2("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 Y2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new Y2("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=QIp(l,n,this.cohorts,this.debugMode):s=GIp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&await AIp(t.key,r)>a/100)}async getMatchingVariant(t,r){let i=await AIp(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(G0D,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 g3n(`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 g3n(`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 g3n(`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 g3n&&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=B7o(()=>{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=B7o(()=>{a.abort()},this.timeout),i.signal=a.signal}try{return this.fetch(r,i)}finally{clearTimeout(n)}}};async function AIp(e,t,r=""){let i=await $0D(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/Q0D}function GIp(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 Y2("Operator is_not_set is not supported")}else throw new Y2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!J0D.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 qIp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return qIp(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=K0D(String(n));if(s==null&&(s=TIp(n)),s==null)throw new Y2(`Invalid date: ${n}`);let o=TIp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new Y2(`Unknown operator: ${a}`)}}function QIp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new Y2("can't match cohort without a given cohort property value");let a=r[n];return JIp(a,t,r,i)}function JIp(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=JIp(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof Y2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Y2("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=QIp(l,t,r,i):d=GIp(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 Y2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Y2("can't match cohort without a given cohort property value");return n==="AND"}}function qIp(e){try{return new RegExp(e),!0}catch{return!1}}function TIp(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 Y2(`${e} is in an invalid date format`)}else throw new Y2(`The date provided ${e} must be a string, number, or date object`)}function K0D(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 sXs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},Y0D=100,CIp=30*1e3,X0D=50*1e3,cXs=class extends aXs{constructor(t,r={}){if(super(t,r),this._memoryStorage=new sXs,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,Y0D):CIp,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 uXs({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 O3n(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||X0D}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):HIp(t,r)}getLibraryVersion(){return D0D}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=CIp){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=dXs(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");O3n.captureException(this,t,{syntheticException:n},r,i)}},BIp=/\(error: (.*)\)/,KIp=50,YIp="?";function Z0D(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||YIp,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:IIp(n[3]),colno:IIp(n[4]),in_app:k0D(o||"",c),platform:"node:javascript"}}if(i.match(t))return{filename:i,platform:"node:javascript"}}}function k0D(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 IIp(e){return parseInt(e||"",10)||void 0}function egD(e){return[90,Z0D(e)]}function tgD(e){let r=[egD(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=BIp.test(d)?d.replace(BIp,"$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>=KIp)break}}return rgD(a)}}function rgD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,KIp).map(r=>({...r,filename:r.filename||igD(t).filename,function:r.function||YIp}))}function igD(e){return e[e.length-1]||{}}O3n.stackParser=tgD(p0D());O3n.frameModifiers=[y0D];var P3n=class extends cXs{getLibraryId(){return"posthog-node"}};var z7o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new P3n(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.65.41",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var mMa=class{async sendEvent(){}async identify(){}async flush(){}};var w3n=require("fs/promises"),ezp=require("os"),tzp=require("path");var XIp=ui(require("crypto")),R7o=new Uint8Array(256),x7o=R7o.length;function pXs(){return x7o>R7o.length-16&&(XIp.default.randomFillSync(R7o),x7o=0),R7o.slice(x7o,x7o+=16)}var FW=[];for(let e=0;e<256;++e)FW.push((e+256).toString(16).slice(1));function ZIp(e,t=0){return FW[e[t+0]]+FW[e[t+1]]+FW[e[t+2]]+FW[e[t+3]]+"-"+FW[e[t+4]]+FW[e[t+5]]+"-"+FW[e[t+6]]+FW[e[t+7]]+"-"+FW[e[t+8]]+FW[e[t+9]]+"-"+FW[e[t+10]]+FW[e[t+11]]+FW[e[t+12]]+FW[e[t+13]]+FW[e[t+14]]+FW[e[t+15]]}var kIp=ui(require("crypto")),_Xs={randomUUID:kIp.default.randomUUID};function ngD(e,t,r){if(_Xs.randomUUID&&!t&&!e)return _Xs.randomUUID();e=e||{};let i=e.random||(e.rng||pXs)();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 ZIp(i)}var Mae=ngD;var agD="id",ogD=".fern",PMa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new P3n(r),this.userId=t==null?void 0:nHs(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.65.41",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Du(Kc.of((0,ezp.homedir)()),Ia.of(ogD),Ia.of(agD));await yf(t)||(await(0,w3n.mkdir)((0,tzp.dirname)(t),{recursive:!0}),await(0,w3n.writeFile)(t,Mae())),this.persistedDistinctId=(await(0,w3n.readFile)(t)).toString()}return this.persistedDistinctId}};var hXs;async function S3n(){return hXs==null&&(hXs=await ugD()),hXs}async function ugD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new mMa;let r=await rzo();return r!=null?new PMa({token:r,posthogApiKey:e}):await wNn()!=null?new z7o({posthogApiKey:e}):new PMa({token:void 0,posthogApiKey:e})}catch{return new mMa}}function jMa(e,t){return function(){return e.apply(t,arguments)}}var{toString:sgD}=Object.prototype,{getPrototypeOf:vXs}=Object,{iterator:F7o,toStringTag:izp}=Symbol,L7o=(e=>t=>{let r=sgD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),MWt=e=>(e=e.toLowerCase(),t=>L7o(t)===e),U7o=e=>t=>typeof t===e,{isArray:D3n}=Array,wMa=U7o("undefined");function cgD(e){return e!==null&&!wMa(e)&&e.constructor!==null&&!wMa(e.constructor)&&Aae(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var nzp=MWt("ArrayBuffer");function lgD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&nzp(e.buffer),t}var fgD=U7o("string"),Aae=U7o("function"),azp=U7o("number"),V7o=e=>e!==null&&typeof e=="object",dgD=e=>e===!0||e===!1,N7o=e=>{if(L7o(e)!=="object")return!1;let t=vXs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(izp in e)&&!(F7o in e)},pgD=MWt("Date"),_gD=MWt("File"),hgD=MWt("Blob"),ygD=MWt("FileList"),vgD=e=>V7o(e)&&Aae(e.pipe),bgD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Aae(e.append)&&((t=L7o(e))==="formdata"||t==="object"&&Aae(e.toString)&&e.toString()==="[object FormData]"))},ggD=MWt("URLSearchParams"),[OgD,mgD,PgD,jgD]=["ReadableStream","Request","Response","Headers"].map(MWt),wgD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function SMa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),D3n(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 ozp(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 A$i=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,uzp=e=>!wMa(e)&&e!==A$i;function yXs(){let{caseless:e}=uzp(this)&&this||{},t={},r=(i,n)=>{let a=e&&ozp(t,n)||n;N7o(t[a])&&N7o(i)?t[a]=yXs(t[a],i):N7o(i)?t[a]=yXs({},i):D3n(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&SMa(arguments[i],r);return t}var SgD=(e,t,r,{allOwnKeys:i}={})=>(SMa(t,(n,a)=>{r&&Aae(n)?e[a]=jMa(n,r):e[a]=n},{allOwnKeys:i}),e),DgD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),EgD=(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)},MgD=(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&&vXs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},AgD=(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},qgD=e=>{if(!e)return null;if(D3n(e))return e;let t=e.length;if(!azp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},TgD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&vXs(Uint8Array)),CgD=(e,t)=>{let i=(e&&e[F7o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},BgD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},IgD=MWt("HTMLFormElement"),zgD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),rzp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),xgD=MWt("RegExp"),szp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};SMa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},RgD=e=>{szp(e,(t,r)=>{if(Aae(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(Aae(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+"'")})}})},NgD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return D3n(e)?i(e):i(String(e).split(t)),r},FgD=()=>{},LgD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function UgD(e){return!!(e&&Aae(e.append)&&e[izp]==="FormData"&&e[F7o])}var VgD=e=>{let t=new Array(10),r=(i,n)=>{if(V7o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=D3n(i)?[]:{};return SMa(i,(u,l)=>{let d=r(u,n+1);!wMa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},WgD=MWt("AsyncFunction"),HgD=e=>e&&(V7o(e)||Aae(e))&&Aae(e.then)&&Aae(e.catch),czp=((e,t)=>e?setImmediate:t?((r,i)=>(A$i.addEventListener("message",({source:n,data:a})=>{n===A$i&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),A$i.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",Aae(A$i.postMessage)),$gD=typeof queueMicrotask<"u"?queueMicrotask.bind(A$i):typeof process<"u"&&process.nextTick||czp,GgD=e=>e!=null&&Aae(e[F7o]),os={isArray:D3n,isArrayBuffer:nzp,isBuffer:cgD,isFormData:bgD,isArrayBufferView:lgD,isString:fgD,isNumber:azp,isBoolean:dgD,isObject:V7o,isPlainObject:N7o,isReadableStream:OgD,isRequest:mgD,isResponse:PgD,isHeaders:jgD,isUndefined:wMa,isDate:pgD,isFile:_gD,isBlob:hgD,isRegExp:xgD,isFunction:Aae,isStream:vgD,isURLSearchParams:ggD,isTypedArray:TgD,isFileList:ygD,forEach:SMa,merge:yXs,extend:SgD,trim:wgD,stripBOM:DgD,inherits:EgD,toFlatObject:MgD,kindOf:L7o,kindOfTest:MWt,endsWith:AgD,toArray:qgD,forEachEntry:CgD,matchAll:BgD,isHTMLForm:IgD,hasOwnProperty:rzp,hasOwnProp:rzp,reduceDescriptors:szp,freezeMethods:RgD,toObjectSet:NgD,toCamelCase:zgD,noop:FgD,toFiniteNumber:LgD,findKey:ozp,global:A$i,isContextDefined:uzp,isSpecCompliantForm:UgD,toJSONObject:VgD,isAsyncFn:WgD,isThenable:HgD,setImmediate:czp,asap:$gD,isIterable:GgD};function E3n(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(E3n,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 lzp=E3n.prototype,fzp={};["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=>{fzp[e]={value:e}});Object.defineProperties(E3n,fzp);Object.defineProperty(lzp,"isAxiosError",{value:!0});E3n.from=(e,t,r,i,n,a)=>{let u=Object.create(lzp);return os.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),E3n.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Up=E3n;var dzp=ui(c7o(),1),W7o=dzp.default;function bXs(e){return os.isPlainObject(e)||os.isArray(e)}function _zp(e){return os.endsWith(e,"[]")?e.slice(0,-2):e}function pzp(e,t,r){return e?e.concat(t).map(function(n,a){return n=_zp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function QgD(e){return os.isArray(e)&&!e.some(bXs)}var JgD=os.toFlatObject(os,{},null,function(t){return/^is[A-Z]/.test(t)});function KgD(e,t,r){if(!os.isObject(e))throw new TypeError("target must be an object");t=t||new(W7o||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 Up("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)&&QgD(O)||(os.isFileList(O)||os.endsWith(m,"[]"))&&(E=os.toArray(O)))return m=_zp(m),E.forEach(function(M,D){!(os.isUndefined(M)||M===null)&&t.append(u===!0?pzp([m],D,a):u===null?m:m+"[]",s(M))}),!1}return bXs(O)?!0:(t.append(pzp(w,m,a),s(O)),!1)}let c=[],b=Object.assign(JgD,{defaultVisitor:o,convertValue:s,isVisitable:bXs});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 DDi=KgD;function hzp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function yzp(e,t){this._pairs=[],e&&DDi(e,this,t)}var vzp=yzp.prototype;vzp.append=function(t,r){this._pairs.push([t,r])};vzp.toString=function(t){let r=t?function(i){return t.call(this,i,hzp)}:hzp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var bzp=yzp;function YgD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function q$i(e,t,r){if(!t)return e;let i=r&&r.encode||YgD;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 bzp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var gXs=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)})}},OXs=gXs;var M3n={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Pzp=ui(require("crypto"),1);var gzp=ui(require("url"),1),Ozp=gzp.default.URLSearchParams;var mXs="abcdefghijklmnopqrstuvwxyz",mzp="0123456789",jzp={DIGIT:mzp,ALPHA:mXs,ALPHA_DIGIT:mXs+mXs.toUpperCase()+mzp},XgD=(e=16,t=jzp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);Pzp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},wzp={isNode:!0,classes:{URLSearchParams:Ozp,FormData:W7o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:jzp,generateString:XgD,protocols:["http","https","file","data"]};var wXs={};mo(wXs,{hasBrowserEnv:()=>jXs,hasStandardBrowserEnv:()=>ZgD,hasStandardBrowserWebWorkerEnv:()=>kgD,navigator:()=>PXs,origin:()=>eOD});var jXs=typeof window<"u"&&typeof document<"u",PXs=typeof navigator=="object"&&navigator||void 0,ZgD=jXs&&(!PXs||["ReactNative","NativeScript","NS"].indexOf(PXs.product)<0),kgD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",eOD=jXs&&window.location.href||"http://localhost";var hA={...wXs,...wzp};function SXs(e,t){return DDi(e,new hA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return hA.isNode&&os.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function tOD(e){return os.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function rOD(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 iOD(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]=rOD(n[u])),!l)}if(os.isFormData(e)&&os.isFunction(e.entries)){let r={};return os.forEachEntry(e,(i,n)=>{t(tOD(i),n,r,0)}),r}return null}var H7o=iOD;function nOD(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 DXs={transitional:M3n,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(H7o(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 SXs(t,this.formSerializer).toString();if((l=os.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return DDi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),nOD(t)):t}],transformResponse:[function(t){let r=this.transitional||DXs.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"?Up.from(l,Up.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:hA.classes.FormData,Blob:hA.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=>{DXs.headers[e]={}});var A3n=DXs;var aOD=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"]),Szp=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=BIp.test(d)?d.replace(BIp,"$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>=KIp)break}}return rgD(a)}}function rgD(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,KIp).map(r=>({...r,filename:r.filename||igD(t).filename,function:r.function||YIp}))}function igD(e){return e[e.length-1]||{}}O3n.stackParser=tgD(p0D());O3n.frameModifiers=[y0D];var P3n=class extends cXs{getLibraryId(){return"posthog-node"}};var z7o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new P3n(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.65.42",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var mMa=class{async sendEvent(){}async identify(){}async flush(){}};var w3n=require("fs/promises"),ezp=require("os"),tzp=require("path");var XIp=ui(require("crypto")),R7o=new Uint8Array(256),x7o=R7o.length;function pXs(){return x7o>R7o.length-16&&(XIp.default.randomFillSync(R7o),x7o=0),R7o.slice(x7o,x7o+=16)}var FW=[];for(let e=0;e<256;++e)FW.push((e+256).toString(16).slice(1));function ZIp(e,t=0){return FW[e[t+0]]+FW[e[t+1]]+FW[e[t+2]]+FW[e[t+3]]+"-"+FW[e[t+4]]+FW[e[t+5]]+"-"+FW[e[t+6]]+FW[e[t+7]]+"-"+FW[e[t+8]]+FW[e[t+9]]+"-"+FW[e[t+10]]+FW[e[t+11]]+FW[e[t+12]]+FW[e[t+13]]+FW[e[t+14]]+FW[e[t+15]]}var kIp=ui(require("crypto")),_Xs={randomUUID:kIp.default.randomUUID};function ngD(e,t,r){if(_Xs.randomUUID&&!t&&!e)return _Xs.randomUUID();e=e||{};let i=e.random||(e.rng||pXs)();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 ZIp(i)}var Mae=ngD;var agD="id",ogD=".fern",PMa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new P3n(r),this.userId=t==null?void 0:nHs(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.65.42",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Du(Kc.of((0,ezp.homedir)()),Ia.of(ogD),Ia.of(agD));await yf(t)||(await(0,w3n.mkdir)((0,tzp.dirname)(t),{recursive:!0}),await(0,w3n.writeFile)(t,Mae())),this.persistedDistinctId=(await(0,w3n.readFile)(t)).toString()}return this.persistedDistinctId}};var hXs;async function S3n(){return hXs==null&&(hXs=await ugD()),hXs}async function ugD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new mMa;let r=await rzo();return r!=null?new PMa({token:r,posthogApiKey:e}):await wNn()!=null?new z7o({posthogApiKey:e}):new PMa({token:void 0,posthogApiKey:e})}catch{return new mMa}}function jMa(e,t){return function(){return e.apply(t,arguments)}}var{toString:sgD}=Object.prototype,{getPrototypeOf:vXs}=Object,{iterator:F7o,toStringTag:izp}=Symbol,L7o=(e=>t=>{let r=sgD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),MWt=e=>(e=e.toLowerCase(),t=>L7o(t)===e),U7o=e=>t=>typeof t===e,{isArray:D3n}=Array,wMa=U7o("undefined");function cgD(e){return e!==null&&!wMa(e)&&e.constructor!==null&&!wMa(e.constructor)&&Aae(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var nzp=MWt("ArrayBuffer");function lgD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&nzp(e.buffer),t}var fgD=U7o("string"),Aae=U7o("function"),azp=U7o("number"),V7o=e=>e!==null&&typeof e=="object",dgD=e=>e===!0||e===!1,N7o=e=>{if(L7o(e)!=="object")return!1;let t=vXs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(izp in e)&&!(F7o in e)},pgD=MWt("Date"),_gD=MWt("File"),hgD=MWt("Blob"),ygD=MWt("FileList"),vgD=e=>V7o(e)&&Aae(e.pipe),bgD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Aae(e.append)&&((t=L7o(e))==="formdata"||t==="object"&&Aae(e.toString)&&e.toString()==="[object FormData]"))},ggD=MWt("URLSearchParams"),[OgD,mgD,PgD,jgD]=["ReadableStream","Request","Response","Headers"].map(MWt),wgD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function SMa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),D3n(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 ozp(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 A$i=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,uzp=e=>!wMa(e)&&e!==A$i;function yXs(){let{caseless:e}=uzp(this)&&this||{},t={},r=(i,n)=>{let a=e&&ozp(t,n)||n;N7o(t[a])&&N7o(i)?t[a]=yXs(t[a],i):N7o(i)?t[a]=yXs({},i):D3n(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&SMa(arguments[i],r);return t}var SgD=(e,t,r,{allOwnKeys:i}={})=>(SMa(t,(n,a)=>{r&&Aae(n)?e[a]=jMa(n,r):e[a]=n},{allOwnKeys:i}),e),DgD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),EgD=(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)},MgD=(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&&vXs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},AgD=(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},qgD=e=>{if(!e)return null;if(D3n(e))return e;let t=e.length;if(!azp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},TgD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&vXs(Uint8Array)),CgD=(e,t)=>{let i=(e&&e[F7o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},BgD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},IgD=MWt("HTMLFormElement"),zgD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),rzp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),xgD=MWt("RegExp"),szp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};SMa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},RgD=e=>{szp(e,(t,r)=>{if(Aae(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(Aae(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+"'")})}})},NgD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return D3n(e)?i(e):i(String(e).split(t)),r},FgD=()=>{},LgD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function UgD(e){return!!(e&&Aae(e.append)&&e[izp]==="FormData"&&e[F7o])}var VgD=e=>{let t=new Array(10),r=(i,n)=>{if(V7o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=D3n(i)?[]:{};return SMa(i,(u,l)=>{let d=r(u,n+1);!wMa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},WgD=MWt("AsyncFunction"),HgD=e=>e&&(V7o(e)||Aae(e))&&Aae(e.then)&&Aae(e.catch),czp=((e,t)=>e?setImmediate:t?((r,i)=>(A$i.addEventListener("message",({source:n,data:a})=>{n===A$i&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),A$i.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",Aae(A$i.postMessage)),$gD=typeof queueMicrotask<"u"?queueMicrotask.bind(A$i):typeof process<"u"&&process.nextTick||czp,GgD=e=>e!=null&&Aae(e[F7o]),os={isArray:D3n,isArrayBuffer:nzp,isBuffer:cgD,isFormData:bgD,isArrayBufferView:lgD,isString:fgD,isNumber:azp,isBoolean:dgD,isObject:V7o,isPlainObject:N7o,isReadableStream:OgD,isRequest:mgD,isResponse:PgD,isHeaders:jgD,isUndefined:wMa,isDate:pgD,isFile:_gD,isBlob:hgD,isRegExp:xgD,isFunction:Aae,isStream:vgD,isURLSearchParams:ggD,isTypedArray:TgD,isFileList:ygD,forEach:SMa,merge:yXs,extend:SgD,trim:wgD,stripBOM:DgD,inherits:EgD,toFlatObject:MgD,kindOf:L7o,kindOfTest:MWt,endsWith:AgD,toArray:qgD,forEachEntry:CgD,matchAll:BgD,isHTMLForm:IgD,hasOwnProperty:rzp,hasOwnProp:rzp,reduceDescriptors:szp,freezeMethods:RgD,toObjectSet:NgD,toCamelCase:zgD,noop:FgD,toFiniteNumber:LgD,findKey:ozp,global:A$i,isContextDefined:uzp,isSpecCompliantForm:UgD,toJSONObject:VgD,isAsyncFn:WgD,isThenable:HgD,setImmediate:czp,asap:$gD,isIterable:GgD};function E3n(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(E3n,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 lzp=E3n.prototype,fzp={};["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=>{fzp[e]={value:e}});Object.defineProperties(E3n,fzp);Object.defineProperty(lzp,"isAxiosError",{value:!0});E3n.from=(e,t,r,i,n,a)=>{let u=Object.create(lzp);return os.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),E3n.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Up=E3n;var dzp=ui(c7o(),1),W7o=dzp.default;function bXs(e){return os.isPlainObject(e)||os.isArray(e)}function _zp(e){return os.endsWith(e,"[]")?e.slice(0,-2):e}function pzp(e,t,r){return e?e.concat(t).map(function(n,a){return n=_zp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function QgD(e){return os.isArray(e)&&!e.some(bXs)}var JgD=os.toFlatObject(os,{},null,function(t){return/^is[A-Z]/.test(t)});function KgD(e,t,r){if(!os.isObject(e))throw new TypeError("target must be an object");t=t||new(W7o||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 Up("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)&&QgD(O)||(os.isFileList(O)||os.endsWith(m,"[]"))&&(E=os.toArray(O)))return m=_zp(m),E.forEach(function(M,D){!(os.isUndefined(M)||M===null)&&t.append(u===!0?pzp([m],D,a):u===null?m:m+"[]",s(M))}),!1}return bXs(O)?!0:(t.append(pzp(w,m,a),s(O)),!1)}let c=[],b=Object.assign(JgD,{defaultVisitor:o,convertValue:s,isVisitable:bXs});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 DDi=KgD;function hzp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function yzp(e,t){this._pairs=[],e&&DDi(e,this,t)}var vzp=yzp.prototype;vzp.append=function(t,r){this._pairs.push([t,r])};vzp.toString=function(t){let r=t?function(i){return t.call(this,i,hzp)}:hzp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var bzp=yzp;function YgD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function q$i(e,t,r){if(!t)return e;let i=r&&r.encode||YgD;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 bzp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var gXs=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)})}},OXs=gXs;var M3n={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Pzp=ui(require("crypto"),1);var gzp=ui(require("url"),1),Ozp=gzp.default.URLSearchParams;var mXs="abcdefghijklmnopqrstuvwxyz",mzp="0123456789",jzp={DIGIT:mzp,ALPHA:mXs,ALPHA_DIGIT:mXs+mXs.toUpperCase()+mzp},XgD=(e=16,t=jzp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);Pzp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},wzp={isNode:!0,classes:{URLSearchParams:Ozp,FormData:W7o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:jzp,generateString:XgD,protocols:["http","https","file","data"]};var wXs={};mo(wXs,{hasBrowserEnv:()=>jXs,hasStandardBrowserEnv:()=>ZgD,hasStandardBrowserWebWorkerEnv:()=>kgD,navigator:()=>PXs,origin:()=>eOD});var jXs=typeof window<"u"&&typeof document<"u",PXs=typeof navigator=="object"&&navigator||void 0,ZgD=jXs&&(!PXs||["ReactNative","NativeScript","NS"].indexOf(PXs.product)<0),kgD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",eOD=jXs&&window.location.href||"http://localhost";var hA={...wXs,...wzp};function SXs(e,t){return DDi(e,new hA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return hA.isNode&&os.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function tOD(e){return os.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function rOD(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 iOD(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]=rOD(n[u])),!l)}if(os.isFormData(e)&&os.isFunction(e.entries)){let r={};return os.forEachEntry(e,(i,n)=>{t(tOD(i),n,r,0)}),r}return null}var H7o=iOD;function nOD(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 DXs={transitional:M3n,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(H7o(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 SXs(t,this.formSerializer).toString();if((l=os.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return DDi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),nOD(t)):t}],transformResponse:[function(t){let r=this.transitional||DXs.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"?Up.from(l,Up.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:hA.classes.FormData,Blob:hA.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=>{DXs.headers[e]={}});var A3n=DXs;var aOD=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"]),Szp=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]&&aOD[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var Dzp=Symbol("internals");function DMa(e){return e&&String(e).trim().toLowerCase()}function $7o(e){return e===!1||e==null?e:os.isArray(e)?e.map($7o):String(e)}function oOD(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 uOD=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function EXs(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 sOD(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function cOD(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 q3n=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,d,s){let o=DMa(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]=$7o(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())&&!uOD(t))u(Szp(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=DMa(t),t){let i=os.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return oOD(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=DMa(t),t){let i=os.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||EXs(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=DMa(u),u){let l=os.findKey(i,u);l&&(!r||EXs(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||EXs(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]=$7o(n),delete r[a];return}let l=t?sOD(a):String(a).trim();l!==a&&delete r[a],r[l]=$7o(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[Dzp]=this[Dzp]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=DMa(u);i[l]||(cOD(n,u),i[l]=!0)}return os.isArray(t)?t.forEach(a):a(t),this}};q3n.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);os.reduceDescriptors(q3n.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});os.freezeMethods(q3n);var hR=q3n;function EMa(e,t){let r=this||A3n,i=t||r,n=hR.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 MMa(e){return!!(e&&e.__CANCEL__)}function Ezp(e,t,r){Up.call(this,e??"canceled",Up.ERR_CANCELED,t,r),this.name="CanceledError"}os.inherits(Ezp,Up,{__CANCEL__:!0});var nMe=Ezp;function _rr(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Up("Request failed with status code "+r.status,[Up.ERR_BAD_REQUEST,Up.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function MXs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function AXs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function T$i(e,t,r){let i=!MXs(t);return e&&(i||r==!1)?AXs(e,t):t}var Wzp=ui(lMa(),1),Hzp=ui(require("http"),1),$zp=ui(require("https"),1),Gzp=ui(require("util"),1),Qzp=ui(AYs(),1),Rfi=ui(require("zlib"),1);var C$i="1.10.0";function AMa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var lOD=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function qXs(e,t,r){let i=r&&r.Blob||hA.classes.Blob,n=AMa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=lOD.exec(e);if(!a)throw new Up("Invalid URL",Up.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 Up("Blob is not supported",Up.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new Up("Unsupported protocol "+n,Up.ERR_NOT_SUPPORT)}var I$i=ui(require("stream"),1);var Mzp=ui(require("stream"),1);var TXs=Symbol("internals"),CXs=class extends Mzp.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[TXs]={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[TXs];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[TXs],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,M=0;if(a){let D=Date.now();(!n.ts||(M=D-n.ts)>=l)&&(n.ts=D,q=s-n.bytes,n.bytes=q<0?-q:0,M=0),q=s-n.bytes}if(a){if(q<=0)return setTimeout(()=>{O(null,g)},l-M);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)})}},BXs=CXs;var Jzp=require("events");var qzp=ui(require("util"),1),Tzp=require("stream");var{asyncIterator:Azp}=Symbol,fOD=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[Azp]?yield*e[Azp]():yield e},G7o=fOD;var dOD=hA.ALPHABET.ALPHA_DIGIT+"-_",qMa=typeof TextEncoder=="function"?new TextEncoder:new qzp.default.TextEncoder,B$i=`\r
|
|
1718
1718
|
`,pOD=qMa.encode(B$i),_OD=2,IXs=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)}"`:""}${B$i}`;n?r=qMa.encode(String(r).replace(/\r?\n|\r\n?/g,B$i)):a+=`Content-Type: ${r.type||"application/octet-stream"}${B$i}`,this.headers=qMa.encode(a+B$i),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+_OD,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;os.isTypedArray(t)?yield t:yield*G7o(t),yield pOD}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},hOD=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+hA.generateString(n,dOD)}=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=qMa.encode("--"+a+B$i),l=qMa.encode("--"+a+"--"+B$i),d=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new IXs(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),Tzp.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},Czp=hOD;var Bzp=ui(require("stream"),1),zXs=class extends Bzp.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)}},Izp=zXs;var yOD=(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,zzp=yOD;function vOD(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 xzp=vOD;function bOD(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 Rzp=bOD;var xfi=(e,t,r=3)=>{let i=0,n=xzp(50,250);return Rzp(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)},T3n=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},C3n=e=>(...t)=>os.asap(()=>e(...t));var Nzp={flush:Rfi.default.constants.Z_SYNC_FLUSH,finishFlush:Rfi.default.constants.Z_SYNC_FLUSH},gOD={flush:Rfi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:Rfi.default.constants.BROTLI_OPERATION_FLUSH},Fzp=os.isFunction(Rfi.default.createBrotliDecompress),{http:OOD,https:mOD}=Qzp.default,POD=/https:?/,Lzp=hA.protocols.map(e=>e+":"),Uzp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function jOD(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function Kzp(e,t,r){let i=t;if(!i&&i!==!1){let n=Wzp.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){Kzp(a,t,a.href)}}var wOD=typeof process<"u"&&os.kindOf(process)==="process",SOD=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)}),DOD=({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)}},Vzp=(e,t)=>DOD(os.isObject(e)?e:{address:e,family:t}),Yzp=wOD&&function(t){return SOD(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=zzp(l,Ue=>os.isArray(Ue)?Ue:[Ue]);l=(Ue,bt,De)=>{Oe(Ue,bt,(Te,xt,Pe)=>{if(Te)return De(Te);let ot=os.isArray(xt)?xt.map(at=>Vzp(at)):[Vzp(xt,Pe)];bt.all?De(Te,ot):De(Te,ot[0].address,ot[0].family)})}}let m=new Jzp.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 nMe(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=T$i(t.baseURL,t.url,t.allowAbsoluteUrls),M=new URL(q,hA.hasBrowserEnv?hA.origin:void 0),D=M.protocol||Lzp[0];if(D==="data:"){let Oe;if(c!=="GET")return _rr(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{Oe=qXs(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Ue){throw Up.from(Ue,Up.ERR_BAD_REQUEST,t)}return s==="text"?(Oe=Oe.toString(o),(!o||o==="utf8")&&(Oe=os.stripBOM(Oe))):s==="stream"&&(Oe=I$i.default.Readable.from(Oe)),_rr(i,n,{data:Oe,status:200,statusText:"OK",headers:new hR,config:t})}if(Lzp.indexOf(D)===-1)return n(new Up("Unsupported protocol "+D,Up.ERR_BAD_REQUEST,t));let C=hR.from(t.headers).normalize();C.set("User-Agent","axios/"+C$i,!1);let{onUploadProgress:x,onDownloadProgress:G}=t,I=t.maxRate,F,V;if(os.isSpecCompliantForm(u)){let Oe=C.getContentType(/boundary=([-_\w\d]{10,70})/i);u=Czp(u,Ue=>{C.set(Ue)},{tag:`axios-${C$i}-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 Gzp.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=I$i.default.Readable.from(G7o(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 Up("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Up.ERR_BAD_REQUEST,t));if(C.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new Up("Request body larger than maxBodyLength limit",Up.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=I$i.default.Readable.from(u,{objectMode:!1})),u=I$i.default.pipeline([u,new BXs({maxRate:os.toFiniteNumber(F)})],os.noop),x&&u.on("progress",Uzp(u,T3n(K,xfi(C3n(x),!1,3)))));let Y;if(t.auth){let Oe=t.auth.username||"",Ue=t.auth.password||"";Y=Oe+":"+Ue}if(!Y&&M.username){let Oe=M.username,Ue=M.password;Y=Oe+":"+Ue}Y&&C.delete("authorization");let Z;try{Z=q$i(M.pathname+M.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"+(Fzp?", 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:jOD,beforeRedirects:{}};!os.isUndefined(l)&&(oe.lookup=l),t.socketPath?oe.socketPath=t.socketPath:(oe.hostname=M.hostname.startsWith("[")?M.hostname.slice(1,-1):M.hostname,oe.port=M.port,Kzp(oe,t.proxy,D+"//"+M.hostname+(M.port?":"+M.port:"")+oe.path));let pe,de=POD.test(oe.protocol);if(oe.agent=de?t.httpsAgent:t.httpAgent,t.transport?pe=t.transport:t.maxRedirects===0?pe=de?$zp.default:Hzp.default:(t.maxRedirects&&(oe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(oe.beforeRedirects.config=t.beforeRedirect),pe=de?mOD:OOD),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 bt=[Ue],De=+Ue.headers["content-length"];if(G||V){let at=new BXs({maxRate:os.toFiniteNumber(V)});G&&at.on("progress",Uzp(at,T3n(De,xfi(C3n(G),!0,3)))),bt.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":bt.push(Rfi.default.createUnzip(Nzp)),delete Ue.headers["content-encoding"];break;case"deflate":bt.push(new Izp),bt.push(Rfi.default.createUnzip(Nzp)),delete Ue.headers["content-encoding"];break;case"br":Fzp&&(bt.push(Rfi.default.createBrotliDecompress(gOD)),delete Ue.headers["content-encoding"])}Te=bt.length>1?I$i.default.pipeline(bt,os.noop):bt[0];let Pe=I$i.default.finished(Te,()=>{Pe(),w()}),ot={status:Ue.statusCode,statusText:Ue.statusMessage,headers:new hR(Ue.headers),config:t,request:xt};if(s==="stream")ot.data=Te,_rr(i,n,ot);else{let at=[],me=0;Te.on("data",function(wt){at.push(wt),me+=wt.length,t.maxContentLength>-1&&me>t.maxContentLength&&(g=!0,Te.destroy(),n(new Up("maxContentLength size of "+t.maxContentLength+" exceeded",Up.ERR_BAD_RESPONSE,t,xt)))}),Te.on("aborted",function(){if(g)return;let wt=new Up("stream has been aborted",Up.ERR_BAD_RESPONSE,t,xt);Te.destroy(wt),n(wt)}),Te.on("error",function(wt){O.destroyed||n(Up.from(wt,null,t,xt))}),Te.on("end",function(){try{let wt=at.length===1?at[0]:Buffer.concat(at);s!=="arraybuffer"&&(wt=wt.toString(o),(!o||o==="utf8")&&(wt=os.stripBOM(wt))),ot.data=wt}catch(wt){return n(Up.from(wt,null,t,ot.request,ot))}_rr(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(Up.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 Up("error trying to parse `config.timeout` to int",Up.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(Oe,function(){if(b)return;let bt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",De=t.transitional||M3n;t.timeoutErrorMessage&&(bt=t.timeoutErrorMessage),n(new Up(bt,De.clarifyTimeoutError?Up.ETIMEDOUT:Up.ECONNABORTED,t,O)),E()})}if(os.isStream(u)){let Oe=!1,Ue=!1;u.on("end",()=>{Oe=!0}),u.once("error",bt=>{Ue=!0,O.destroy(bt)}),u.on("close",()=>{!Oe&&!Ue&&E(new nMe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var Xzp=hA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,hA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(hA.origin),hA.navigator&&/(msie|trident)/i.test(hA.navigator.userAgent)):()=>!0;var Zzp=hA.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 kzp=e=>e instanceof hR?{...e}:e;function AWt(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(kzp(s),kzp(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 Q7o=e=>{let t=AWt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=hR.from(u),t.url=q$i(T$i(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(hA.hasStandardBrowserEnv||hA.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(hA.hasStandardBrowserEnv&&(i&&os.isFunction(i)&&(i=i(t)),i||i!==!1&&Xzp(t.url))){let s=n&&a&&Zzp.read(a);s&&u.set(n,s)}return t};var EOD=typeof XMLHttpRequest<"u",exp=EOD&&function(e){return new Promise(function(r,i){let n=Q7o(e),a=n.data,u=hR.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 M=hR.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),C={data:!l||l==="text"||l==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:M,config:e,request:w};_rr(function(G){r(G),m()},function(G){i(G),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 Up("Request aborted",Up.ECONNABORTED,e,w)),w=null)},w.onerror=function(){i(new Up("Network Error",Up.ERR_NETWORK,e,w)),w=null},w.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",C=n.transitional||M3n;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new Up(D,C.clarifyTimeoutError?Up.ETIMEDOUT:Up.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]=xfi(s,!0),w.addEventListener("progress",b)),d&&w.upload&&([c,g]=xfi(d),w.upload.addEventListener("progress",c),w.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=M=>{w&&(i(!M||M.type?new nMe(null,e,w):M),w.abort(),w=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let q=AMa(n.url);if(q&&hA.protocols.indexOf(q)===-1){i(new Up("Unsupported protocol "+q+":",Up.ERR_BAD_REQUEST,e));return}w.send(a||null)})};var MOD=(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 Up?o:new nMe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new Up(`timeout ${t} of ms exceeded`,Up.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}},txp=MOD;var AOD=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},qOD=async function*(e,t){for await(let r of TOD(e))yield*AOD(r,t)},TOD=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()}},xXs=(e,t,r,i)=>{let n=qOD(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 K7o=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",ixp=K7o&&typeof ReadableStream=="function",COD=K7o&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),nxp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},BOD=ixp&&nxp(()=>{let e=!1,t=new Request(hA.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),rxp=64*1024,RXs=ixp&&nxp(()=>os.isReadableStream(new Response("").body)),J7o={stream:RXs&&(e=>e.body)};K7o&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!J7o[t]&&(J7o[t]=os.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new Up(`Response type '${t}' is not supported`,Up.ERR_NOT_SUPPORT,i)})})})(new Response);var IOD=async e=>{if(e==null)return 0;if(os.isBlob(e))return e.size;if(os.isSpecCompliantForm(e))return(await new Request(hA.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 COD(e)).byteLength},zOD=async(e,t)=>{let r=os.toFiniteNumber(e.getContentLength());return r??IOD(t)},axp=K7o&&(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}=Q7o(e);s=s?(s+"").toLowerCase():"text";let g=txp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),w;try{if(d&&BOD&&r!=="get"&&r!=="head"&&(w=await zOD(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[G,I]=T3n(w,xfi(C3n(d)));i=xXs(C.body,rxp,G,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),M=RXs&&(s==="stream"||s==="response");if(RXs&&(l||M&&m)){let C={};["status","statusText","headers"].forEach(F=>{C[F]=q[F]});let x=os.toFiniteNumber(q.headers.get("content-length")),[G,I]=l&&T3n(x,xfi(C3n(l),!0))||[];q=new Response(xXs(q.body,rxp,G,()=>{I&&I(),m&&m()}),C)}s=s||"text";let D=await J7o[os.findKey(J7o,s)||"text"](q,e);return!M&&m&&m(),await new Promise((C,x)=>{_rr(C,x,{data:D,headers:hR.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 Up("Network Error",Up.ERR_NETWORK,e,O),{cause:E.cause||E}):Up.from(E,E&&E.code,e,O)}});var NXs={http:Yzp,xhr:exp,fetch:axp};os.forEach(NXs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var oxp=e=>`- ${e}`,xOD=e=>os.isFunction(e)||e===null||e===!1,Y7o={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,!xOD(r)&&(i=NXs[(u=String(r)).toLowerCase()],i===void 0))throw new Up(`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 :
|
|
@@ -1954,7 +1954,7 @@ ${M}${q}${D}${sXp.default.cursorHide}`});var gBa=ui(c1i(),1);function $sc(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.`),I3n(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function rcc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!CXp(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 l$D(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?I3n(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function l$D(e){let r=await new TXp.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 f$D({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await IXp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=s1i(o.name,c),g=await Pkt({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 IXp({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=s1i(s.name,o),b=await Pkt({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 IXp({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 eWt({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 zXp(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=Hae(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 zVo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await f$D({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(...zXp(s,d,t.logger));else u.push(...zXp(l.versions,void 0,t.logger))}return u}var EBa=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 B2n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var icc=(()=>{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})(),xXp=typeof globalThis.AbortController=="function",RXp=typeof globalThis.ReadableStream=="function",NXp=typeof globalThis.FormData=="function",xVo=["get","post","put","patch","head","delete"],d$D=()=>{};d$D();var FXp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},RVo=2147483647,LXp=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,NVo=Symbol("stop"),UXp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},VXp={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 p$D=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=LXp,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},WXp=(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})},HXp=(e,t)=>{let r=p$D(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 I2n=e=>e!==null&&typeof e=="object";var MBa=(...e)=>{for(let t of e)if((!I2n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return occ({},...e)},ncc=(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 FVo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:occ(e[r]??[],t[r]??[])}var acc=(e={},t={})=>({beforeRequest:FVo(e,t,"beforeRequest"),beforeRetry:FVo(e,t,"beforeRetry"),afterResponse:FVo(e,t,"afterResponse"),beforeError:FVo(e,t,"beforeError")}),occ=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(I2n(n)){for(let[a,u]of Object.entries(n))I2n(u)&&a in t&&(u=occ(t[a],u)),t={...t,[a]:u};I2n(n.hooks)&&(i=acc(i,n.hooks),t.hooks=i),I2n(n.headers)&&(r=ncc(r,n.headers),t.headers=r)}return t};var GXp=e=>xVo.includes(e)?e.toUpperCase():e,_$D=["get","put","head","delete","options","trace"],h$D=[408,413,429,500,502,503,504],y$D=[413,429,503],$Xp={limit:2,methods:_$D,statusCodes:h$D,afterStatusCodes:y$D,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},QXp=(e={})=>{if(typeof e=="number")return{...$Xp,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{...$Xp,...e}};async function ucc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new B2n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function scc(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 JXp=(e,t)=>{let r={};for(let i in t)!(i in VXp)&&!(i in UXp)&&!(i in e)&&(r[i]=t[i]);return r};var ABa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>RVo)throw new RangeError(`The \`timeout\` option cannot be greater than ${RVo}`);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 EBa(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(!RXp)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return WXp(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(FXp))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:ncc(this._input.headers,r.headers),hooks:acc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:GXp(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:QXp(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(xXp){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(icc&&(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);(NXp&&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(!icc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=HXp(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof B2n)throw t;if(t instanceof EBa){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),RVo);if(this._retryCount<1)throw r;await scc(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})===NVo)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=JXp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):ucc(r,t,this.abortController,this._options)}};var ccc=e=>{let t=(r,i)=>ABa.create(r,MBa(e,i));for(let r of xVo)t[r]=(i,n)=>ABa.create(i,MBa(e,n,{method:r}));return t.create=r=>ccc(MBa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),ccc(MBa(e,r))),t.stop=NVo,t},v$D=ccc(),KXp=v$D;var bZp=ui(vZp(),1);function _cc(e){let t=(0,bZp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var dkp=ui(fkp(),1),pkp=ui(c1i(),1),Ecc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Mcc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Acc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??_cc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,dkp.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 KXp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new Ecc(e):c}if(t.allVersions)return s;let o=new Mcc(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=pkp.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 zBa(e,t){let{version:r}=await Acc(e.toLowerCase(),t);return r}async function aMi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:zBa(e.packageName,{version:t?"prerelease":"latest"})}var _kp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],XVo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=eb.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new IVo(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.65.41"}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 m9}failWithoutThrowing(t,r){this.didSucceed=!1,qVo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await S3n()).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 BXp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1957
|
+
`,i?I3n(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function l$D(e){let r=await new TXp.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 f$D({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await IXp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=s1i(o.name,c),g=await Pkt({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 IXp({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=s1i(s.name,o),b=await Pkt({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 IXp({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 eWt({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 zXp(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=Hae(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 zVo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await f$D({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(...zXp(s,d,t.logger));else u.push(...zXp(l.versions,void 0,t.logger))}return u}var EBa=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 B2n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var icc=(()=>{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})(),xXp=typeof globalThis.AbortController=="function",RXp=typeof globalThis.ReadableStream=="function",NXp=typeof globalThis.FormData=="function",xVo=["get","post","put","patch","head","delete"],d$D=()=>{};d$D();var FXp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},RVo=2147483647,LXp=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,NVo=Symbol("stop"),UXp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},VXp={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 p$D=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=LXp,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},WXp=(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})},HXp=(e,t)=>{let r=p$D(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 I2n=e=>e!==null&&typeof e=="object";var MBa=(...e)=>{for(let t of e)if((!I2n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return occ({},...e)},ncc=(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 FVo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:occ(e[r]??[],t[r]??[])}var acc=(e={},t={})=>({beforeRequest:FVo(e,t,"beforeRequest"),beforeRetry:FVo(e,t,"beforeRetry"),afterResponse:FVo(e,t,"afterResponse"),beforeError:FVo(e,t,"beforeError")}),occ=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(I2n(n)){for(let[a,u]of Object.entries(n))I2n(u)&&a in t&&(u=occ(t[a],u)),t={...t,[a]:u};I2n(n.hooks)&&(i=acc(i,n.hooks),t.hooks=i),I2n(n.headers)&&(r=ncc(r,n.headers),t.headers=r)}return t};var GXp=e=>xVo.includes(e)?e.toUpperCase():e,_$D=["get","put","head","delete","options","trace"],h$D=[408,413,429,500,502,503,504],y$D=[413,429,503],$Xp={limit:2,methods:_$D,statusCodes:h$D,afterStatusCodes:y$D,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},QXp=(e={})=>{if(typeof e=="number")return{...$Xp,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{...$Xp,...e}};async function ucc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new B2n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function scc(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 JXp=(e,t)=>{let r={};for(let i in t)!(i in VXp)&&!(i in UXp)&&!(i in e)&&(r[i]=t[i]);return r};var ABa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>RVo)throw new RangeError(`The \`timeout\` option cannot be greater than ${RVo}`);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 EBa(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(!RXp)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return WXp(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(FXp))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:ncc(this._input.headers,r.headers),hooks:acc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:GXp(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:QXp(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(xXp){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(icc&&(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);(NXp&&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(!icc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=HXp(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof B2n)throw t;if(t instanceof EBa){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),RVo);if(this._retryCount<1)throw r;await scc(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})===NVo)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=JXp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):ucc(r,t,this.abortController,this._options)}};var ccc=e=>{let t=(r,i)=>ABa.create(r,MBa(e,i));for(let r of xVo)t[r]=(i,n)=>ABa.create(i,MBa(e,n,{method:r}));return t.create=r=>ccc(MBa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),ccc(MBa(e,r))),t.stop=NVo,t},v$D=ccc(),KXp=v$D;var bZp=ui(vZp(),1);function _cc(e){let t=(0,bZp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var dkp=ui(fkp(),1),pkp=ui(c1i(),1),Ecc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Mcc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Acc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??_cc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,dkp.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 KXp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new Ecc(e):c}if(t.allVersions)return s;let o=new Mcc(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=pkp.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 zBa(e,t){let{version:r}=await Acc(e.toLowerCase(),t);return r}async function aMi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:zBa(e.packageName,{version:t?"prerelease":"latest"})}var _kp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],XVo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=eb.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new IVo(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.65.42"}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 m9}failWithoutThrowing(t,r){this.didSucceed=!1,qVo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await S3n()).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 BXp({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=zzs(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 OBa(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 m9}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await S3n()).sendEvent(t)}logger=xXt((t,...r)=>this.log(t,...r));stderr=xXt((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=hkp(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?hkp(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=_kp[this.numTasks++%_kp.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===FB.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=>Owi.indexOf(n.level)>=Owi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===eb.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 aMi({cliEnvironment:this.environment,includePreReleases:t}),i=Hae(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await zVo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await Lsc({message:t,default:r})}async getInput(t){return await Usc({message:t.message,default:t.default})}};function hkp(e){return`[${e}]:`}var HO_=require("fs/promises");function gFe({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 Hh_=require("fs/promises");var lHt=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 SMe=class extends lHt{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 xBa=class{context;constructor(t){this.context=t}};var ZVo=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let d=n!=null?ty.of(`${n}${bVt}${u}`):ty.of(u);t[d]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${bVt}${u}`:u,d=i.directories[u];r(d,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(bVt))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[ty.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 oJi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new ZVo,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"]))ykp(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(ykp(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??h_((Dxe(r)+"/"+AVi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===ty.of(kF))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=GOo(Dxe(AIn.of(`/${t}`)),AIn.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=GOo(Dxe(AIn.of(`/${t}`)),AIn.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===ty.of(kF))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=>T2(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=LN(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:LN(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:LN(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===J1?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 ykp(e){return e?.header!=null}var oJ={openapi:e=>({...e,type:"openapi",_visit:function(t){return oJ._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return oJ._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 U2n={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return U2n._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var nL={basic:e=>({...e,type:"basic",_visit:function(t){return nL._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return nL._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return nL._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return nL._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return nL._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 Rg={primitive:e=>({value:e,type:"primitive",_visit:function(t){return Rg._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Rg._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return Rg._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return Rg._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return Rg._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return Rg._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Rg._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return Rg._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 a_={int:e=>({value:e,type:"int",_visit:function(t){return a_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return a_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return a_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return a_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return a_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return a_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return a_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return a_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return a_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return a_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return a_._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 V2n={boolean:e=>({value:e,type:"boolean",_visit:function(t){return V2n._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return V2n._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 oMi={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return oMi._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return oMi._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 ZW={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case ZW.GenerallyAvailable:return t.generallyAvailable();case ZW.Beta:return t.beta();case ZW.Deprecated:return t.deprecated();default:return t._other()}}};var OFe={cursor:e=>({...e,type:"cursor",_visit:function(t){return OFe._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return OFe._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return OFe._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 Tdi={language:e=>({...e,type:"language",_visit:function(t){return Tdi._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return Tdi._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 kW={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 kW.Curl:return t.curl();case kW.Python:return t.python();case kW.Javascript:return t.javascript();case kW.Typescript:return t.typescript();case kW.Go:return t.go();case kW.Ruby:return t.ruby();case kW.Csharp:return t.csharp();case kW.Java:return t.java();case kW.Js:return t.js();case kW.Node:return t.node();case kW.Ts:return t.ts();case kW.Nodets:return t.nodets();case kW.Golang:return t.golang();case kW.Dotnet:return t.dotnet();case kW.Jvm:return t.jvm();default:return t._other()}}};var fHt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return fHt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return fHt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"unknown":return t.unknown(e.value);case"full":return t.full(e);default:return t._other(e)}}};var dHt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return dHt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return dHt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"withStreaming":return t.withStreaming(e);case"withoutStreaming":return t.withoutStreaming(e.value);default:return t._other(e)}}};var eH={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case eH.Get:return t.get();case eH.Post:return t.post();case eH.Put:return t.put();case eH.Patch:return t.patch();case eH.Delete:return t.delete();case eH.Head:return t.head();case eH.Options:return t.options();case eH.Trace:return t.trace();default:return t._other()}}};var uMi={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return uMi._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return uMi._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return uMi._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 Cdi={file:e=>({...e,type:"file",_visit:function(t){return Cdi._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return Cdi._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 uJ={file:e=>({...e,type:"file",_visit:function(t){return uJ._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return uJ._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return uJ._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return uJ._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return uJ._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return uJ._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return uJ._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 Zy={primitive:e=>({...e,type:"primitive",_visit:function(t){return Zy._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Zy._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Zy._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Zy._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Zy._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Zy._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Zy._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Zy._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Zy._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Zy._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Zy._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 ow={int:e=>({...e,type:"int",_visit:function(t){return ow._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return ow._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return ow._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return ow._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return ow._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return ow._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return ow._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return ow._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return ow._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return ow._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return ow._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 Oz={boolean:e=>({value:e,type:"boolean",_visit:function(t){return Oz._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Oz._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 Bdi={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Bdi._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Bdi._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 DMe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return DMe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return DMe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return DMe._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 MC={file:e=>({...e,type:"file",_visit:function(t){return MC._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return MC._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return MC._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return MC._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return MC._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return MC._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return MC._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 El={primitive:e=>({...e,type:"primitive",_visit:function(t){return El._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return El._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return El._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return El._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return El._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return El._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return El._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return El._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return El._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return El._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return El._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 KZ={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return KZ._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return KZ._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 rp={int:e=>({...e,type:"int",_visit:function(t){return rp._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return rp._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return rp._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return rp._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return rp._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return rp._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return rp._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return rp._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return rp._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return rp._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return rp._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 Rv={};mo(Rv,{AllOfPropertyConflict:()=>f8n,ArraySchema:()=>_Ho,ArraySchemaWithExample:()=>VHo,Availability:()=>sWo,Base64WithExample:()=>RHo,BasicSecurityScheme:()=>fWo,BearerSecurityScheme:()=>dWo,BooleanSchema:()=>sHo,BooleanWithExample:()=>NHo,BytesResponse:()=>r8n,CasingOverrides:()=>hWo,CommonProperty:()=>PHo,CommonPropertyWithExample:()=>XHo,CursorPagination:()=>$Wo,CustomCodeSample:()=>WWo,CustomCodeSampleLanguage:()=>LWo,CustomCodeSampleSdk:()=>VWo,CustomPagination:()=>QWo,DateWithExample:()=>xHo,DatetimeWithExample:()=>zHo,DiscriminatedOneOfSchema:()=>OHo,DiscriminatedOneOfSchemaWithExample:()=>KHo,DoubleSchema:()=>oHo,DoubleWithExample:()=>BHo,Encoding:()=>uWo,Endpoint:()=>JWo,EndpointExample:()=>o8n,EndpointResponseExample:()=>FWo,EndpointSdkName:()=>uir,EndpointWithExample:()=>Gkp,EnumSchema:()=>G2n,EnumSchemaWithExample:()=>LHo,EnumValue:()=>lMi,ErrorExample:()=>IWo,FernExample:()=>xWo,FileResponse:()=>e8n,FileSchema:()=>EWo,FloatWithExample:()=>CHo,FullEndpointExample:()=>HWo,FullExample:()=>Yq,FullObjectExample:()=>PWo,FullOneOfExample:()=>wWo,GlobalHeader:()=>lHo,Header:()=>dMi,HeaderExample:()=>a8n,HeaderSecurityScheme:()=>pWo,HeaderWithExample:()=>hMi,HttpEndpointServer:()=>i8n,HttpError:()=>zWo,HttpErrorWithExample:()=>EHo,HttpMethod:()=>K2n,IdempotencyHeader:()=>fHo,Int64WithExample:()=>AHo,IntSchema:()=>nHo,IntWithExample:()=>MHo,JsonRequest:()=>TWo,JsonRequestWithExample:()=>wHo,JsonResponse:()=>t8n,JsonResponseWithExample:()=>_8n,KeyValuePair:()=>jWo,LiteralExample:()=>mWo,LiteralSchema:()=>l8n,LiteralSchemaValue:()=>dHo,LongSchema:()=>aHo,MapSchema:()=>hHo,MapSchemaWithExample:()=>WHo,MultipartRequest:()=>k2n,MultipartRequestProperty:()=>qWo,MultipartRequestPropertyEncoding:()=>AWo,MultipartSchema:()=>MWo,NamedFullExample:()=>cir,Namespace:()=>yWo,NamespaceId:()=>OWo,NullableSchema:()=>vHo,NullableSchemaWithExample:()=>$Ho,OauthSecurityScheme:()=>bWo,ObjectProperty:()=>gHo,ObjectPropertyConflictInfo:()=>d8n,ObjectPropertyWithExample:()=>JHo,ObjectSchema:()=>pHo,ObjectSchemaWithExample:()=>GHo,OctetStreamRequest:()=>Z2n,OffsetPagination:()=>GWo,OneOfSchema:()=>bHo,OneOfSchemaWithExample:()=>QHo,OpenApiIntermediateRepresentation:()=>Hkp,OpenApiSource:()=>iWo,OptionalSchema:()=>yHo,OptionalSchemaWithExample:()=>HHo,Pagination:()=>u8n,PathParameter:()=>Y2n,PathParameterExample:()=>RWo,PathParameterWithExample:()=>jHo,PrimitiveExample:()=>J2n,PrimitiveSchema:()=>_Mi,PrimitiveSchemaValue:()=>cHo,PrimitiveSchemaValueWithExample:()=>FHo,PrimitiveSchemaWithExample:()=>h8n,PropertyKey:()=>Q2n,ProtobufEncoding:()=>oWo,ProtobufSource:()=>nWo,QueryParameter:()=>X2n,QueryParameterExample:()=>n8n,QueryParameterWithExample:()=>p8n,QuerySecurityScheme:()=>_Wo,ReferencedSchema:()=>sir,Request:()=>CWo,RequestWithExample:()=>SHo,Response:()=>BWo,ResponseWithExample:()=>DHo,Schema:()=>Tm,SchemaId:()=>YZ,SchemaWithExample:()=>OA,Schemas:()=>iHo,SdkGroup:()=>vWo,SdkGroupInfo:()=>SWo,SdkGroupName:()=>fMi,SecurityScheme:()=>gWo,SecuritySchemeId:()=>lWo,Server:()=>LBa,Source:()=>aWo,StatusCode:()=>oir,StreamingResponseExample:()=>NWo,StringSchema:()=>uHo,StringSchemaWithExample:()=>IHo,SupportedSdkLanguage:()=>UWo,Tag:()=>cWo,TagId:()=>XZ,Tags:()=>DWo,TextResponse:()=>pMi,Uint64WithExample:()=>THo,UintWithExample:()=>qHo,UnDiscriminatedOneOfSchema:()=>mHo,UnDiscriminatedOneOfSchemaWithExample:()=>YHo,UnknownSchemaWithExample:()=>UHo,Webhook:()=>KWo,WebhookExampleCall:()=>c8n,WebhookHttpMethod:()=>s8n,WebhookWithExample:()=>Qkp,WebsocketChannel:()=>rHo,WebsocketHandshake:()=>YWo,WebsocketHandshakeWithExample:()=>$kp,WebsocketMessageExample:()=>eHo,WebsocketMessageOrigin:()=>XWo,WebsocketMessageSchema:()=>ZWo,WebsocketServer:()=>kWo,WebsocketSessionExample:()=>tHo,WithAvailability:()=>xh,WithDescription:()=>Of,WithEncoding:()=>$ae,WithInline:()=>ZE,WithName:()=>L0,WithNamespace:()=>c0,WithSdkGroupName:()=>_m,WithSource:()=>ny,WithStatusCode:()=>mFe,WithTitle:()=>pm,commons:()=>Icc,example:()=>zcc,finalIr:()=>xcc,parseIr:()=>Rcc});var Icc={};mo(Icc,{BasicSecurityScheme:()=>fWo,BearerSecurityScheme:()=>dWo,Encoding:()=>uWo,HeaderSecurityScheme:()=>pWo,Namespace:()=>yWo,NamespaceId:()=>OWo,OauthSecurityScheme:()=>bWo,OpenApiSource:()=>iWo,ProtobufEncoding:()=>oWo,ProtobufSource:()=>nWo,QuerySecurityScheme:()=>_Wo,SchemaId:()=>YZ,SdkGroup:()=>vWo,SdkGroupName:()=>fMi,SecurityScheme:()=>gWo,SecuritySchemeId:()=>lWo,Server:()=>LBa,Source:()=>aWo,StatusCode:()=>oir,Tag:()=>cWo,TagId:()=>XZ,WithAvailability:()=>xh,WithDescription:()=>Of,WithEncoding:()=>$ae,WithInline:()=>ZE,WithName:()=>L0,WithNamespace:()=>c0,WithSdkGroupName:()=>_m,WithSource:()=>ny,WithStatusCode:()=>mFe,WithTitle:()=>pm});var Mt={};mo(Mt,{JsonError:()=>W2n,ParseError:()=>H2n,any:()=>Tkp,bigint:()=>bkp,boolean:()=>Ckp,booleanLiteral:()=>qkp,date:()=>gkp,discriminant:()=>Ukp,enum_:()=>eWo,getObjectLikeUtils:()=>pHt,getObjectUtils:()=>uJi,getSchemaUtils:()=>Kq,isProperty:()=>cMi,lazy:()=>Okp,lazyObject:()=>Ekp,list:()=>rWo,number:()=>Bkp,object:()=>tWo,objectWithoutOptionalProperties:()=>Dkp,optional:()=>qcc,property:()=>Pkp,record:()=>Rkp,set:()=>Nkp,string:()=>Ikp,stringLiteral:()=>Akp,transform:()=>Tcc,undiscriminatedUnion:()=>Lkp,union:()=>Wkp,unknown:()=>zkp,withParsedProperties:()=>Bcc});var zj={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 gA(e,t){return`Expected ${t}. Received ${jGD(e)}.`}function jGD(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 aL(e){return{...e,json:vkp(e.json),parse:vkp(e.parse)}}function vkp(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(`
|
|
@@ -2046,7 +2046,7 @@ ${a}]`:`[${e.join(u)}]`},etu=(e,t,r)=>`let ${e} = ${SPc(t,r)}`,SPc=(e,t,r)=>{swi
|
|
|
2046
2046
|
`)}];if(t["base-properties"]!=null){let M=Object.fromEntries(Object.entries(c).filter(([C])=>t["base-properties"]?.[C]!=null)),D=_Yi({typeName:e,typeNameForBreadcrumb:e,rawObject:{properties:t["base-properties"]},file:a,example:M,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 jx_(c);let O=i.resolveType({type:g,file:a});if(O==null)return[];if(O._type==="named"&&GS(O.declaration)){let M=Object.fromEntries(Object.entries(c).filter(([D])=>t["base-properties"]?.[D]==null));return _Yi({typeName:e,typeNameForBreadcrumb:e,rawObject:O.declaration,file:O.file,example:M,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(...OL({rawTypeReference:g,example:w,typeResolver:i,exampleResolver:n,file:a,workspace:u,breadcrumbs:l,depth:d+1})),q.push(...jx_(E)),q}function jx_(e){return Object.keys(e).map(t=>({severity:"fatal",message:`Unexpected property "${t}"`}))}function Gtu({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:d}){return _3(t,{alias:s=>yx_({rawAlias:s,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:d}),enum:s=>vx_({rawEnum:s,example:a,breadcrumbs:l}),object:s=>_Yi({typeName:e,typeNameForBreadcrumb:e,rawObject:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d}),discriminatedUnion:s=>wx_({typeName:e,rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d}),undiscriminatedUnion:s=>bx_({rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d})})}var Bx_=/^([+-]?\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)?)?)?)?$/,V8E=/^[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}$/,W8E=/^\d{4}-\d{2}-\d{2}$/,H8E=128;function OL({rawTypeReference:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l}){if(l>H8E)return[{message:"Example is too deeply nested. This may indicate a circular reference."}];if(typeof t=="string"&&t.startsWith(jkt)){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?[]:CLn({expected:d,actual:o})?[]:[{message:`Expected example to be: ${e}. Example is ${t}.`}]}return XWi({type:e,_default:void 0,validation:void 0,visitor:{primitive:d=>$8E({primitiveType:d,example:t}),named:d=>{let s=r.getDeclarationOfNamedType({referenceToNamedType:d,file:n});return s==null?[]:Gtu({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})=>ew(t)?Object.entries(t).flatMap(([o,c])=>[...OL({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1}),...OL({rawTypeReference:s,example:c,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1})]):HFe(t,"a map"),list:d=>Array.isArray(t)?t.flatMap((s,o)=>OL({rawTypeReference:d,example:s,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${o}`],depth:l+1})):HFe(t,"a list"),set:d=>{if(!Array.isArray(t))return HFe(t,"a list");let s=vzs(t);return s.length>0?[{severity:"fatal",message:`Set has duplicate elements:
|
|
2047
2047
|
`+s.map(o=>` - ${JSON.stringify(o)}`).join(`
|
|
2048
2048
|
`)}]:t.flatMap((o,c)=>OL({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${c}`],depth:l+1}))},optional:d=>t==null?[]:OL({rawTypeReference:d,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l+1}),nullable:d=>t==null?[]:OL({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 VMe(s=>s===d.boolean,d.boolean.toString())(t);case"string":return VMe(s=>s===d.string,`"${d.string}"`)(t);default:wo(d)}}}})}function $8E({primitiveType:e,example:t}){return e.v2!=null?Md._visit(e.v2,{integer:r=>G8E({example:t,rules:r.validation}),long:()=>Mx_(t),uint:()=>Sx_(t),uint64:()=>Dx_(t),double:r=>Q8E({example:t,rules:r.validation}),float:()=>Ex_(t),boolean:()=>Ax_(t),string:r=>J8E({example:t,rules:r.validation}),uuid:()=>qx_(t),date:()=>Cx_(t),dateTime:()=>Tx_(t),base64:()=>TLn(t),bigInteger:()=>TLn(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):Gh._visit(e.v1,{integer:()=>Ix_(t),long:()=>Mx_(t),uint:()=>Sx_(t),uint64:()=>Dx_(t),double:()=>zx_(t),float:()=>Ex_(t),boolean:()=>Ax_(t),string:()=>TLn(t),uuid:()=>qx_(t),dateTime:()=>Tx_(t),date:()=>Cx_(t),base64:()=>TLn(t),bigInteger:()=>TLn(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function G8E({example:e,rules:t}){let r=Ix_(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 Q8E({example:e,rules:t}){let r=zx_(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 J8E({example:e,rules:t}){let r=TLn(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 TLn=VMe(e=>typeof e=="string","a string"),Ix_=VMe(e=>Number.isInteger(e),"an integer"),Sx_=VMe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),Dx_=VMe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),Ex_=VMe(e=>typeof e=="number","a float"),zx_=VMe(e=>typeof e=="number","a double"),Mx_=VMe(e=>Number.isInteger(e),"an integer"),Ax_=VMe(e=>typeof e=="boolean","a boolean"),qx_=VMe(e=>typeof e=="string"&&V8E.test(e),"a UUID"),Tx_=VMe(e=>typeof e=="string"&&Bx_.test(e),"an ISO 8601 timestamp"),Cx_=VMe(e=>typeof e=="string"&&W8E.test(e)&&Bx_.test(e),"a date");function VMe(e,t){return r=>e(r)?[]:HFe(r,t)}function CLn({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&&CLn({expected:e.container.itemType,actual:t.container.itemType});case"optional":return CLn({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="optional"?t.container.itemType:t});case"nullable":return CLn({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&&CLn({expected:e.container.keyType,actual:t.container.keyType})&&CLn({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:K8E({expected:e.container.literal,actual:t.container.literal});default:wo(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;wo(e)}function K8E({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:wo(e)}}function Qtu({_enum:e,file:t}){let r=e.enum.map(n=>({...SJ(n),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof n=="string"?n:n.value,name:BLn(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 xx_(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 BLn(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function O1c({typeName:e,typeDeclaration:t,example:r,typeResolver:i,exampleResolver:n,fileContainingType:a,fileContainingExample:u,workspace:l}){return _3(t,{alias:d=>Qw.alias({value:rM({example:r,rawTypeBeingExemplified:typeof d=="string"?d:d.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l})}),object:d=>Rx_({typeName:e,rawObject:d,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l}),discriminatedUnion:d=>{let s=hYi(d);if(!ew(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 Qw.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:sqi(d).name,wireValue:s}),singleUnionType:X8E({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 Qw.enum({value:u.casingsGenerator.generateNameAndWireValue({name:xx_(r,d).name,wireValue:r})})},undiscriminatedUnion:d=>{for(let[c,b]of d.union.entries())if(OL({rawTypeReference:typeof b=="string"?b:b.type,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:l,breadcrumbs:[],depth:0}).length===0)return Qw.undiscriminatedUnion({index:c,singleUnionType:rM({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 rM({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:XWi({type:r,_default:void 0,validation:void 0,visitor:{primitive:c=>Y8E({example:l,typeBeingExemplified:c.v1}),map:({keyType:c,valueType:b})=>{if(!ew(l))throw new Error("Example is not an object");return Qh.container(Mm.map({map:Object.entries(l).map(([g,O])=>({key:rM({example:g,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}),value:rM({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 Qh.container(Mm.list({list:l.map(b=>rM({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 Qh.container(Mm.set({set:l.map(b=>rM({example:b,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})),itemType:i.parseTypeReference(c)}))},optional:c=>Qh.container(Mm.optional({optional:l!=null?rM({example:l,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}):void 0,valueType:i.parseTypeReference(c)})),nullable:c=>Qh.container(Mm.nullable({nullable:l!=null?rM({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 Qh.container(Mm.literal({literal:Ld.boolean(c.boolean)}));case"string":return Qh.container(Mm.literal({literal:Ld.string({original:c.string})}));default:wo(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 Qh.named({typeName:O,shape:O1c({typeName:O,typeDeclaration:b.declaration,fileContainingType:b.file,fileContainingExample:d,example:l,typeResolver:n,exampleResolver:a,workspace:u})})},unknown:()=>Qh.unknown(s)}}),jsonExample:s}}function Y8E({example:e,typeBeingExemplified:t}){return Gh._visit(t,{string:()=>typeof e!="string"?Qh.primitive(Ld.string({original:mh.STRING})):Qh.primitive(Ld.string({original:e})),dateTime:()=>typeof e!="string"?Qh.primitive(Ld.string({original:mh.DATE_TIME})):Qh.primitive(Ld.datetime({datetime:new Date(e),raw:e})),date:()=>typeof e!="string"?Qh.primitive(Ld.string({original:mh.DATE})):Qh.primitive(Ld.date(e)),base64:()=>typeof e!="string"?Qh.primitive(Ld.string({original:mh.BASE64})):Qh.primitive(Ld.string({original:e})),uint:()=>typeof e!="number"?Qh.primitive(Ld.uint(mh.UINT)):Qh.primitive(Ld.uint(e)),uint64:()=>typeof e!="number"?Qh.primitive(Ld.uint64(mh.UINT64)):Qh.primitive(Ld.uint64(e)),integer:()=>typeof e!="number"?Qh.primitive(Ld.integer(mh.INT)):Qh.primitive(Ld.integer(e)),float:()=>typeof e!="number"?Qh.primitive(Ld.float(mh.FLOAT)):Qh.primitive(Ld.float(e)),double:()=>typeof e!="number"?Qh.primitive(Ld.double(mh.DOUBLE)):Qh.primitive(Ld.double(e)),long:()=>typeof e!="number"?Qh.primitive(Ld.long(mh.UINT)):Qh.primitive(Ld.long(e)),boolean:()=>typeof e!="boolean"?Qh.primitive(Ld.boolean(mh.BOOLEAN)):Qh.primitive(Ld.boolean(e)),uuid:()=>typeof e!="string"?Qh.primitive(Ld.string({original:mh.UUID})):Qh.primitive(Ld.uuid(e)),bigInteger:()=>typeof e!="string"?Qh.primitive(Ld.string({original:mh.BIG_INTEGER})):Qh.primitive(Ld.string({original:e})),_other:()=>{throw new Error("Unknown primitive type: "+t)}})}function Rx_({typeName:e,rawObject:t,example:r,fileContainingType:i,fileContainingExample:n,typeResolver:a,exampleResolver:u,workspace:l}){if(!ew(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return Qw.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((d,[s,o])=>{let c=Nx_({typeName:e,wirePropertyKey:s,rawObject:t,typeResolver:a,file:i});if(c==null)return d;let b=rM({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:gL({propertyKey:s,property:c.rawPropertyType}).name,wireValue:s}),value:b,originalTypeDeclaration:c.typeName}),d},[]):[]})}function Nx_({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:i,file:n}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:n}:mNa({wirePropertyKey:t,extends_:r.extends,typeResolver:i,file:n})}function mNa({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"||!GS(u.declaration))throw new Error("Extension is not of a named object");let l=Nx_({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(l!=null)return l}}}function X8E({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:qLn({unionKey:d,rawSingleUnionType:t}).name,wireValue:d});if(e==null)return{wireDiscriminantValue:o,shape:d3.noProperties()};let c=g1c({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:n});switch(c.propertiesType){case"singleProperty":{if(!ew(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:d3.singleProperty(rM({example:u[c.name.wireValue],rawTypeBeingExemplified:e,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:i,workspace:s}))}}case"samePropertiesAsObject":{if(!ew(u))throw new Error("Example is not an object");let{[l]:b,...g}=u,O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});for(;$1i(O.declaration);)O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:typeof O.declaration=="string"?O.declaration:O.declaration.type,file:r});if(!GS(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:d3.samePropertiesAsObject({typeId:qm.generateTypeId(m),object:Rx_({rawObject:O.declaration,example:g,fileContainingType:O.file,fileContainingExample:i,typeResolver:n,exampleResolver:a,typeName:m,workspace:s})})}}default:wo(c)}}function Jtu({file:e,queryParameterKey:t,queryParameter:r}){let{name:i}=Gpi({queryParameterKey:t,queryParameter:r}),n=e.parseTypeReference(r);return{...SJ(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 Gpi({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function Fx_({service:e,endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,variableResolver:u,file:l,workspace:d}){let s=k8E({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,variableResolver:u,file:l,workspace:d});return{id:r.name??nBa(r),name:r.name!=null?l.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:n5E({file:l,service:e,endpoint:t,example:r,pathParams:s}),...s,...e5E({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:Gpi({queryParameterKey:o,queryParameter:b}).name,wireValue:o}),value:rM({example:c,rawTypeBeingExemplified:typeof b=="string"?b:b.type,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:l,fileContainingExample:l,workspace:d}),shape:Z8E({queryParameter:b})}}):[],request:t5E({endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:l,workspace:d}),response:r5E({endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,file:l,workspace:d})}}function Z8E({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?V2.exploded():V2.single()}function k8E({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=PNa({parameter:g,variableResolver:a,file:u});return{name:b,value:rM({example:O,rawTypeBeingExemplified:m.rawType,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:m.file,fileContainingExample:u,workspace:l})}};if(r["path-parameters"]!=null){let b=VHt(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 e5E({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:nnr({headerKey:s,header:c}).name,wireValue:s}),value:rM({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:nnr({headerKey:s,header:b}).name,wireValue:s}),value:rM({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 t5E({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"&&zSa(u)!=null)return;if(!oB(u))return qQ.reference(rM({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(!ew(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&&gRe(c)!=null))if(o!=null)l.push({name:n.casingsGenerator.generateNameAndWireValue({name:gL({propertyKey:d,property:o}).name,wireValue:d}),value:rM({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=mNa({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:gL({propertyKey:d,property:b.rawPropertyType}).name,wireValue:d}),value:rM({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 qQ.inlinedRequestBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t.request,file:n}).resolvedExample,properties:l})}function r5E({endpoint:e,example:t,typeResolver:r,errorResolver:i,exampleResolver:n,file:a,workspace:u}){return t.response==null?GT.ok(sB.body(void 0)):kWi(e,t.response,{body:l=>{if(l.error!=null){let d=i.getDeclarationOrThrow(l.error,a);return GT.error({error:oqi({errorName:l.error,file:a}),body:d.declaration.type!=null?rM({example:l.body,rawTypeBeingExemplified:d.declaration.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:d.file,fileContainingExample:a,workspace:u}):void 0})}return GT.ok(sB.body(i5E({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 GT.ok(sB.stream(l.stream.map(s=>{if(d!=null)return rM({example:s,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter(Ly)))},events:l=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return GT.ok(sB.sse(l.stream.map(({event:s,data:o})=>{if(d==null)return;let c=rM({example:o,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:s,data:c}}).filter(Ly)))}})}function i5E({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 rM({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})}function n5E({file:e,service:t,endpoint:r,example:i,pathParams:n}){let a=_b(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 Lx_({endpoint:e,file:t,typeResolver:r}){return{body:a5E({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}function a5E({endpoint:e,file:t,typeResolver:r}){let i=o5E({endpoint:e,file:t,typeResolver:r}),n=u5E({endpoint:e,file:t,typeResolver:r});if(i!=null&&n!=null){let a;switch(i.type){case"fileDownload":{a=mW.fileDownload({...i});break}case"json":{a=mW.json({...i.value});break}case"text":{a=mW.text({...i});break}case"bytes":{a=mW.bytes({...i});break}default:wo(i)}return Gw.streamParameter({nonStreamResponse:a,streamResponse:n})}else{if(i!=null)return i;if(n!=null)return Gw.streaming(n)}}function o5E({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 gRe(a)!=null?Gw.fileDownload({docs:n,v2Examples:void 0}):xSa(a)!=null?Gw.text({docs:n,v2Examples:void 0}):Nkt(a)!=null?Gw.bytes({docs:n,v2Examples:void 0}):s5E(i,n,t,r)}}function u5E({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 jxn(a)?I9.text({docs:n,v2Examples:void 0}):typeof i!="string"&&u==="sse"?I9.sse({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0,v2Examples:void 0}):I9.json({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0,v2Examples:void 0})}}function s5E(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?Gw.json(B9.nestedPropertyAsResponse({docs:t,responseBodyType:a,responseProperty:vNa({typeResolver:i,file:r,resolvedType:u,property:l}),v2Examples:void 0})):Gw.json(B9.response({docs:t,responseBodyType:a,v2Examples:void 0}))}function Ux_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return AQ.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 Vx_({propertyResolver:e,file:t,endpointName:r,paginationPropertyComponents:i}){return AQ.custom({results:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results})})}function Wx_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return AQ.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 Hx_(e){if(l5E(e))return{type:"offset",offset:UHt(e.offset),results:inr(e.results),step:e.step!=null?UHt(e.step):void 0,hasNextPage:e["has-next-page"]!=null?inr(e["has-next-page"]):void 0};if(c5E(e))return{type:"cursor",cursor:UHt(e.cursor),next_cursor:inr(e.next_cursor),results:inr(e.results)};if(f5E(e))return{type:"custom",results:inr(e.results)};throw new Error("Invalid pagination schema")}function c5E(e){return e.cursor!=null}function l5E(e){return e.offset!=null&&e.results!=null}function f5E(e){return"type"in e&&e.type==="custom"}function $x_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i}){let n=typeof i.pagination=="boolean"?t.rootApiFile.pagination:i.pagination;if(!n)return;let a=Hx_(n);switch(a.type){case"cursor":return Ux_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"offset":return Wx_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"custom":return Vx_({propertyResolver:e,file:t,endpointName:r,paginationPropertyComponents:a});default:wo(a)}}function Gx_({errors:e,file:t}){return e==null?[]:Object.values(e).map(r=>{let i=typeof r=="string"?r:r.error,n=oqi({errorName:i,file:t});return{docs:typeof r!="string"?r.docs:void 0,error:n}})}function Ktu({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function Qx_({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:Ktu({source:e}),name:uqi.generateName(r)}}function Jx_({file:e,serviceDeclaration:t,sourceResolver:r}){return Dkt(t.source)?Yx_(e,t.source,r,t.transport?.grpc?.["service-name"]):dRe.http()}function Kx_({file:e,serviceTransport:t,endpointDeclaration:r,sourceResolver:i}){let n=t.type==="grpc",a=t.type==="http",u=Dkt(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 dRe.http();if(n&&u){let d=r.source,s=r.transport?.grpc?.["service-name"];return s?Yx_(e,d,i,s):void 0}throw new Error(`Internal error; failed to determine endpoint transport for
|
|
2049
|
-
${JSON.stringify(r)}"`)}}function Yx_(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=Qx_({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return dRe.grpc({service:a})}function Xx_({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=ILn({pathParameters:r["path-parameters"],location:pRe.Service,file:i,variableResolver:d}),g=Jx_({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:doe(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:uF(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([w,E])=>$Fe({headerKey:w,header:E,file:i})):[],pathParameters:b,encoding:h5E(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([w,E])=>{let q=ILn({pathParameters:VHt(E),location:pRe.Endpoint,file:i,variableResolver:d}),M={...SJ(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?_5E(E.method):uB.Post,basePath:E["base-path"]!=null?uF(E["base-path"]):void 0,path:uF(E.path),fullPath:uF(E["base-path"]!=null?_b(E["base-path"],E.path):i.rootApiFile["base-path"]!=null?_b(i.rootApiFile["base-path"],r["base-path"],E.path):_b(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])=>Jtu({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof E.request!="string"&&E.request?.headers!=null?Object.entries(E.request.headers).map(([D,C])=>$Fe({headerKey:D,header:C,file:i})):[],requestBody:cx_({request:E.request,file:i}),v2RequestBodies:void 0,sdkRequest:_x_({service:r,request:E.request,endpoint:E,endpointKey:w,file:i,typeResolver:a,propertyResolver:u}),response:Lx_({endpoint:E,file:i,typeResolver:a}),v2Responses:void 0,errors:[...Gx_({errors:E.errors,file:i}),...o],userSpecifiedExamples:E.examples!=null?E.examples.map(D=>({example:Fx_({service:r,endpoint:E,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:d,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(C=>hx_({codeSample:C,file:i}))})):[],autogeneratedExamples:[],pagination:$x_({propertyResolver:u,file:i,endpointName:w,endpointSchema:E}),transport:Kx_({file:i,serviceTransport:g,endpointDeclaration:E,sourceResolver:s}),v2Examples:void 0,source:void 0,audiences:E.audiences};return M.id=qm.generateEndpointId(O,M),M}),audiences:r.audiences}}function ILn({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>d5E({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function d5E({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...SJ(t),name:i.casingsGenerator.generateName(e),valueType:p5E({parameter:t,variableResolver:n,file:i}),location:r,variable:jRn(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function p5E({parameter:e,variableResolver:t,file:r}){let i=PNa({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function PNa({parameter:e,variableResolver:t,file:r}){let i=Ytu({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function Ytu({parameter:e,variableResolver:t,file:r}){if(jRn(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 _5E(e){switch(e){case"GET":return uB.Get;case"POST":return uB.Post;case"PUT":return uB.Put;case"PATCH":return uB.Patch;case"DELETE":return uB.Delete;case"HEAD":return uB.Head;default:wo(e)}}function $Fe({headerKey:e,header:t,file:r}){let{name:i}=nnr({headerKey:e,header:t});return{...SJ(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 nnr({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function h5E(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:wo(e)}}var Zx_="1.0.0";var Xtu=class{ir;casingsGenerator;auth;authValues;generatorConfig;constructor(t){this.ir=t.ir,this.generatorConfig=t.generatorConfig,this.casingsGenerator=JZ({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:Zx_,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:wo(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:wo(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:wo(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:wo(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return bs.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return bs.FileUploadRequestBodyProperty.fileArray(t.key);default:wo(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:wo(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:wo(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:wo(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:wo(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:wo(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:wo(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:wo(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=_b(r,t.fullPath.head));for(let i of t.fullPath.parts)r=_b(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=_b(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??Mae(),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 kx_({ir:e,generationLanguage:t,smartCasing:r,disableExamples:i,generatorConfig:n}){return new Xtu({ir:e,generationLanguage:t,smartCasing:r,generatorConfig:n}).convert({disableExamples:i})}var DJ={};mo(DJ,{validateObjectExample:()=>_Yi,validateTypeExample:()=>Gtu,validateTypeReferenceExample:()=>OL});var Ztu=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:qm.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:dd(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!eR_(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(!eR_(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=qm.generateSubpackageId(l),o={docs:void 0,fernFilepath:l,name:n,displayName:void 0,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 eR_(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 tR_(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}var ktu=e=>{let t=PMe(e.file.fernFilepath),r=e.endpointId;return`endpoint_${t}.${r}`};function eru({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function rR_({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:ktu(n),serviceId:qm.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:eru({fernFilePath:n.file.fernFilepath})?void 0:qm.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 iR_({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:ktu(n),serviceId:qm.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:eru({fernFilePath:n.file.fernFilepath})?void 0:qm.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:y5E({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 y5E=({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 nR_({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=iR_({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?rR_({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 jNa={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}},m1c={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 aR_(e){return{endpoint:e["get-token"].endpoint,requestProperties:v5E({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:b5E({responseProperties:e["get-token"]?.["response-properties"]})}}function oR_(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:g5E({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:O5E({responseProperties:e["refresh-token"]?.["response-properties"]})}}function v5E({requestProperties:e}){if(e==null)return jNa.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?UHt(t):jNa.requestProperties.client_id,client_secret:r!=null?UHt(r):jNa.requestProperties.client_secret,scopes:i!=null?UHt(i):jNa.requestProperties.scopes}}function b5E({responseProperties:e}){return uR_({responseProperties:e,defaultValue:jNa.responseProperties})}function g5E({requestProperties:e}){if(e==null)return m1c.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?UHt(t):m1c.requestProperties.refresh_token}}function O5E({responseProperties:e}){return uR_({responseProperties:e,defaultValue:m1c.responseProperties})}function uR_({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?inr(r):t.access_token,expires_in:i!=null?inr(i):t.expires_in,refresh_token:n!=null?inr(n):t.refresh_token}}function dR_({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:xne.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return eHi(e.auth,{single:a=>{let u=sR_({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:xne.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:xne.Any,schemes:a.map(u=>sR_({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function sR_({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 RSa(s,{header:o=>$T.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=>lR_({file:r,docs:d,rawScheme:o}),bearer:o=>cR_({file:r,docs:d,rawScheme:o}),oauth:o=>fR_({file:r,docs:d,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return cR_({file:r,docs:void 0,rawScheme:void 0});case"basic":return lR_({file:r,docs:void 0,rawScheme:void 0});case"oauth":return fR_({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function cR_({file:e,docs:t,rawScheme:r}){return $T.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function lR_({file:e,docs:t,rawScheme:r}){return $T.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 fR_({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return $T.oauth({docs:t,configuration:I1i.clientCredentials(nR_({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:aR_(r),refreshTokenEndpoint:oR_(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function pR_({file:e,rawApiFileSchema:t}){if(t.version!=null)return x1i.header({header:m5E({file:e,header:t.version.header}),value:P5E({file:e,versionDeclaration:t.version})})}function m5E({file:e,header:t}){return typeof t=="string"?$Fe({file:e,headerKey:t,header:{type:"string"}}):$Fe({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function P5E({file:e,versionDeclaration:t}){return Qtu({_enum:{default:t.default,enum:t.values},file:e})}function _R_({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:doe(d.availability),docs:d.docs,origin:d.origin,body:S5E({body:d.body,file:n}),displayName:d["display-name"]});return{availability:doe(e.availability),path:uF(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])=>$Fe({headerKey:l,header:d,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?ILn({pathParameters:e["path-parameters"],location:pRe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,d])=>{let{name:s}=Gpi({queryParameterKey:l,queryParameter:d}),o=n.parseTypeReference(d);return{...SJ(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=E5E({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:A5E({channel:e,example:l,pathParams:d}),...d,...M5E({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:Gpi({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:rM({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:j5E({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:w5E({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}}),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function j5E({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?V2.exploded():V2.single()}function w5E({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!q5E(e.body))return QEe.reference(rM({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!ew(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:gL({propertyKey:l,property:s}).name,wireValue:l}),value:rM({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=mNa({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:gL({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:rM({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 QEe.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function S5E({body:e,file:t}){return typeof e=="string"?R9.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):D5E(e)?R9.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):R9.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:LHt(e.extends??[]).map(r=>bL({typeName:r,file:t})),properties:Object.entries(e.properties??{}).map(([r,i])=>({name:t.casingsGenerator.generateNameAndWireValue({name:gL({propertyKey:r,property:i}).name,wireValue:r}),value:t.parseTypeReference(i),valueType:t.parseTypeReference(i),availability:void 0,docs:void 0}))})}function D5E(e){return e.type!=null}function E5E({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=PNa({parameter:o,variableResolver:n,file:a});return{name:s,value:rM({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=VHt(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 M5E({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:nnr({headerKey:l,header:s}).name,wireValue:l}),value:rM({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 A5E({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 q5E(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function hR_({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:rM({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:oqi({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 yR_="content";function vR_(e,t){if(e==null||e.strategy==="status-code")return GEe.statusCode();switch(e.strategy){case"property":return GEe.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:yR_,wireValue:yR_})});default:wo(e)}}function bR_({readme:e,services:t}){let r=new P1c(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 P1c=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=C5E({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:T5E(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function T5E(e){let t="";e.fullPath.head.length>0&&(t=_b(t,e.fullPath.head));for(let r of e.fullPath.parts)t=_b(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=_b(t,r.tail));return t.startsWith("/")?t:`/${t}`}function C5E({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 gR_({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:qm.generateWebhookId(t.fernFilepath,u),availability:doe(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])=>$Fe({headerKey:d,header:s,file:t})):[],payload:B5E({payload:l.payload,file:t}),examples:l.examples!=null?z5E({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0,v2Examples:void 0});return a}function B5E({payload:e,file:t}){return typeof e=="string"?jW.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):l2n(e)?jW.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):jW.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:LHt(e.extends).map(r=>bL({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>I5E({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?doe(i.availability):void 0,file:t})):[]})}function I5E({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:gL({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function z5E({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:l2n(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:rM({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!ew(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:rM({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function OR_({name:e,source:t}){return nw.userDefined({file:Ktu({source:t}),name:uqi.generateName(e)})}function mR_({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=x5E({type:e.proto.type});if(t!=null)return t}}function x5E({type:e}){switch(e){case"google.protobuf.Any":return nw.wellKnown(nd.any());case"google.protobuf.Api":return nw.wellKnown(nd.api());case"google.protobuf.BoolValue":return nw.wellKnown(nd.boolValue());case"google.protobuf.BytesValue":return nw.wellKnown(nd.bytesValue());case"google.protobuf.DoubleValue":return nw.wellKnown(nd.doubleValue());case"google.protobuf.Duration":return nw.wellKnown(nd.duration());case"google.protobuf.Empty":return nw.wellKnown(nd.empty());case"google.protobuf.Enum":return nw.wellKnown(nd.enum());case"google.protobuf.EnumValue":return nw.wellKnown(nd.enumValue());case"google.protobuf.Field":return nw.wellKnown(nd.field());case"google.protobuf.FieldCardinality":return nw.wellKnown(nd.fieldCardinality());case"google.protobuf.FieldKind":return nw.wellKnown(nd.fieldKind());case"google.protobuf.FieldMask":return nw.wellKnown(nd.fieldMask());case"google.protobuf.FloatVlaue":return nw.wellKnown(nd.floatValue());case"google.protobuf.Int32Value":return nw.wellKnown(nd.int32Value());case"google.protobuf.Int64Value":return nw.wellKnown(nd.int64Value());case"google.protobuf.ListValue":return nw.wellKnown(nd.listValue());case"google.protobuf.Method":return nw.wellKnown(nd.method());case"google.protobuf.Mixin":return nw.wellKnown(nd.mixin());case"google.protobuf.NullValue":return nw.wellKnown(nd.nullValue());case"google.protobuf.Option":return nw.wellKnown(nd.option());case"google.protobuf.SourceContext":return nw.wellKnown(nd.sourceContext());case"google.protobuf.StringValue":return nw.wellKnown(nd.stringValue());case"google.protobuf.Struct":return nw.wellKnown(nd.struct());case"google.protobuf.Syntax":return nw.wellKnown(nd.syntax());case"google.protobuf.Timestamp":return nw.wellKnown(nd.timestamp());case"google.protobuf.Type":return nw.wellKnown(nd.type());case"google.protobuf.Uint32Value":return nw.wellKnown(nd.uint32Value());case"google.protobuf.Uint64Value":return nw.wellKnown(nd.uint64Value());case"google.protobuf.Value":return nw.wellKnown(nd.value())}}function PR_({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=fR(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&GS(a.declaration)){let u=fR(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 Ab.object({extends:LHt(a.declaration.extends).map(d=>bL({typeName:d,file:t})),properties:yNa({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function jR_({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return lRe(i)?PR_({generic:i,file:t,typeResolver:r}):Ab.alias({aliasOf:t.parseTypeReference(e),resolvedType:R5E({aliasOf:i,file:t,typeResolver:r})})}function R5E({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return PW.primitive(i.originalTypeReference.primitive);case"container":return PW.container(i.originalTypeReference.container);case"unknown":return PW.unknown();case"named":{let n=GS(i.declaration)?QVt.Object:G1i(i.declaration)?QVt.Union:XVt(i.declaration)?QVt.Enum:wRn(i.declaration)?QVt.UndiscriminatedUnion:wo(i.declaration);return PW.named({name:i.name,shape:n})}}}function wR_({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 Ab.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"?pbo(n.name.originalName):i["display-name"]??pbo(n.name.originalName)}:n,docs:typeof i=="string"?void 0:i.docs}})})}function SR_(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 w1c({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new j1c}){let n=_3(e,{alias:u=>{let l=typeof u=="string"?u:u.type,d=fR(l);if(d!=null){let s=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=fR(o.typeName)?.arguments;if(GS(o.declaration)){let b=SR_(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>SR_(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=W2({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=bL({typeName:d,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(lRe(o.typeName))continue;a.push(...w1c({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var j1c=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 DR_({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=SJ(t),d=bL({typeName:e,file:r}),s=w1c({typeDeclaration:t,file:r,typeResolver:i}),o={};GS(t)&&(o=EQi(t.properties??{}));let c=F5E({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:W5E(t),name:d,shape:N5E({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:L5E({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:O1c({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 N5E({typeDeclaration:e,file:t,typeResolver:r}){return _3(e,{alias:i=>jR_({alias:i,file:t,typeResolver:r}),object:i=>ux_({object:i,file:t}),discriminatedUnion:i=>Px_({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>wR_({union:i,file:t}),enum:i=>Ab.enum(Qtu({_enum:i,file:t}))})}function F5E({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=mR_({encoding:t.encoding});if(a!=null)return Hli.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return Hli.proto(OR_({source:n,name:r}))}function L5E({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?U5E(e.encoding):V5E(t)}function U5E(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function V5E(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function W5E(e){if(typeof e!="string"&&"inline"in e)return e.inline}function ER_(e,t){let r=t[e];if(r==null)throw new bli(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function MR_(e){e.types=Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,$5E({typeDeclaration:r,ir:e})])),e.services=Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>H5E({endpoint:i,ir:e}))}]))}function H5E({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>AR_(r,t))}}}function $5E({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>AR_(r,t))}}}return e}function AR_(e,t){let r=S1c(e.typeId,t);return qR_({objectTypeDeclaration:r,ir:t})}function S1c(e,t){let r=ER_(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return S1c(r.shape.resolvedType.name.typeId,t)}throw new bli(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function qR_({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=S1c(i.typeId,t);return qR_({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function TR_({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:aqi({referencedIn:t,importPath:l})}}var yYi=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 x3(this.workspace,(n,a,u)=>{let l=B0({relativeFilepath:n,definitionFile:a,casingsGenerator:uqi,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})}),RJi(this.workspace,(n,a)=>{let u=B0({relativeFilepath:n,definitionFile:a,casingsGenerator:uqi,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 tHi().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=TR_({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=eoe(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:B0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var vYi=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=UMe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=eoe(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:B0({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var WMe=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(ew(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(`\\${jkt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(jkt))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(jkt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(jkt.length),exampleName:n}}};var tru=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:Nne.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:Nne.query(Jtu({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:Nne.body(u)}}if(oB(i.body)){let u=y1c({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Nne.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:Nne.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return h1c({typeResolver:this.typeResolver,file:bNa(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 tS=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=UMe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=eoe(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=fR(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:B0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:B0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return W2({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:Yc.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:Yc.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:Yc.container(Dy.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:Yc.container(Dy.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:Yc.container(Dy.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:Yc.container(Dy.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:Yc.container(Dy.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:Yc.container(Dy.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($1i(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=ONa({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||eoe(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 HHt=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:$pi({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 rru(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function MR({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=JZ({generationLanguage:t,keywords:r,smartCasing:i}),O=new MQi(a),m=$pi({casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents}),w=(e.definition.rootApiFile.contents.errors??[]).map(ot=>({error:oqi({errorName:ot,file:m}),docs:void 0})),E=new tS(e),q=new yYi(e),M=new tru(E,q),D=new vYi(e),C=new WMe(E),x=new HHt,I=sBa({casingsGenerator:g,rawApiFileSchema:e.definition.rootApiFile.contents})?.environmentsConfig,F={selfHosted:!1,fdrApiDefinitionId:s,apiVersion:pR_({file:m,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:g.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:hNa(e.definition.rootApiFile.contents.docs),auth:dR_({rawApiFileSchema:e.definition.rootApiFile.contents,file:m,propertyResolver:M,endpointResolver:q}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([ot,at])=>$Fe({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])=>$Fe({headerKey:ot,header:at,file:m})):[],types:{},errors:{},services:{},constants:tR_(g),environments:I,errorDiscriminationStrategy:vR_(e.definition.rootApiFile.contents["error-discrimination"],m),basePath:e.definition.rootApiFile.contents["base-path"]!=null?uF(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:ILn({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:m,location:pRe.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 Ztu,K=ot=>{V.addSubpackage(ot.fernFilepath),Vw(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(lRe(me))continue;let wt=DR_({typeName:me,typeDeclaration:we,file:ot,typeResolver:E,exampleResolver:C,sourceResolver:o,workspace:e}),Ot=wt.typeDeclaration;n.disabled&&(Ot.userProvidedExamples=[],Ot.autogeneratedExamples=[]);let Tr=wt.descendantFilepaths,fr=qm.generateTypeId(Ot.name);F.types[fr]=Ot,V.addType(fr,Ot),O.addType({declaredTypeName:Ot.name,descendantTypeIds:Ot.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:wt.propertiesByAudience,descendantFilepaths:Tr}),O.markTypeForAudiences(Ot.name,ox_(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,wt]of Object.entries(at)){let Ot=hR_({errorName:we,errorDeclaration:wt,file:ot,typeResolver:E,exampleResolver:C,workspace:e}),Tr=qm.generateErrorId(Ot.name);F.errors[Tr]=Ot,V.addError(Tr,Ot),O.addError(Ot)}},service:at=>{if(at==null)return;let me=Xx_({rootDefaultUrl:ot.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:F.pathParameters,serviceDefinition:at,file:ot,errorResolver:D,typeResolver:E,propertyResolver:M,exampleResolver:C,sourceResolver:o,globalErrors:w,variableResolver:x,workspace:e}),we=qm.generateServiceId(me.name);F.services[we]=me,V.addService(we,me);let wt={};me.endpoints.forEach(Ot=>{n.disabled&&(Ot.autogeneratedExamples=[],Ot.userSpecifiedExamples=[]);let Tr=at.endpoints[Ot.name.originalName];O.addEndpoint(me,Ot,Tr),wt[Ot.name.originalName]=Ot}),at.audiences!=null&&O.markEndpointForAudience(me.name,me.endpoints,at.audiences),Object.entries(at.endpoints).map(([Ot,Tr])=>{let fr=wt[Ot];fr!=null&&Tr.audiences!=null&&O.markEndpointForAudience(me.name,[fr],Tr.audiences)})},webhooks:at=>{if(at==null)return;let me=qm.generateWebhookGroupId(ot.fernFilepath),we=gR_({webhooks:at,file:ot,typeResolver:E,exampleResolver:C,workspace:e}),wt={};for(let Ot of we)wt[Ot.name.originalName]=Ot;Object.entries(at).forEach(([Ot,Tr])=>{let fr=wt[Ot];fr!=null&&(O.addWebhook(ot.fernFilepath,fr,Tr),Tr.audiences!=null&&O.markWebhookForAudiences(ot.fernFilepath,fr,Tr.audiences))}),F.webhookGroups[me]=we,V.addWebhookGroup(me,ot.fernFilepath)},channel:at=>{if(at==null)return;let me=qm.generateWebSocketChannelId(ot.fernFilepath),we=_R_({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))}})};x3(e,(ot,at,me)=>{K(B0({relativeFilepath:ot,definitionFile:at,casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:me.defaultUrl}))}),RJi(e,(ot,at)=>{if(at.navigation!=null)if(typeof at.navigation=="string")V.addPackageRedirection({from:foe({relativeFilepath:ot,casingsGenerator:g}),to:foe({relativeFilepath:LN(Dxe(ot),ty.of(at.navigation)),casingsGenerator:g})});else{let me=at.navigation.map(we=>qm.generateSubpackageId(foe({relativeFilepath:LN(Dxe(ot),ty.of(we)),casingsGenerator:g})));ot===J1?V.sortRootPackage(me):V.sortSubpackage(qm.generateSubpackageId(foe({relativeFilepath:ot,casingsGenerator:g})),me)}}),F.serviceTypeReferenceInfo=Q5E(O),MR_(F);let Y=n.disabled?F:uBa({ir:F,exampleGeneration:n}),Z=e.definition.rootApiFile.contents,oe=I?.environments._visit({singleBaseUrl:ot=>ot.environments.filter(at=>rru(at.id,Z.environments)!=null).length===0,multipleBaseUrls:ot=>ot.environments.filter(at=>rru(at.id,Z.environments)!=null).length===0,_other:()=>!1});I?.environments.environments.forEach(ot=>{O.markEnvironmentForAudiences(ot,rru(ot.id,Z.environments)??[],oe)});let pe=O.hasNoAudiences()?void 0:O.build(),de=gsc(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")),bt=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:bt,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?bR_({readme:u,services:F.services}):void 0,Pe=G5E({...de,...V.build(pe),sdkConfig:Te,readmeConfig:xt});return{...Pe,dynamic:kx_({ir:Pe,generatorConfig:b,disableExamples:c,generationLanguage:t,smartCasing:i})}}function G5E(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]=hNa(n):n&&typeof n=="object"&&t(n)}return r};return t(e)}function Q5E(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 CR_(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var IR_=ui(IBn(),1);var BR_=["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 $Ht(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,IR_.default)(e,{special:BR_}).replace(/V\s(\d)/g,"V$1")}function wNa(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&CR_(e),r._other(e))}}}function anr(e){return typeof e.subpackageId=="string"}function bYi(e,t){return`${e} ${TC(t)}`}function TC(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function GFe(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var D1c="__package__",cqi=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;#c=new Map;#l=new Map;#p=new Map;#_=new Map;static getSubpackageId(t){return anr(t)?t.subpackageId:D1c}getSubpackageByIdOrLocator(t){if(t==null)return;let r=s4.SubpackageId(t),i=s4.SubpackageId(`subpackage_${h_(t)}`);return r===D1c?this.api.rootPackage:this.api.subpackages[r]??this.#_.get(r)??this.api.subpackages[i]??this.#_.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=s4.SubpackageId(e.getSubpackageId(i)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map,grpcs:new Map};this.#f.set(n,a),i.endpoints.forEach(u=>{if(u.protocol?.type==="grpc"){a.grpcs.set(u.id,u);let l=e.createGrpcId(u,n);this.#n.set(l,u)}else{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} ${TC(u.path.parts)}`),d.push(`${o} ${GFe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${_b(c.baseUrl,TC(u.path.parts))}`),d.push(`${o} ${_b(c.baseUrl,GFe(u.path.parts))}`);let b=iru(c);b!=null&&(d.push(`${o} ${_b(b,TC(u.path.parts))}`),d.push(`${o} ${_b(b,GFe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering endpoint locator: ${o}`),this.#u.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} ${TC(u.path.parts)}`),d.push(`${o} ${GFe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${_b(c.baseUrl,TC(u.path.parts))}`),d.push(`${o} ${_b(c.baseUrl,GFe(u.path.parts))}`);let b=iru(c);b!=null&&(d.push(`${o} ${_b(b,TC(u.path.parts))}`),d.push(`${o} ${_b(b,GFe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering websocket locator: ${o}`),this.#c.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.#i.set(i,n)}),this.#t.forEach((i,n)=>{this.#a.set(i,n)}),this.#r.forEach((i,n)=>{this.#o.set(i,n)}),this.#n.forEach((i,n)=>{this.#s.set(i,n)}),this.#h(t.rootPackage,[])}#h(t,r){if(t==null)return;let i=anr(t)?[...r,t.name]:r,n=i.length===0?[D1c]:i;if([n.join("."),n.join("/"),`${n.join(".")}.yml`].forEach(u=>{this.context?.logger.trace(`Registering subpackage locator: ${u}`),this.#_.set(u,t)}),t.pointsTo!=null)return this.#h(this.api.subpackages[t.pointsTo],i);t.endpoints.forEach(u=>{if(u.protocol?.type==="grpc")return;let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering endpoint locator: ${s}`),this.#u.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.#c.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.#l.set(s,u)})}),t.subpackages.forEach(u=>{this.#h(this.api.subpackages[u],i)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#r}get grpcs(){return this.#n}get endpointsByLocator(){return this.#u}get webSocketsByLocator(){return this.#c}get webhooksByLocator(){return this.#l}get grpcsByLocator(){return this.#p}get subpackages(){return this.#f}get subpackagesByLocator(){return this.#_}get subpackageLocators(){return new Set(this.#_.keys())}getEndpointId(t){return this.#i.get(t)}getWebSocketId(t){return this.#a.get(t)}getWebhookId(t){return this.#o.get(t)}getGrpcId(t){return this.#s.get(t)}static createEndpointId(t,r){return Oo.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return Oo.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return Oo.WebhookId(`${r}.${t.id}`)}static createGrpcId(t,r){return Oo.GrpcId(`${r}.${t.id}`)}};function iru(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 zLn=ui(Gko(),1),xR_=ui(Qko(),1);function zR_(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{}}zLn.default.extend(xR_.default);var J5E="Changelog",K5E=["summary","index","overview"],Qpi=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??J5E,i=[],n;for(let b of this.changelogFiles??[]){let g=qzs(b.split("/"));if(g==null)continue;let O=zR_(g);if(O==null){let w=g.split(".")[0]?.toLowerCase();w!=null&&K5E.includes(w)&&(n=b);continue}let m=this.toRelativeFilepath(b);i.push({date:O,pageId:Oo.PageId(m),absoluteFilepath:b})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??Vq(r)}),u=n!=null?this.markdownToNoIndex.get(n):void 0,l=i.map(b=>{let g=zLn.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=E1c(l,b=>b.date,"desc"),s=n!=null?Oo.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=zLn.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return E1c(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=zLn.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return E1c(Array.from(n.entries()).map(([a,u])=>{let l=(0,zLn.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 Hq(this.docsWorkspace.absoluteFilePath,t)}};function E1c(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 nru(e){if(e)return{environments:e.environments!=null&&e.environments.length>0?e.environments.map(t=>Oo.V1.EnvironmentId(t)):void 0,button:e.button!=null&&e.button.href?{href:Oo.V1.Url(e.button.href)}:void 0,"limit-websocket-messages-per-connection":e.limitWebsocketMessagesPerConnection!=null?e.limitWebsocketMessagesPerConnection:void 0}}function SNa({child:e,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i}){if(e.type==="apiPackage"){let n=Oo.V1.SlugGenerator.init(e.slug),u=(t.get(e.id)??[]).flatMap(s=>r(s,n)),l=e.children.map(s=>SNa({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),d=i(l,u);return{...e,children:d,pointsTo:void 0}}return e}var WR_=ui(LR_(),1);var eC=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(u){u(a)})}return new(r||(r=Promise))(function(a,u){function l(o){try{s(i.next(o))}catch(c){u(c)}}function d(o){try{s(i.throw(o))}catch(c){u(c)}}function s(o){o.done?a(o.value):n(o.value).then(l,d)}s((i=i.apply(e,t||[])).next())})},rT=function(e,t){var r={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,n,a,u=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return u.next=l(0),u.throw=l(1),u.return=l(2),typeof Symbol=="function"&&(u[Symbol.iterator]=function(){return this}),u;function l(s){return function(o){return d([s,o])}}function d(s){if(i)throw new TypeError("Generator is already executing.");for(;u&&(u=0,s[0]&&(r=0)),r;)try{if(i=1,n&&(a=s[0]&2?n.return:s[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,s[1])).done)return a;switch(n=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return r.label++,{value:s[1],done:!1};case 5:r.label++,n=s[1],s=[0];continue;case 7:s=r.ops.pop(),r.trys.pop();continue;default:if(a=r.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){r=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){r.label=s[1];break}if(s[0]===6&&r.label<a[1]){r.label=a[1],a=s;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(s);break}a[2]&&r.ops.pop(),r.trys.pop();continue}s=t.call(e,r)}catch(o){s=[6,o],n=0}finally{i=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},poe=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var i=r.call(e),n,a=[],u;try{for(;(t===void 0||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(l){u={error:l}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(u)throw u.error}}return a},QFe=function(e,t,r){if(r||arguments.length===2)for(var i=0,n=t.length,a;i<n;i++)(a||!(i in t))&&(a||(a=Array.prototype.slice.call(t,0,i)),a[i]=t[i]);return e.concat(a||Array.prototype.slice.call(t))},UR_=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],i=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},v45=function(){function e(t){t===void 0&&(t=e.minComparator);var r=this;this.compare=t,this.heapArray=[],this._limit=0,this.offer=this.add,this.element=this.peek,this.poll=this.pop,this._invertedCompare=function(i,n){return r.compare(i,n).then(function(a){return-1*a})}}return e.getChildrenIndexOf=function(t){return[t*2+1,t*2+2]},e.getParentIndexOf=function(t){if(t<=0)return-1;var r=t%2?1:2;return Math.floor((t-r)/2)},e.getSiblingIndexOf=function(t){if(t<=0)return-1;var r=t%2?1:-1;return t+r},e.minComparator=function(t,r){return eC(this,void 0,void 0,function(){return rT(this,function(i){return t>r?[2,1]:t<r?[2,-1]:[2,0]})})},e.maxComparator=function(t,r){return eC(this,void 0,void 0,function(){return rT(this,function(i){return r>t?[2,1]:r<t?[2,-1]:[2,0]})})},e.minComparatorNumber=function(t,r){return eC(this,void 0,void 0,function(){return rT(this,function(i){return[2,t-r]})})},e.maxComparatorNumber=function(t,r){return eC(this,void 0,void 0,function(){return rT(this,function(i){return[2,r-t]})})},e.defaultIsEqual=function(t,r){return eC(this,void 0,void 0,function(){return rT(this,function(i){return[2,t===r]})})},e.print=function(t){function r(o){var c=e.getParentIndexOf(o);return Math.floor(Math.log2(c+1))}function i(o,c){for(var b="";c>0;--c)b+=o;return b}for(var n=0,a=[],u=r(t.length-1)+2,l=0;n<t.length;){var d=r(n)+1;n===0&&(d=0);var s=String(t.get(n));s.length>l&&(l=s.length),a[d]=a[d]||[],a[d].push(s),n+=1}return a.map(function(o,c){var b=Math.pow(2,u-c)-1;return i(" ",Math.floor(b/2)*l)+o.map(function(g){var O=(l-g.length)/2;return i(" ",Math.ceil(O))+g+i(" ",Math.floor(O))}).join(i(" ",b*l))}).join(`
|
|
2049
|
+
${JSON.stringify(r)}"`)}}function Yx_(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=Qx_({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return dRe.grpc({service:a})}function Xx_({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=ILn({pathParameters:r["path-parameters"],location:pRe.Service,file:i,variableResolver:d}),g=Jx_({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:doe(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:uF(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([w,E])=>$Fe({headerKey:w,header:E,file:i})):[],pathParameters:b,encoding:h5E(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([w,E])=>{let q=ILn({pathParameters:VHt(E),location:pRe.Endpoint,file:i,variableResolver:d}),M={...SJ(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?_5E(E.method):uB.Post,basePath:E["base-path"]!=null?uF(E["base-path"]):void 0,path:uF(E.path),fullPath:uF(E["base-path"]!=null?_b(E["base-path"],E.path):i.rootApiFile["base-path"]!=null?_b(i.rootApiFile["base-path"],r["base-path"],E.path):_b(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])=>Jtu({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof E.request!="string"&&E.request?.headers!=null?Object.entries(E.request.headers).map(([D,C])=>$Fe({headerKey:D,header:C,file:i})):[],requestBody:cx_({request:E.request,file:i}),v2RequestBodies:void 0,sdkRequest:_x_({service:r,request:E.request,endpoint:E,endpointKey:w,file:i,typeResolver:a,propertyResolver:u}),response:Lx_({endpoint:E,file:i,typeResolver:a}),v2Responses:void 0,errors:[...Gx_({errors:E.errors,file:i}),...o],userSpecifiedExamples:E.examples!=null?E.examples.map(D=>{try{let C=Fx_({service:r,endpoint:E,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:d,file:i,workspace:c});return C===void 0?void 0:{example:C,codeSamples:D["code-samples"]?.map(x=>hx_({codeSample:x,file:i}))}}catch{return}}).filter(D=>D!==void 0):[],autogeneratedExamples:[],pagination:$x_({propertyResolver:u,file:i,endpointName:w,endpointSchema:E}),transport:Kx_({file:i,serviceTransport:g,endpointDeclaration:E,sourceResolver:s}),v2Examples:void 0,source:void 0,audiences:E.audiences};return M.id=qm.generateEndpointId(O,M),M}),audiences:r.audiences}}function ILn({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>d5E({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function d5E({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...SJ(t),name:i.casingsGenerator.generateName(e),valueType:p5E({parameter:t,variableResolver:n,file:i}),location:r,variable:jRn(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function p5E({parameter:e,variableResolver:t,file:r}){let i=PNa({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function PNa({parameter:e,variableResolver:t,file:r}){let i=Ytu({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function Ytu({parameter:e,variableResolver:t,file:r}){if(jRn(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 _5E(e){switch(e){case"GET":return uB.Get;case"POST":return uB.Post;case"PUT":return uB.Put;case"PATCH":return uB.Patch;case"DELETE":return uB.Delete;case"HEAD":return uB.Head;default:wo(e)}}function $Fe({headerKey:e,header:t,file:r}){let{name:i}=nnr({headerKey:e,header:t});return{...SJ(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 nnr({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function h5E(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:wo(e)}}var Zx_="1.0.0";var Xtu=class{ir;casingsGenerator;auth;authValues;generatorConfig;constructor(t){this.ir=t.ir,this.generatorConfig=t.generatorConfig,this.casingsGenerator=JZ({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:Zx_,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:wo(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:wo(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:wo(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:wo(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return bs.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return bs.FileUploadRequestBodyProperty.fileArray(t.key);default:wo(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:wo(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:wo(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:wo(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:wo(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:wo(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:wo(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:wo(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=_b(r,t.fullPath.head));for(let i of t.fullPath.parts)r=_b(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=_b(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??Mae(),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 kx_({ir:e,generationLanguage:t,smartCasing:r,disableExamples:i,generatorConfig:n}){return new Xtu({ir:e,generationLanguage:t,smartCasing:r,generatorConfig:n}).convert({disableExamples:i})}var DJ={};mo(DJ,{validateObjectExample:()=>_Yi,validateTypeExample:()=>Gtu,validateTypeReferenceExample:()=>OL});var Ztu=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:qm.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:dd(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!eR_(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(!eR_(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=qm.generateSubpackageId(l),o={docs:void 0,fernFilepath:l,name:n,displayName:void 0,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 eR_(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 tR_(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}var ktu=e=>{let t=PMe(e.file.fernFilepath),r=e.endpointId;return`endpoint_${t}.${r}`};function eru({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function rR_({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:ktu(n),serviceId:qm.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:eru({fernFilePath:n.file.fernFilepath})?void 0:qm.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 iR_({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:ktu(n),serviceId:qm.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:eru({fernFilePath:n.file.fernFilepath})?void 0:qm.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:y5E({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 y5E=({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 nR_({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=iR_({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?rR_({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 jNa={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}},m1c={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 aR_(e){return{endpoint:e["get-token"].endpoint,requestProperties:v5E({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:b5E({responseProperties:e["get-token"]?.["response-properties"]})}}function oR_(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:g5E({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:O5E({responseProperties:e["refresh-token"]?.["response-properties"]})}}function v5E({requestProperties:e}){if(e==null)return jNa.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?UHt(t):jNa.requestProperties.client_id,client_secret:r!=null?UHt(r):jNa.requestProperties.client_secret,scopes:i!=null?UHt(i):jNa.requestProperties.scopes}}function b5E({responseProperties:e}){return uR_({responseProperties:e,defaultValue:jNa.responseProperties})}function g5E({requestProperties:e}){if(e==null)return m1c.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?UHt(t):m1c.requestProperties.refresh_token}}function O5E({responseProperties:e}){return uR_({responseProperties:e,defaultValue:m1c.responseProperties})}function uR_({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?inr(r):t.access_token,expires_in:i!=null?inr(i):t.expires_in,refresh_token:n!=null?inr(n):t.refresh_token}}function dR_({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:xne.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return eHi(e.auth,{single:a=>{let u=sR_({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:xne.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:xne.Any,schemes:a.map(u=>sR_({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function sR_({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 RSa(s,{header:o=>$T.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=>lR_({file:r,docs:d,rawScheme:o}),bearer:o=>cR_({file:r,docs:d,rawScheme:o}),oauth:o=>fR_({file:r,docs:d,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return cR_({file:r,docs:void 0,rawScheme:void 0});case"basic":return lR_({file:r,docs:void 0,rawScheme:void 0});case"oauth":return fR_({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function cR_({file:e,docs:t,rawScheme:r}){return $T.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function lR_({file:e,docs:t,rawScheme:r}){return $T.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 fR_({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return $T.oauth({docs:t,configuration:I1i.clientCredentials(nR_({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:aR_(r),refreshTokenEndpoint:oR_(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function pR_({file:e,rawApiFileSchema:t}){if(t.version!=null)return x1i.header({header:m5E({file:e,header:t.version.header}),value:P5E({file:e,versionDeclaration:t.version})})}function m5E({file:e,header:t}){return typeof t=="string"?$Fe({file:e,headerKey:t,header:{type:"string"}}):$Fe({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function P5E({file:e,versionDeclaration:t}){return Qtu({_enum:{default:t.default,enum:t.values},file:e})}function _R_({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:doe(d.availability),docs:d.docs,origin:d.origin,body:S5E({body:d.body,file:n}),displayName:d["display-name"]});return{availability:doe(e.availability),path:uF(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])=>$Fe({headerKey:l,header:d,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?ILn({pathParameters:e["path-parameters"],location:pRe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,d])=>{let{name:s}=Gpi({queryParameterKey:l,queryParameter:d}),o=n.parseTypeReference(d);return{...SJ(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=E5E({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:A5E({channel:e,example:l,pathParams:d}),...d,...M5E({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:Gpi({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:rM({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:j5E({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:w5E({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}}),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function j5E({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?V2.exploded():V2.single()}function w5E({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!q5E(e.body))return QEe.reference(rM({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!ew(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:gL({propertyKey:l,property:s}).name,wireValue:l}),value:rM({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=mNa({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:gL({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:rM({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 QEe.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function S5E({body:e,file:t}){return typeof e=="string"?R9.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):D5E(e)?R9.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):R9.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:LHt(e.extends??[]).map(r=>bL({typeName:r,file:t})),properties:Object.entries(e.properties??{}).map(([r,i])=>({name:t.casingsGenerator.generateNameAndWireValue({name:gL({propertyKey:r,property:i}).name,wireValue:r}),value:t.parseTypeReference(i),valueType:t.parseTypeReference(i),availability:void 0,docs:void 0}))})}function D5E(e){return e.type!=null}function E5E({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=PNa({parameter:o,variableResolver:n,file:a});return{name:s,value:rM({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=VHt(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 M5E({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:nnr({headerKey:l,header:s}).name,wireValue:l}),value:rM({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 A5E({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 q5E(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function hR_({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:rM({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:oqi({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 yR_="content";function vR_(e,t){if(e==null||e.strategy==="status-code")return GEe.statusCode();switch(e.strategy){case"property":return GEe.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:yR_,wireValue:yR_})});default:wo(e)}}function bR_({readme:e,services:t}){let r=new P1c(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 P1c=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=C5E({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:T5E(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function T5E(e){let t="";e.fullPath.head.length>0&&(t=_b(t,e.fullPath.head));for(let r of e.fullPath.parts)t=_b(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=_b(t,r.tail));return t.startsWith("/")?t:`/${t}`}function C5E({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 gR_({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:qm.generateWebhookId(t.fernFilepath,u),availability:doe(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])=>$Fe({headerKey:d,header:s,file:t})):[],payload:B5E({payload:l.payload,file:t}),examples:l.examples!=null?z5E({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0,v2Examples:void 0});return a}function B5E({payload:e,file:t}){return typeof e=="string"?jW.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):l2n(e)?jW.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):jW.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:LHt(e.extends).map(r=>bL({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>I5E({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?doe(i.availability):void 0,file:t})):[]})}function I5E({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:gL({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function z5E({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:l2n(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:rM({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!ew(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:rM({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function OR_({name:e,source:t}){return nw.userDefined({file:Ktu({source:t}),name:uqi.generateName(e)})}function mR_({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=x5E({type:e.proto.type});if(t!=null)return t}}function x5E({type:e}){switch(e){case"google.protobuf.Any":return nw.wellKnown(nd.any());case"google.protobuf.Api":return nw.wellKnown(nd.api());case"google.protobuf.BoolValue":return nw.wellKnown(nd.boolValue());case"google.protobuf.BytesValue":return nw.wellKnown(nd.bytesValue());case"google.protobuf.DoubleValue":return nw.wellKnown(nd.doubleValue());case"google.protobuf.Duration":return nw.wellKnown(nd.duration());case"google.protobuf.Empty":return nw.wellKnown(nd.empty());case"google.protobuf.Enum":return nw.wellKnown(nd.enum());case"google.protobuf.EnumValue":return nw.wellKnown(nd.enumValue());case"google.protobuf.Field":return nw.wellKnown(nd.field());case"google.protobuf.FieldCardinality":return nw.wellKnown(nd.fieldCardinality());case"google.protobuf.FieldKind":return nw.wellKnown(nd.fieldKind());case"google.protobuf.FieldMask":return nw.wellKnown(nd.fieldMask());case"google.protobuf.FloatVlaue":return nw.wellKnown(nd.floatValue());case"google.protobuf.Int32Value":return nw.wellKnown(nd.int32Value());case"google.protobuf.Int64Value":return nw.wellKnown(nd.int64Value());case"google.protobuf.ListValue":return nw.wellKnown(nd.listValue());case"google.protobuf.Method":return nw.wellKnown(nd.method());case"google.protobuf.Mixin":return nw.wellKnown(nd.mixin());case"google.protobuf.NullValue":return nw.wellKnown(nd.nullValue());case"google.protobuf.Option":return nw.wellKnown(nd.option());case"google.protobuf.SourceContext":return nw.wellKnown(nd.sourceContext());case"google.protobuf.StringValue":return nw.wellKnown(nd.stringValue());case"google.protobuf.Struct":return nw.wellKnown(nd.struct());case"google.protobuf.Syntax":return nw.wellKnown(nd.syntax());case"google.protobuf.Timestamp":return nw.wellKnown(nd.timestamp());case"google.protobuf.Type":return nw.wellKnown(nd.type());case"google.protobuf.Uint32Value":return nw.wellKnown(nd.uint32Value());case"google.protobuf.Uint64Value":return nw.wellKnown(nd.uint64Value());case"google.protobuf.Value":return nw.wellKnown(nd.value())}}function PR_({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=fR(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&GS(a.declaration)){let u=fR(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 Ab.object({extends:LHt(a.declaration.extends).map(d=>bL({typeName:d,file:t})),properties:yNa({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function jR_({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return lRe(i)?PR_({generic:i,file:t,typeResolver:r}):Ab.alias({aliasOf:t.parseTypeReference(e),resolvedType:R5E({aliasOf:i,file:t,typeResolver:r})})}function R5E({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return PW.primitive(i.originalTypeReference.primitive);case"container":return PW.container(i.originalTypeReference.container);case"unknown":return PW.unknown();case"named":{let n=GS(i.declaration)?QVt.Object:G1i(i.declaration)?QVt.Union:XVt(i.declaration)?QVt.Enum:wRn(i.declaration)?QVt.UndiscriminatedUnion:wo(i.declaration);return PW.named({name:i.name,shape:n})}}}function wR_({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 Ab.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"?pbo(n.name.originalName):i["display-name"]??pbo(n.name.originalName)}:n,docs:typeof i=="string"?void 0:i.docs}})})}function SR_(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 w1c({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new j1c}){let n=_3(e,{alias:u=>{let l=typeof u=="string"?u:u.type,d=fR(l);if(d!=null){let s=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=fR(o.typeName)?.arguments;if(GS(o.declaration)){let b=SR_(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>SR_(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=W2({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=bL({typeName:d,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(lRe(o.typeName))continue;a.push(...w1c({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var j1c=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 DR_({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=SJ(t),d=bL({typeName:e,file:r}),s=w1c({typeDeclaration:t,file:r,typeResolver:i}),o={};GS(t)&&(o=EQi(t.properties??{}));let c=F5E({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:W5E(t),name:d,shape:N5E({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:L5E({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:O1c({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 N5E({typeDeclaration:e,file:t,typeResolver:r}){return _3(e,{alias:i=>jR_({alias:i,file:t,typeResolver:r}),object:i=>ux_({object:i,file:t}),discriminatedUnion:i=>Px_({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>wR_({union:i,file:t}),enum:i=>Ab.enum(Qtu({_enum:i,file:t}))})}function F5E({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=mR_({encoding:t.encoding});if(a!=null)return Hli.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return Hli.proto(OR_({source:n,name:r}))}function L5E({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?U5E(e.encoding):V5E(t)}function U5E(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function V5E(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function W5E(e){if(typeof e!="string"&&"inline"in e)return e.inline}function ER_(e,t){let r=t[e];if(r==null)throw new bli(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function MR_(e){e.types=Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,$5E({typeDeclaration:r,ir:e})])),e.services=Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>H5E({endpoint:i,ir:e}))}]))}function H5E({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>AR_(r,t))}}}function $5E({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>AR_(r,t))}}}return e}function AR_(e,t){let r=S1c(e.typeId,t);return qR_({objectTypeDeclaration:r,ir:t})}function S1c(e,t){let r=ER_(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return S1c(r.shape.resolvedType.name.typeId,t)}throw new bli(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function qR_({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=S1c(i.typeId,t);return qR_({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function TR_({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:aqi({referencedIn:t,importPath:l})}}var yYi=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 x3(this.workspace,(n,a,u)=>{let l=B0({relativeFilepath:n,definitionFile:a,casingsGenerator:uqi,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})}),RJi(this.workspace,(n,a)=>{let u=B0({relativeFilepath:n,definitionFile:a,casingsGenerator:uqi,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 tHi().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=TR_({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=eoe(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:B0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var vYi=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=UMe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=eoe(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:B0({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var WMe=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(ew(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(`\\${jkt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(jkt))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(jkt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(jkt.length),exampleName:n}}};var tru=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:Nne.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:Nne.query(Jtu({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:Nne.body(u)}}if(oB(i.body)){let u=y1c({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Nne.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:Nne.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return h1c({typeResolver:this.typeResolver,file:bNa(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 tS=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=UMe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=eoe(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=fR(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:B0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:B0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return W2({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:Yc.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:Yc.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:Yc.container(Dy.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:Yc.container(Dy.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:Yc.container(Dy.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:Yc.container(Dy.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:Yc.container(Dy.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:Yc.container(Dy.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($1i(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=ONa({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||eoe(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 HHt=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:$pi({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 rru(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function MR({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=JZ({generationLanguage:t,keywords:r,smartCasing:i}),O=new MQi(a),m=$pi({casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents}),w=(e.definition.rootApiFile.contents.errors??[]).map(ot=>({error:oqi({errorName:ot,file:m}),docs:void 0})),E=new tS(e),q=new yYi(e),M=new tru(E,q),D=new vYi(e),C=new WMe(E),x=new HHt,I=sBa({casingsGenerator:g,rawApiFileSchema:e.definition.rootApiFile.contents})?.environmentsConfig,F={selfHosted:!1,fdrApiDefinitionId:s,apiVersion:pR_({file:m,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:g.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:hNa(e.definition.rootApiFile.contents.docs),auth:dR_({rawApiFileSchema:e.definition.rootApiFile.contents,file:m,propertyResolver:M,endpointResolver:q}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([ot,at])=>$Fe({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])=>$Fe({headerKey:ot,header:at,file:m})):[],types:{},errors:{},services:{},constants:tR_(g),environments:I,errorDiscriminationStrategy:vR_(e.definition.rootApiFile.contents["error-discrimination"],m),basePath:e.definition.rootApiFile.contents["base-path"]!=null?uF(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:ILn({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:m,location:pRe.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 Ztu,K=ot=>{V.addSubpackage(ot.fernFilepath),Vw(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(lRe(me))continue;let wt=DR_({typeName:me,typeDeclaration:we,file:ot,typeResolver:E,exampleResolver:C,sourceResolver:o,workspace:e}),Ot=wt.typeDeclaration;n.disabled&&(Ot.userProvidedExamples=[],Ot.autogeneratedExamples=[]);let Tr=wt.descendantFilepaths,fr=qm.generateTypeId(Ot.name);F.types[fr]=Ot,V.addType(fr,Ot),O.addType({declaredTypeName:Ot.name,descendantTypeIds:Ot.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:wt.propertiesByAudience,descendantFilepaths:Tr}),O.markTypeForAudiences(Ot.name,ox_(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,wt]of Object.entries(at)){let Ot=hR_({errorName:we,errorDeclaration:wt,file:ot,typeResolver:E,exampleResolver:C,workspace:e}),Tr=qm.generateErrorId(Ot.name);F.errors[Tr]=Ot,V.addError(Tr,Ot),O.addError(Ot)}},service:at=>{if(at==null)return;let me=Xx_({rootDefaultUrl:ot.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:F.pathParameters,serviceDefinition:at,file:ot,errorResolver:D,typeResolver:E,propertyResolver:M,exampleResolver:C,sourceResolver:o,globalErrors:w,variableResolver:x,workspace:e}),we=qm.generateServiceId(me.name);F.services[we]=me,V.addService(we,me);let wt={};me.endpoints.forEach(Ot=>{n.disabled&&(Ot.autogeneratedExamples=[],Ot.userSpecifiedExamples=[]);let Tr=at.endpoints[Ot.name.originalName];O.addEndpoint(me,Ot,Tr),wt[Ot.name.originalName]=Ot}),at.audiences!=null&&O.markEndpointForAudience(me.name,me.endpoints,at.audiences),Object.entries(at.endpoints).map(([Ot,Tr])=>{let fr=wt[Ot];fr!=null&&Tr.audiences!=null&&O.markEndpointForAudience(me.name,[fr],Tr.audiences)})},webhooks:at=>{if(at==null)return;let me=qm.generateWebhookGroupId(ot.fernFilepath),we=gR_({webhooks:at,file:ot,typeResolver:E,exampleResolver:C,workspace:e}),wt={};for(let Ot of we)wt[Ot.name.originalName]=Ot;Object.entries(at).forEach(([Ot,Tr])=>{let fr=wt[Ot];fr!=null&&(O.addWebhook(ot.fernFilepath,fr,Tr),Tr.audiences!=null&&O.markWebhookForAudiences(ot.fernFilepath,fr,Tr.audiences))}),F.webhookGroups[me]=we,V.addWebhookGroup(me,ot.fernFilepath)},channel:at=>{if(at==null)return;let me=qm.generateWebSocketChannelId(ot.fernFilepath),we=_R_({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))}})};x3(e,(ot,at,me)=>{K(B0({relativeFilepath:ot,definitionFile:at,casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:me.defaultUrl}))}),RJi(e,(ot,at)=>{if(at.navigation!=null)if(typeof at.navigation=="string")V.addPackageRedirection({from:foe({relativeFilepath:ot,casingsGenerator:g}),to:foe({relativeFilepath:LN(Dxe(ot),ty.of(at.navigation)),casingsGenerator:g})});else{let me=at.navigation.map(we=>qm.generateSubpackageId(foe({relativeFilepath:LN(Dxe(ot),ty.of(we)),casingsGenerator:g})));ot===J1?V.sortRootPackage(me):V.sortSubpackage(qm.generateSubpackageId(foe({relativeFilepath:ot,casingsGenerator:g})),me)}}),F.serviceTypeReferenceInfo=Q5E(O),MR_(F);let Y=n.disabled?F:uBa({ir:F,exampleGeneration:n}),Z=e.definition.rootApiFile.contents,oe=I?.environments._visit({singleBaseUrl:ot=>ot.environments.filter(at=>rru(at.id,Z.environments)!=null).length===0,multipleBaseUrls:ot=>ot.environments.filter(at=>rru(at.id,Z.environments)!=null).length===0,_other:()=>!1});I?.environments.environments.forEach(ot=>{O.markEnvironmentForAudiences(ot,rru(ot.id,Z.environments)??[],oe)});let pe=O.hasNoAudiences()?void 0:O.build(),de=gsc(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")),bt=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:bt,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?bR_({readme:u,services:F.services}):void 0,Pe=G5E({...de,...V.build(pe),sdkConfig:Te,readmeConfig:xt});return{...Pe,dynamic:kx_({ir:Pe,generatorConfig:b,disableExamples:c,generationLanguage:t,smartCasing:i})}}function G5E(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]=hNa(n):n&&typeof n=="object"&&t(n)}return r};return t(e)}function Q5E(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 CR_(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var IR_=ui(IBn(),1);var BR_=["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 $Ht(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,IR_.default)(e,{special:BR_}).replace(/V\s(\d)/g,"V$1")}function wNa(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&CR_(e),r._other(e))}}}function anr(e){return typeof e.subpackageId=="string"}function bYi(e,t){return`${e} ${TC(t)}`}function TC(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function GFe(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var D1c="__package__",cqi=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;#c=new Map;#l=new Map;#p=new Map;#_=new Map;static getSubpackageId(t){return anr(t)?t.subpackageId:D1c}getSubpackageByIdOrLocator(t){if(t==null)return;let r=s4.SubpackageId(t),i=s4.SubpackageId(`subpackage_${h_(t)}`);return r===D1c?this.api.rootPackage:this.api.subpackages[r]??this.#_.get(r)??this.api.subpackages[i]??this.#_.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=s4.SubpackageId(e.getSubpackageId(i)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map,grpcs:new Map};this.#f.set(n,a),i.endpoints.forEach(u=>{if(u.protocol?.type==="grpc"){a.grpcs.set(u.id,u);let l=e.createGrpcId(u,n);this.#n.set(l,u)}else{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} ${TC(u.path.parts)}`),d.push(`${o} ${GFe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${_b(c.baseUrl,TC(u.path.parts))}`),d.push(`${o} ${_b(c.baseUrl,GFe(u.path.parts))}`);let b=iru(c);b!=null&&(d.push(`${o} ${_b(b,TC(u.path.parts))}`),d.push(`${o} ${_b(b,GFe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering endpoint locator: ${o}`),this.#u.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} ${TC(u.path.parts)}`),d.push(`${o} ${GFe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${_b(c.baseUrl,TC(u.path.parts))}`),d.push(`${o} ${_b(c.baseUrl,GFe(u.path.parts))}`);let b=iru(c);b!=null&&(d.push(`${o} ${_b(b,TC(u.path.parts))}`),d.push(`${o} ${_b(b,GFe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering websocket locator: ${o}`),this.#c.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.#i.set(i,n)}),this.#t.forEach((i,n)=>{this.#a.set(i,n)}),this.#r.forEach((i,n)=>{this.#o.set(i,n)}),this.#n.forEach((i,n)=>{this.#s.set(i,n)}),this.#h(t.rootPackage,[])}#h(t,r){if(t==null)return;let i=anr(t)?[...r,t.name]:r,n=i.length===0?[D1c]:i;if([n.join("."),n.join("/"),`${n.join(".")}.yml`].forEach(u=>{this.context?.logger.trace(`Registering subpackage locator: ${u}`),this.#_.set(u,t)}),t.pointsTo!=null)return this.#h(this.api.subpackages[t.pointsTo],i);t.endpoints.forEach(u=>{if(u.protocol?.type==="grpc")return;let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering endpoint locator: ${s}`),this.#u.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.#c.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.#l.set(s,u)})}),t.subpackages.forEach(u=>{this.#h(this.api.subpackages[u],i)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#r}get grpcs(){return this.#n}get endpointsByLocator(){return this.#u}get webSocketsByLocator(){return this.#c}get webhooksByLocator(){return this.#l}get grpcsByLocator(){return this.#p}get subpackages(){return this.#f}get subpackagesByLocator(){return this.#_}get subpackageLocators(){return new Set(this.#_.keys())}getEndpointId(t){return this.#i.get(t)}getWebSocketId(t){return this.#a.get(t)}getWebhookId(t){return this.#o.get(t)}getGrpcId(t){return this.#s.get(t)}static createEndpointId(t,r){return Oo.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return Oo.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return Oo.WebhookId(`${r}.${t.id}`)}static createGrpcId(t,r){return Oo.GrpcId(`${r}.${t.id}`)}};function iru(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 zLn=ui(Gko(),1),xR_=ui(Qko(),1);function zR_(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{}}zLn.default.extend(xR_.default);var J5E="Changelog",K5E=["summary","index","overview"],Qpi=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??J5E,i=[],n;for(let b of this.changelogFiles??[]){let g=qzs(b.split("/"));if(g==null)continue;let O=zR_(g);if(O==null){let w=g.split(".")[0]?.toLowerCase();w!=null&&K5E.includes(w)&&(n=b);continue}let m=this.toRelativeFilepath(b);i.push({date:O,pageId:Oo.PageId(m),absoluteFilepath:b})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??Vq(r)}),u=n!=null?this.markdownToNoIndex.get(n):void 0,l=i.map(b=>{let g=zLn.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=E1c(l,b=>b.date,"desc"),s=n!=null?Oo.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=zLn.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return E1c(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=zLn.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return E1c(Array.from(n.entries()).map(([a,u])=>{let l=(0,zLn.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 Hq(this.docsWorkspace.absoluteFilePath,t)}};function E1c(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 nru(e){if(e)return{environments:e.environments!=null&&e.environments.length>0?e.environments.map(t=>Oo.V1.EnvironmentId(t)):void 0,button:e.button!=null&&e.button.href?{href:Oo.V1.Url(e.button.href)}:void 0,"limit-websocket-messages-per-connection":e.limitWebsocketMessagesPerConnection!=null?e.limitWebsocketMessagesPerConnection:void 0}}function SNa({child:e,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i}){if(e.type==="apiPackage"){let n=Oo.V1.SlugGenerator.init(e.slug),u=(t.get(e.id)??[]).flatMap(s=>r(s,n)),l=e.children.map(s=>SNa({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),d=i(l,u);return{...e,children:d,pointsTo:void 0}}return e}var WR_=ui(LR_(),1);var eC=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(u){u(a)})}return new(r||(r=Promise))(function(a,u){function l(o){try{s(i.next(o))}catch(c){u(c)}}function d(o){try{s(i.throw(o))}catch(c){u(c)}}function s(o){o.done?a(o.value):n(o.value).then(l,d)}s((i=i.apply(e,t||[])).next())})},rT=function(e,t){var r={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,n,a,u=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return u.next=l(0),u.throw=l(1),u.return=l(2),typeof Symbol=="function"&&(u[Symbol.iterator]=function(){return this}),u;function l(s){return function(o){return d([s,o])}}function d(s){if(i)throw new TypeError("Generator is already executing.");for(;u&&(u=0,s[0]&&(r=0)),r;)try{if(i=1,n&&(a=s[0]&2?n.return:s[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,s[1])).done)return a;switch(n=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return r.label++,{value:s[1],done:!1};case 5:r.label++,n=s[1],s=[0];continue;case 7:s=r.ops.pop(),r.trys.pop();continue;default:if(a=r.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){r=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){r.label=s[1];break}if(s[0]===6&&r.label<a[1]){r.label=a[1],a=s;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(s);break}a[2]&&r.ops.pop(),r.trys.pop();continue}s=t.call(e,r)}catch(o){s=[6,o],n=0}finally{i=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},poe=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var i=r.call(e),n,a=[],u;try{for(;(t===void 0||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(l){u={error:l}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(u)throw u.error}}return a},QFe=function(e,t,r){if(r||arguments.length===2)for(var i=0,n=t.length,a;i<n;i++)(a||!(i in t))&&(a||(a=Array.prototype.slice.call(t,0,i)),a[i]=t[i]);return e.concat(a||Array.prototype.slice.call(t))},UR_=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],i=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},v45=function(){function e(t){t===void 0&&(t=e.minComparator);var r=this;this.compare=t,this.heapArray=[],this._limit=0,this.offer=this.add,this.element=this.peek,this.poll=this.pop,this._invertedCompare=function(i,n){return r.compare(i,n).then(function(a){return-1*a})}}return e.getChildrenIndexOf=function(t){return[t*2+1,t*2+2]},e.getParentIndexOf=function(t){if(t<=0)return-1;var r=t%2?1:2;return Math.floor((t-r)/2)},e.getSiblingIndexOf=function(t){if(t<=0)return-1;var r=t%2?1:-1;return t+r},e.minComparator=function(t,r){return eC(this,void 0,void 0,function(){return rT(this,function(i){return t>r?[2,1]:t<r?[2,-1]:[2,0]})})},e.maxComparator=function(t,r){return eC(this,void 0,void 0,function(){return rT(this,function(i){return r>t?[2,1]:r<t?[2,-1]:[2,0]})})},e.minComparatorNumber=function(t,r){return eC(this,void 0,void 0,function(){return rT(this,function(i){return[2,t-r]})})},e.maxComparatorNumber=function(t,r){return eC(this,void 0,void 0,function(){return rT(this,function(i){return[2,r-t]})})},e.defaultIsEqual=function(t,r){return eC(this,void 0,void 0,function(){return rT(this,function(i){return[2,t===r]})})},e.print=function(t){function r(o){var c=e.getParentIndexOf(o);return Math.floor(Math.log2(c+1))}function i(o,c){for(var b="";c>0;--c)b+=o;return b}for(var n=0,a=[],u=r(t.length-1)+2,l=0;n<t.length;){var d=r(n)+1;n===0&&(d=0);var s=String(t.get(n));s.length>l&&(l=s.length),a[d]=a[d]||[],a[d].push(s),n+=1}return a.map(function(o,c){var b=Math.pow(2,u-c)-1;return i(" ",Math.floor(b/2)*l)+o.map(function(g){var O=(l-g.length)/2;return i(" ",Math.ceil(O))+g+i(" ",Math.floor(O))}).join(i(" ",b*l))}).join(`
|
|
2050
2050
|
`)},e.heapify=function(t,r){return eC(this,void 0,void 0,function(){var i;return rT(this,function(n){switch(n.label){case 0:return i=new e(r),i.heapArray=t,[4,i.init()];case 1:return n.sent(),[2,i]}})})},e.heappop=function(t,r){var i=new e(r);return i.heapArray=t,i.pop()},e.heappush=function(t,r,i){return eC(this,void 0,void 0,function(){var n;return rT(this,function(a){switch(a.label){case 0:return n=new e(i),n.heapArray=t,[4,n.push(r)];case 1:return a.sent(),[2]}})})},e.heappushpop=function(t,r,i){var n=new e(i);return n.heapArray=t,n.pushpop(r)},e.heapreplace=function(t,r,i){var n=new e(i);return n.heapArray=t,n.replace(r)},e.heaptop=function(t,r,i){r===void 0&&(r=1);var n=new e(i);return n.heapArray=t,n.top(r)},e.heapbottom=function(t,r,i){r===void 0&&(r=1);var n=new e(i);return n.heapArray=t,n.bottom(r)},e.nlargest=function(t,r,i){return eC(this,void 0,void 0,function(){var n;return rT(this,function(a){switch(a.label){case 0:return n=new e(i),n.heapArray=QFe([],poe(r),!1),[4,n.init()];case 1:return a.sent(),[2,n.top(t)]}})})},e.nsmallest=function(t,r,i){return eC(this,void 0,void 0,function(){var n;return rT(this,function(a){switch(a.label){case 0:return n=new e(i),n.heapArray=QFe([],poe(r),!1),[4,n.init()];case 1:return a.sent(),[2,n.bottom(t)]}})})},e.prototype.add=function(t){return eC(this,void 0,void 0,function(){return rT(this,function(r){switch(r.label){case 0:return[4,this._sortNodeUp(this.heapArray.push(t)-1)];case 1:return r.sent(),this._applyLimit(),[2,!0]}})})},e.prototype.addAll=function(t){return eC(this,void 0,void 0,function(){var r,i,n;return rT(this,function(a){switch(a.label){case 0:r=this.length,(n=this.heapArray).push.apply(n,QFe([],poe(t),!1)),i=this.length,a.label=1;case 1:return r<i?[4,this._sortNodeUp(r)]:[3,4];case 2:a.sent(),a.label=3;case 3:return++r,[3,1];case 4:return this._applyLimit(),[2,!0]}})})},e.prototype.bottom=function(){return eC(this,arguments,void 0,function(t){return t===void 0&&(t=1),rT(this,function(r){return this.heapArray.length===0||t<=0?[2,[]]:this.heapArray.length===1?[2,[this.heapArray[0]]]:t>=this.heapArray.length?[2,QFe([],poe(this.heapArray),!1)]:[2,this._bottomN_push(~~t)]})})},e.prototype.check=function(){return eC(this,void 0,void 0,function(){var t,r,i,n,a,u,l,d,s;return rT(this,function(o){switch(o.label){case 0:t=0,o.label=1;case 1:if(!(t<this.heapArray.length))return[3,10];r=this.heapArray[t],i=this.getChildrenOf(t),o.label=2;case 2:o.trys.push([2,7,8,9]),n=(d=void 0,UR_(i)),a=n.next(),o.label=3;case 3:return a.done?[3,6]:(u=a.value,[4,this.compare(r,u)]);case 4:if(o.sent()>0)return[2,r];o.label=5;case 5:return a=n.next(),[3,3];case 6:return[3,9];case 7:return l=o.sent(),d={error:l},[3,9];case 8:try{a&&!a.done&&(s=n.return)&&s.call(n)}finally{if(d)throw d.error}return[7];case 9:return++t,[3,1];case 10:return[2]}})})},e.prototype.clear=function(){this.heapArray=[]},e.prototype.clone=function(){var t=new e(this.comparator());return t.heapArray=this.toArray(),t._limit=this._limit,t},e.prototype.comparator=function(){return this.compare},e.prototype.contains=function(t){return eC(this,arguments,void 0,function(r,i){var n,a,u,l,d,s;return i===void 0&&(i=e.defaultIsEqual),rT(this,function(o){switch(o.label){case 0:o.trys.push([0,5,6,7]),n=UR_(this.heapArray),a=n.next(),o.label=1;case 1:return a.done?[3,4]:(u=a.value,[4,i(u,r)]);case 2:if(o.sent())return[2,!0];o.label=3;case 3:return a=n.next(),[3,1];case 4:return[3,7];case 5:return l=o.sent(),d={error:l},[3,7];case 6:try{a&&!a.done&&(s=n.return)&&s.call(n)}finally{if(d)throw d.error}return[7];case 7:return[2,!1]}})})},e.prototype.init=function(t){return eC(this,void 0,void 0,function(){var r;return rT(this,function(i){switch(i.label){case 0:t&&(this.heapArray=QFe([],poe(t),!1)),r=Math.floor(this.heapArray.length),i.label=1;case 1:return r>=0?[4,this._sortNodeDown(r)]:[3,4];case 2:i.sent(),i.label=3;case 3:return--r,[3,1];case 4:return this._applyLimit(),[2]}})})},e.prototype.isEmpty=function(){return this.length===0},e.prototype.leafs=function(){if(this.heapArray.length===0)return[];var t=e.getParentIndexOf(this.heapArray.length-1);return this.heapArray.slice(t+1)},Object.defineProperty(e.prototype,"length",{get:function(){return this.heapArray.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"limit",{get:function(){return this._limit},set:function(t){this._limit=~~t,this._applyLimit()},enumerable:!1,configurable:!0}),e.prototype.peek=function(){return this.heapArray[0]},e.prototype.pop=function(){return eC(this,void 0,void 0,function(){var t;return rT(this,function(r){return t=this.heapArray.pop(),this.length>0&&t!==void 0?[2,this.replace(t)]:[2,t]})})},e.prototype.push=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return eC(this,void 0,void 0,function(){return rT(this,function(i){return t.length<1?[2,!1]:t.length===1?[2,this.add(t[0])]:[2,this.addAll(t)]})})},e.prototype.pushpop=function(t){return eC(this,void 0,void 0,function(){var r;return rT(this,function(i){switch(i.label){case 0:return[4,this.compare(this.heapArray[0],t)];case 1:return i.sent()<0?(r=poe([this.heapArray[0],t],2),t=r[0],this.heapArray[0]=r[1],[4,this._sortNodeDown(0)]):[3,3];case 2:i.sent(),i.label=3;case 3:return[2,t]}})})},e.prototype.remove=function(t){return eC(this,arguments,void 0,function(r,i){var n,a,u,l=this;return i===void 0&&(i=e.defaultIsEqual),rT(this,function(d){switch(d.label){case 0:return this.heapArray.length?r!==void 0?[3,2]:[4,this.pop()]:[2,!1];case 1:return d.sent(),[2,!0];case 2:n=[0],d.label=3;case 3:return n.length?(a=n.shift(),[4,i(this.heapArray[a],r)]):[3,13];case 4:return d.sent()?a!==0?[3,6]:[4,this.pop()]:[3,11];case 5:return d.sent(),[3,10];case 6:return a!==this.heapArray.length-1?[3,7]:(this.heapArray.pop(),[3,10]);case 7:return this.heapArray.splice(a,1,this.heapArray.pop()),[4,this._sortNodeUp(a)];case 8:return d.sent(),[4,this._sortNodeDown(a)];case 9:d.sent(),d.label=10;case 10:return[2,!0];case 11:u=e.getChildrenIndexOf(a).filter(function(s){return s<l.heapArray.length}),n.push.apply(n,QFe([],poe(u),!1)),d.label=12;case 12:return[3,3];case 13:return[2,!1]}})})},e.prototype.replace=function(t){return eC(this,void 0,void 0,function(){var r;return rT(this,function(i){switch(i.label){case 0:return r=this.heapArray[0],this.heapArray[0]=t,[4,this._sortNodeDown(0)];case 1:return i.sent(),[2,r]}})})},e.prototype.size=function(){return this.length},e.prototype.top=function(){return eC(this,arguments,void 0,function(t){return t===void 0&&(t=1),rT(this,function(r){return this.heapArray.length===0||t<=0?[2,[]]:this.heapArray.length===1||t===1?[2,[this.heapArray[0]]]:t>=this.heapArray.length?[2,QFe([],poe(this.heapArray),!1)]:[2,this._topN_push(~~t)]})})},e.prototype.toArray=function(){return QFe([],poe(this.heapArray),!1)},e.prototype.toString=function(){return this.heapArray.toString()},e.prototype.get=function(t){return this.heapArray[t]},e.prototype.getChildrenOf=function(t){var r=this;return e.getChildrenIndexOf(t).map(function(i){return r.heapArray[i]}).filter(function(i){return i!==void 0})},e.prototype.getParentOf=function(t){var r=e.getParentIndexOf(t);return this.heapArray[r]},e.prototype[Symbol.iterator]=function(){return rT(this,function(t){switch(t.label){case 0:return this.length?[4,this.pop()]:[3,2];case 1:return t.sent(),[3,0];case 2:return[2]}})},e.prototype.iterator=function(){return this},e.prototype._applyLimit=function(){if(this._limit&&this._limit<this.heapArray.length)for(var t=this.heapArray.length-this._limit;t;)this.heapArray.pop(),--t},e.prototype._bottomN_push=function(t){return eC(this,void 0,void 0,function(){var r,i,n,a,l,u,l;return rT(this,function(d){switch(d.label){case 0:return r=new e(this.compare),r.limit=t,r.heapArray=this.heapArray.slice(-t),[4,r.init()];case 1:for(d.sent(),i=this.heapArray.length-1-t,n=e.getParentIndexOf(i),a=[],l=i;l>n;--l)a.push(l);u=this.heapArray,d.label=2;case 2:return a.length?(l=a.shift(),[4,this.compare(u[l],r.peek())]):[3,6];case 3:return d.sent()>0?[4,r.replace(u[l])]:[3,5];case 4:d.sent(),l%2&&a.push(e.getParentIndexOf(l)),d.label=5;case 5:return[3,2];case 6:return[2,r.toArray()]}})})},e.prototype._moveNode=function(t,r){var i;i=poe([this.heapArray[r],this.heapArray[t]],2),this.heapArray[t]=i[0],this.heapArray[r]=i[1]},e.prototype._sortNodeDown=function(t){return eC(this,void 0,void 0,function(){var r,i,n,a,u,l;return rT(this,function(d){switch(d.label){case 0:r=this.heapArray.length,d.label=1;case 1:return i=2*t+1,n=i+1,a=t,u=i<r,u?[4,this.compare(this.heapArray[i],this.heapArray[a])]:[3,3];case 2:u=d.sent()<0,d.label=3;case 3:return u&&(a=i),l=n<r,l?[4,this.compare(this.heapArray[n],this.heapArray[a])]:[3,5];case 4:l=d.sent()<0,d.label=5;case 5:if(l&&(a=n),a===t)return[3,7];this._moveNode(t,a),t=a,d.label=6;case 6:return[3,1];case 7:return[2]}})})},e.prototype._sortNodeUp=function(t){return eC(this,void 0,void 0,function(){var r;return rT(this,function(i){switch(i.label){case 0:return t>0?(r=e.getParentIndexOf(t),[4,this.compare(this.heapArray[t],this.heapArray[r])]):[3,2];case 1:if(i.sent()<0)this._moveNode(t,r),t=r;else return[3,2];return[3,0];case 2:return[2]}})})},e.prototype._topN_push=function(t){return eC(this,void 0,void 0,function(){var r,i,n,a;return rT(this,function(u){switch(u.label){case 0:r=new e(this._invertedCompare),r.limit=t,i=[0],n=this.heapArray,u.label=1;case 1:return i.length?(a=i.shift(),a<n.length?r.length<t?[4,r.push(n[a])]:[3,3]:[3,6]):[3,7];case 2:return u.sent(),i.push.apply(i,QFe([],poe(e.getChildrenIndexOf(a)),!1)),[3,6];case 3:return[4,this.compare(n[a],r.peek())];case 4:return u.sent()<0?[4,r.replace(n[a])]:[3,6];case 5:u.sent(),i.push.apply(i,QFe([],poe(e.getChildrenIndexOf(a)),!1)),u.label=6;case 6:return[3,1];case 7:return[2,r.toArray()]}})})},e.prototype._topN_fill=function(t){return eC(this,void 0,void 0,function(){var r,i,n,a,u,u;return rT(this,function(l){switch(l.label){case 0:return r=this.heapArray,i=new e(this._invertedCompare),i.limit=t,i.heapArray=r.slice(0,t),[4,i.init()];case 1:for(l.sent(),n=e.getParentIndexOf(t-1)+1,a=[],u=n;u<t;++u)a.push.apply(a,QFe([],poe(e.getChildrenIndexOf(u).filter(function(d){return d<r.length})),!1));(t-1)%2&&a.push(t),l.label=2;case 2:return a.length?(u=a.shift(),u<r.length?[4,this.compare(r[u],i.peek())]:[3,5]):[3,6];case 3:return l.sent()<0?[4,i.replace(r[u])]:[3,5];case 4:l.sent(),a.push.apply(a,QFe([],poe(e.getChildrenIndexOf(u)),!1)),l.label=5;case 5:return[3,2];case 6:return[2,i.toArray()]}})})},e.prototype._topN_heap=function(t){return eC(this,void 0,void 0,function(){var r,i,n,a,u;return rT(this,function(l){switch(l.label){case 0:r=this.clone(),i=[],n=0,l.label=1;case 1:return n<t?(u=(a=i).push,[4,r.pop()]):[3,4];case 2:u.apply(a,[l.sent()]),l.label=3;case 3:return++n,[3,1];case 4:return[2,i]}})})},e.prototype._topIdxOf=function(t){return eC(this,void 0,void 0,function(){var r,i,n,a;return rT(this,function(u){switch(u.label){case 0:if(!t.length)return[2,-1];r=0,i=t[r],n=1,u.label=1;case 1:return n<t.length?[4,this.compare(t[n],i)]:[3,4];case 2:a=u.sent(),a<0&&(r=n,i=t[n]),u.label=3;case 3:return++n,[3,1];case 4:return[2,r]}})})},e.prototype._topOf=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return eC(this,void 0,void 0,function(){var i;return rT(this,function(n){switch(n.label){case 0:return i=new e(this.compare),[4,i.init(t)];case 1:return n.sent(),[2,i.peek()]}})})},e}(),k5E=function(e,t){var r={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,n,a,u=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return u.next=l(0),u.throw=l(1),u.return=l(2),typeof Symbol=="function"&&(u[Symbol.iterator]=function(){return this}),u;function l(s){return function(o){return d([s,o])}}function d(s){if(i)throw new TypeError("Generator is already executing.");for(;u&&(u=0,s[0]&&(r=0)),r;)try{if(i=1,n&&(a=s[0]&2?n.return:s[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,s[1])).done)return a;switch(n=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return r.label++,{value:s[1],done:!1};case 5:r.label++,n=s[1],s=[0];continue;case 7:s=r.ops.pop(),r.trys.pop();continue;default:if(a=r.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){r=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){r.label=s[1];break}if(s[0]===6&&r.label<a[1]){r.label=a[1],a=s;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(s);break}a[2]&&r.ops.pop(),r.trys.pop();continue}s=t.call(e,r)}catch(o){s=[6,o],n=0}finally{i=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},yH=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var i=r.call(e),n,a=[],u;try{for(;(t===void 0||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(l){u={error:l}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(u)throw u.error}}return a},pk=function(e,t,r){if(r||arguments.length===2)for(var i=0,n=t.length,a;i<n;i++)(a||!(i in t))&&(a||(a=Array.prototype.slice.call(t,0,i)),a[i]=t[i]);return e.concat(a||Array.prototype.slice.call(t))};var VR_=function(){function e(t){t===void 0&&(t=e.minComparator);var r=this;this.compare=t,this.heapArray=[],this._limit=0,this.offer=this.add,this.element=this.peek,this.poll=this.pop,this.removeAll=this.clear,this._invertedCompare=function(i,n){return-1*r.compare(i,n)}}return e.getChildrenIndexOf=function(t){return[t*2+1,t*2+2]},e.getParentIndexOf=function(t){if(t<=0)return-1;var r=t%2?1:2;return Math.floor((t-r)/2)},e.getSiblingIndexOf=function(t){if(t<=0)return-1;var r=t%2?1:-1;return t+r},e.minComparator=function(t,r){return t>r?1:t<r?-1:0},e.maxComparator=function(t,r){return r>t?1:r<t?-1:0},e.minComparatorNumber=function(t,r){return t-r},e.maxComparatorNumber=function(t,r){return r-t},e.defaultIsEqual=function(t,r){return t===r},e.print=function(t){function r(o){var c=e.getParentIndexOf(o);return Math.floor(Math.log2(c+1))}function i(o,c){for(var b="";c>0;--c)b+=o;return b}for(var n=0,a=[],u=r(t.length-1)+2,l=0;n<t.length;){var d=r(n)+1;n===0&&(d=0);var s=String(t.get(n));s.length>l&&(l=s.length),a[d]=a[d]||[],a[d].push(s),n+=1}return a.map(function(o,c){var b=Math.pow(2,u-c)-1;return i(" ",Math.floor(b/2)*l)+o.map(function(g){var O=(l-g.length)/2;return i(" ",Math.ceil(O))+g+i(" ",Math.floor(O))}).join(i(" ",b*l))}).join(`
|
|
2051
2051
|
`)},e.heapify=function(t,r){var i=new e(r);return i.heapArray=t,i.init(),i},e.heappop=function(t,r){var i=new e(r);return i.heapArray=t,i.pop()},e.heappush=function(t,r,i){var n=new e(i);n.heapArray=t,n.push(r)},e.heappushpop=function(t,r,i){var n=new e(i);return n.heapArray=t,n.pushpop(r)},e.heapreplace=function(t,r,i){var n=new e(i);return n.heapArray=t,n.replace(r)},e.heaptop=function(t,r,i){r===void 0&&(r=1);var n=new e(i);return n.heapArray=t,n.top(r)},e.heapbottom=function(t,r,i){r===void 0&&(r=1);var n=new e(i);return n.heapArray=t,n.bottom(r)},e.nlargest=function(t,r,i){var n=new e(i);return n.heapArray=pk([],yH(r),!1),n.init(),n.top(t)},e.nsmallest=function(t,r,i){var n=new e(i);return n.heapArray=pk([],yH(r),!1),n.init(),n.bottom(t)},e.prototype.add=function(t){return this._sortNodeUp(this.heapArray.push(t)-1),this._applyLimit(),!0},e.prototype.addAll=function(t){var r,i=this.length;(r=this.heapArray).push.apply(r,pk([],yH(t),!1));for(var n=this.length;i<n;++i)this._sortNodeUp(i);return this._applyLimit(),!0},e.prototype.bottom=function(t){return t===void 0&&(t=1),this.heapArray.length===0||t<=0?[]:this.heapArray.length===1?[this.heapArray[0]]:t>=this.heapArray.length?pk([],yH(this.heapArray),!1):this._bottomN_push(~~t)},e.prototype.check=function(){var t=this;return this.heapArray.find(function(r,i){return!!t.getChildrenOf(i).find(function(n){return t.compare(r,n)>0})})},e.prototype.clear=function(){this.heapArray=[]},e.prototype.clone=function(){var t=new e(this.comparator());return t.heapArray=this.toArray(),t._limit=this._limit,t},e.prototype.comparator=function(){return this.compare},e.prototype.contains=function(t,r){return r===void 0&&(r=e.defaultIsEqual),this.indexOf(t,r)!==-1},e.prototype.init=function(t){t&&(this.heapArray=pk([],yH(t),!1));for(var r=Math.floor(this.heapArray.length);r>=0;--r)this._sortNodeDown(r);this._applyLimit()},e.prototype.isEmpty=function(){return this.length===0},e.prototype.indexOf=function(t,r){if(r===void 0&&(r=e.defaultIsEqual),this.heapArray.length===0)return-1;for(var i=[],n=0;n<this.heapArray.length;){var a=this.heapArray[n];if(r(a,t))return n;this.compare(a,t)<=0&&i.push.apply(i,pk([],yH(e.getChildrenIndexOf(n)),!1)),n=i.shift()||this.heapArray.length}return-1},e.prototype.indexOfEvery=function(t,r){if(r===void 0&&(r=e.defaultIsEqual),this.heapArray.length===0)return[];for(var i=[],n=[],a=0;a<this.heapArray.length;){var u=this.heapArray[a];r(u,t)?(n.push(a),i.push.apply(i,pk([],yH(e.getChildrenIndexOf(a)),!1))):this.compare(u,t)<=0&&i.push.apply(i,pk([],yH(e.getChildrenIndexOf(a)),!1)),a=i.shift()||this.heapArray.length}return n},e.prototype.leafs=function(){if(this.heapArray.length===0)return[];var t=e.getParentIndexOf(this.heapArray.length-1);return this.heapArray.slice(t+1)},Object.defineProperty(e.prototype,"length",{get:function(){return this.heapArray.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"limit",{get:function(){return this._limit},set:function(t){t<0||isNaN(t)?this._limit=0:this._limit=~~t,this._applyLimit()},enumerable:!1,configurable:!0}),e.prototype.setLimit=function(t){return this.limit=t,t<0||isNaN(t)?NaN:this._limit},e.prototype.peek=function(){return this.heapArray[0]},e.prototype.pop=function(){var t=this.heapArray.pop();return this.length>0&&t!==void 0?this.replace(t):t},e.prototype.push=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return t.length<1?!1:t.length===1?this.add(t[0]):this.addAll(t)},e.prototype.pushpop=function(t){var r;return this.compare(this.heapArray[0],t)<0&&(r=yH([this.heapArray[0],t],2),t=r[0],this.heapArray[0]=r[1],this._sortNodeDown(0)),t},e.prototype.remove=function(t,r){var i=this;if(r===void 0&&(r=e.defaultIsEqual),!this.heapArray.length)return!1;if(t===void 0)return this.pop(),!0;for(var n=[0];n.length;){var a=n.shift();if(r(this.heapArray[a],t))return a===0?this.pop():a===this.heapArray.length-1?this.heapArray.pop():(this.heapArray.splice(a,1,this.heapArray.pop()),this._sortNodeUp(a),this._sortNodeDown(a)),!0;if(this.compare(this.heapArray[a],t)<=0){var u=e.getChildrenIndexOf(a).filter(function(l){return l<i.heapArray.length});n.push.apply(n,pk([],yH(u),!1))}}return!1},e.prototype.replace=function(t){var r=this.heapArray[0];return this.heapArray[0]=t,this._sortNodeDown(0),r},e.prototype.size=function(){return this.length},e.prototype.top=function(t){return t===void 0&&(t=1),this.heapArray.length===0||t<=0?[]:this.heapArray.length===1||t===1?[this.heapArray[0]]:t>=this.heapArray.length?pk([],yH(this.heapArray),!1):this._topN_push(~~t)},e.prototype.toArray=function(){return pk([],yH(this.heapArray),!1)},e.prototype.toString=function(){return this.heapArray.toString()},e.prototype.get=function(t){return this.heapArray[t]},e.prototype.getChildrenOf=function(t){var r=this;return e.getChildrenIndexOf(t).map(function(i){return r.heapArray[i]}).filter(function(i){return i!==void 0})},e.prototype.getParentOf=function(t){var r=e.getParentIndexOf(t);return this.heapArray[r]},e.prototype[Symbol.iterator]=function(){return k5E(this,function(t){switch(t.label){case 0:return this.length?[4,this.pop()]:[3,2];case 1:return t.sent(),[3,0];case 2:return[2]}})},e.prototype.iterator=function(){return this.toArray()},e.prototype._applyLimit=function(){if(this._limit>0&&this._limit<this.heapArray.length)for(var t=this.heapArray.length-this._limit;t;)this.heapArray.pop(),--t},e.prototype._bottomN_push=function(t){var r=new e(this.compare);r.limit=t,r.heapArray=this.heapArray.slice(-t),r.init();for(var i=this.heapArray.length-1-t,n=e.getParentIndexOf(i),a=[],u=i;u>n;--u)a.push(u);for(var l=this.heapArray;a.length;){var u=a.shift();this.compare(l[u],r.peek())>0&&(r.replace(l[u]),u%2&&a.push(e.getParentIndexOf(u)))}return r.toArray()},e.prototype._moveNode=function(t,r){var i;i=yH([this.heapArray[r],this.heapArray[t]],2),this.heapArray[t]=i[0],this.heapArray[r]=i[1]},e.prototype._sortNodeDown=function(t){for(var r=this.heapArray.length;;){var i=2*t+1,n=i+1,a=t;if(i<r&&this.compare(this.heapArray[i],this.heapArray[a])<0&&(a=i),n<r&&this.compare(this.heapArray[n],this.heapArray[a])<0&&(a=n),a===t)break;this._moveNode(t,a),t=a}},e.prototype._sortNodeUp=function(t){for(;t>0;){var r=e.getParentIndexOf(t);if(this.compare(this.heapArray[t],this.heapArray[r])<0)this._moveNode(t,r),t=r;else break}},e.prototype._topN_push=function(t){var r=new e(this._invertedCompare);r.limit=t;for(var i=[0],n=this.heapArray;i.length;){var a=i.shift();a<n.length&&(r.length<t?(r.push(n[a]),i.push.apply(i,pk([],yH(e.getChildrenIndexOf(a)),!1))):this.compare(n[a],r.peek())<0&&(r.replace(n[a]),i.push.apply(i,pk([],yH(e.getChildrenIndexOf(a)),!1))))}return r.toArray()},e.prototype._topN_fill=function(t){var r=this.heapArray,i=new e(this._invertedCompare);i.limit=t,i.heapArray=r.slice(0,t),i.init();for(var n=e.getParentIndexOf(t-1)+1,a=[],u=n;u<t;++u)a.push.apply(a,pk([],yH(e.getChildrenIndexOf(u).filter(function(l){return l<r.length})),!1));for((t-1)%2&&a.push(t);a.length;){var u=a.shift();u<r.length&&this.compare(r[u],i.peek())<0&&(i.replace(r[u]),a.push.apply(a,pk([],yH(e.getChildrenIndexOf(u)),!1)))}return i.toArray()},e.prototype._topN_heap=function(t){for(var r=this.clone(),i=[],n=0;n<t;++n)i.push(r.pop());return i},e.prototype._topIdxOf=function(t){if(!t.length)return-1;for(var r=0,i=t[r],n=1;n<t.length;++n){var a=this.compare(t[n],i);a<0&&(r=n,i=t[n])}return r},e.prototype._topOf=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var i=new e(this.compare);return i.init(t),i.peek()},e}();function HR_(e,t,r,i,n){if(r<=0)return[];let a=i??(l=>l),u=new VR_(e9E);for(let l of t){let d=WR_.default.get(a(e),a(l));n!=null&&d>n||(u.push({neighbor:l,distance:d}),u.size()>r&&u.pop())}return t9E(u).reverse().map(l=>l.neighbor)}function e9E(e,t){return e.distance!==t.distance?t.distance-e.distance:t.neighbor.localeCompare(e.neighbor)}function t9E(e){let t=[];for(;e.size()>0;){let r=e.pop();r&&t.push(r)}return t}var r9E=3,i9E=5;function lqi(e,t){let r=HR_(e,t,r9E,n9E,i9E),i=Array.from(t),n=`Failed to locate API section ${e}.`;switch(r.length){case 0:return n=`${n} No similar API sections found. Available API sections:`,i.length===0?`${n} []`:`${n} [
|
|
2052
2052
|
${i.map(a=>` ${a}`).join(`,
|