fern-api 3.26.1 → 3.26.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +3 -3
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1147,7 +1147,7 @@ ${PUp.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&d9s(th
1147
1147
  `+N7i.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?N7i.default.cyan(CUp(t,this.opt.mask)):N7i.default.italic(N7i.default.dim("[hidden]")):this.opt.mask?CUp(t,this.opt.mask):N7i.default.italic(N7i.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 a0o=ce(y1(),1);var C4p=ce(K9s(),1),i0o=require("child_process"),oTn=require("fs"),r0o=ce(require("path"),1),q4p=ce(require("os"),1),T4p=require("crypto"),IGs=ce(B4p(),1);var kmo=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var Xga=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var e0o=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var t0o=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function n0o(e="",t,r){let i=new CGs(e,r);i.runAsync((n,a)=>{if(n)setImmediate(t,n,void 0);else try{i.cleanup(),setImmediate(t,void 0,a)}catch(o){setImmediate(t,o,void 0)}})}function I4p(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function sgS(e){let t=[],r="";for(let i=0;i<e.length;i++){let n=e.charAt(i);i>0&&n===" "&&e[i-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${n}`}return r.length>0&&t.push(r),t}var CGs=class{text="";tempFile;editor;lastExitStatus=0;fileOptions={};get temp_file(){return console.log("DEPRECATED: temp_file. Use tempFile moving forward."),this.tempFile}get last_exit_status(){return console.log("DEPRECATED: last_exit_status. Use lastExitStatus moving forward."),this.lastExitStatus}constructor(t="",r){this.text=t,r&&(this.fileOptions=r),this.determineEditor(),this.createTemporaryFile()}run(){return this.launchEditor(),this.readTemporaryFile(),this.text}runAsync(t){try{this.launchEditorAsync(()=>{try{this.readTemporaryFile(),setImmediate(t,void 0,this.text)}catch(r){setImmediate(t,r,void 0)}})}catch(r){setImmediate(t,r,void 0)}}cleanup(){this.removeTemporaryFile()}determineEditor(){let t=process.env.VISUAL?process.env.VISUAL:process.env.EDITOR?process.env.EDITOR:process.platform.startsWith("win")?"notepad":"vim",r=sgS(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??q4p.default.tmpdir(),r=(0,T4p.randomUUID)(),i=I4p(this.fileOptions.prefix),n=I4p(this.fileOptions.postfix),a=`${i}${r}${n}`,o=r0o.default.resolve(t,a),c=r0o.default.resolve(t)+r0o.default.sep;if(!o.startsWith(c))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=o;let f={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(f.mode=this.fileOptions.mode),(0,oTn.writeFileSync)(this.tempFile,this.text,f)}catch(t){throw new kmo(t)}}readTemporaryFile(){try{let t=(0,oTn.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,C4p.detect)(t)??"utf8";IGs.default.encodingExists(r)||(r="utf8"),this.text=IGs.default.decode(t,r)}}catch(t){throw new e0o(t)}}removeTemporaryFile(){try{(0,oTn.unlinkSync)(this.tempFile)}catch(t){throw new t0o(t)}}launchEditor(){try{let t=(0,i0o.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new Xga(t)}}launchEditorAsync(t){try{(0,i0o.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new Xga(r)}}};var R4p=ce(k_e(),1);var Zga=class extends b1{_run(t){this.done=t,this.editorResult=new R4p.Subject;let r=TQ(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"?a0o.default.dim("Received"):a0o.default.dim("Press <enter> to launch your preferred editor."),t&&(r=a0o.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),n0o(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 U4p=require("stream");var F4p=ce(require("readline"),1),Q4p=ce(N4p(),1),L7i=class{constructor(t){this.rl||=F4p.default.createInterface(lgS(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 lgS(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 Q4p.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var kga=class extends L7i{constructor(t={}){super(t),this.log=new U4p.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return zga(this.rl,this.bottomBar.split(`
1148
1148
  `).length),this}updateBottomBar(t){return zga(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+`
1149
1149
  `}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&&Smo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var pO=ce(k_e(),1),W4p=ce(iga(),1);var o0o=ce(k_e(),1),L4p=ce(iga(),1),u0o=function(e,t,r){return typeof e[t]!="function"?(0,o0o.of)(e):(0,o0o.from)((0,L4p.default)(e[t])(r).then(i=>(e[t]=i,e)))};var V4p={set:(e,t="",r)=>{let i=e;t.split(".").forEach((n,a,o)=>{n==="__proto__"||n==="constructor"||(a===o.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((o,c)=>o!=null?o[c]:o,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},uTn=class extends L7i{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,pO.from)(t):(0,pO.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,pO.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,pO.from)([t]),this.process=i.pipe((0,pO.concatMap)(this.processQuestion.bind(this)),(0,pO.publish)()),this.process.connect(),this.process.pipe((0,pO.reduce)((n,a)=>(V4p.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,pO.defer)(()=>(0,pO.of)(t).pipe((0,pO.concatMap)(this.setDefaultType.bind(this)),(0,pO.concatMap)(this.filterIfRunnable.bind(this)),(0,pO.concatMap)(()=>u0o(t,"message",this.answers)),(0,pO.concatMap)(()=>u0o(t,"default",this.answers)),(0,pO.concatMap)(()=>u0o(t,"choices",this.answers)),(0,pO.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,pO.defer)(()=>(0,pO.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,pO.defer)(()=>(0,pO.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&V4p.get(this.answers,t.name)!==void 0)return pO.EMPTY;if(t.when===!1)return pO.EMPTY;if(typeof t.when!="function")return(0,pO.of)(t);let{answers:r}=this;return(0,pO.defer)(()=>(0,pO.from)((0,W4p.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,pO.filter)(i=>i!=null)))}};function x4p(e){let t=function(r,i){let n;try{n=new uTn(t.prompts,e)}catch(o){return Promise.reject(o)}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",Fga),this.registerPrompt("input",z7i),this.registerPrompt("number",Qga),this.registerPrompt("confirm",Uga),this.registerPrompt("rawlist",Lga),this.registerPrompt("expand",Vga),this.registerPrompt("checkbox",Wga),this.registerPrompt("password",xga),this.registerPrompt("editor",Zga)},t.restoreDefaultPrompts(),t}var TGs=x4p();function dgS(e,t){TGs.registerPrompt(e,t)}function pgS(){TGs.restoreDefaultPrompts()}var _gS={prompt:TGs,ui:{BottomBar:kga,Prompt:uTn},createPromptModule:x4p,registerPrompt:dgS,restoreDefaultPrompts:pgS,Separator:wH},s0o=_gS;var OTn=require("path"),P3p=require("fs"),j3p=require("readline"),JLp="posthog-node";function LAS(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"]}={}){return a=>{if(!(n==="*"||n.includes(a.level)))return a;a.tags||(a.tags={});let c=a.tags[M0o.POSTHOG_ID_TAG];if(c===void 0)return a;let f=e.options.host??"https://us.i.posthog.com",s=new URL(`/project/${e.apiKey}/person/${c}`,f).toString();a.tags["PostHog Person URL"]=s;let u=a.exception?.values||[],l=u.map(_=>({..._,stacktrace:_.stacktrace?{..._.stacktrace,type:"raw",frames:(_.stacktrace.frames||[]).map(h=>({...h,platform:"node:javascript"}))}:void 0})),p={$exception_message:u[0]?.value||a.message,$exception_type:u[0]?.type,$exception_personURL:s,$exception_level:a.level,$exception_list:l,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:u[0]?.value||a.message,$sentry_exception_type:u[0]?.type,$sentry_tags:a.tags};return t&&r&&(p.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),e.capture({event:"$exception",distinctId:c,properties:p}),a}}var M0o=class{constructor(t,r,i,n){this.name=JLp,this.name=JLp,this.setupOnce=function(a,o){let c=o()?.getClient()?.getDsn()?.projectId;a(LAS(t,{organization:r,projectId:c,prefix:i,severityAllowList:n}))}}};M0o.POSTHOG_ID_TAG="posthog_distinct_id";var P0o="0123456789abcdef",D0o=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+=P0o.charAt(this.bytes[r]>>>4),t+=P0o.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+=P0o.charAt(this.bytes[r]>>>4),t+=P0o.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}},v7s=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??VAS()}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 D0o.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,D0o.ofInner(t)}},VAS=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),$Lp,g7s=()=>WAS().toString(),WAS=()=>($Lp||($Lp=new v7s)).generate();function xAS(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t())},{_posthogErrorHandler:!0})}function GAS(e,t){global.process.on("uncaughtException",xAS(e,t))}function HAS(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var j0o,YLp,w0o;function KAS(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return w0o&&r.length===YLp||(YLp=r.length,w0o=r.reduce((i,n)=>{j0o||(j0o={});let a=j0o[n];if(a)i[a[0]]=a[1];else{let o=e(n);for(let c=o.length-1;c>=0;c--){let s=o[c]?.filename,u=t[n];if(s&&u){i[s]=u,j0o[n]=[s,u];break}}}return i},{})),w0o}function JAS(e){return typeof Event<"u"&&w3p(e,Event)}function $AS(e){return E3p(e,"Object")}function S7s(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return w3p(e,Error)}}function w3p(e,t){try{return e instanceof t}catch{return!1}}function YAS(e){return E3p(e,"ErrorEvent")}function E3p(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function XAS(e,t,r,i){let a=i&&i.mechanism||{handled:!0,type:"generic"},o=S3p(a,r,i);return{$exception_list:await Promise.all(o.map(async s=>{let u=await nmS(e,t,s);return u.value=u.value||"",u.type=u.type||"Error",u.mechanism=a,u}))}}function S3p(e,t,r){let i=ZAS(e,t,r);return i.cause?[i,...S3p(e,i.cause,r)]:[i]}function ZAS(e,t,r){if(S7s(t))return t;if(e.synthetic=!0,$AS(t)){let n=kAS(t);if(n)return n;let a=emS(t),o=r?.syntheticException||new Error(a);return o.message=a,o}let i=r?.syntheticException||new Error(t);return i.message=`${t}`,i}function kAS(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(S7s(r))return r}}function emS(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=rmS(e);if(YAS(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=tmS(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function tmS(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function rmS(e,t=40){let r=Object.keys(imS(e));r.sort();let i=r[0];if(!i)return"[object has no keys]";if(i.length>=t)return XLp(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:XLp(a,t)}return""}function XLp(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function imS(e){return S7s(e)?{message:e.message,name:e.name,stack:e.stack,...ZLp(e)}:JAS(e)?{type:e.type,target:kLp(e.target),currentTarget:kLp(e.currentTarget),...ZLp(e)}:e}function ZLp(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 kLp(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function nmS(e,t,r){let i={type:r.name||r.constructor.name,value:r.message},n=amS(e,r);for(let a of t)n=await a(n);return n.length&&(i.stacktrace={frames:n,type:"raw"}),i}function amS(e,t){return omS(e(t.stack||"",1),e)}function omS(e,t){let r=KAS(t);return e.forEach(i=>{i.filename&&(i.chunk_id=r[i.filename])}),e}var umS=2e3,bTn=class e{static async captureException(t,r,i,n,a){let o={...a};n||(o.$process_person_profile=!1);let c=await XAS(this.stackParser,this.frameModifiers,r,i);t.capture({event:"$exception",distinctId:n||g7s(),properties:{...c,...o}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(GAS(this.onException.bind(this),this.onFatalError.bind(this)),HAS(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(umS)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function smS(e=process.argv[1]?(0,OTn.dirname)(process.argv[1]):process.cwd(),t=OTn.sep==="\\"){let r=t?e3p(e):e;return i=>{if(!i)return;let n=t?e3p(i):i,{dir:a,base:o,ext:c}=OTn.posix.parse(n);(c===".js"||c===".mjs"||c===".cjs")&&(o=o.slice(0,c.length*-1));let f=decodeURIComponent(o);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${f}`;if(a.startsWith(r)){let u=a.slice(r.length+1).replace(/\//g,".");return u?`${u}:${f}`:f}return f}}function e3p(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var B0o=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)}}},S0o=new B0o(25),M3p=new B0o(20),M7s=7,cmS=1e3,lmS=1e4;async function fmS(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||hmS(o)||ymS(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(M3p.get(n))continue;let a=t[n];if(!a)continue;a.sort((f,s)=>f-s);let o=vmS(a);if(o.every(f=>bmS(n,f)))continue;let c=gmS(S0o,n,{});i.push(dmS(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&pmS(e,S0o),S0o.reduce(),e}function dmS(e,t,r){return new Promise(i=>{let n=(0,P3p.createReadStream)(e),a=(0,j3p.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,f=0,s=t[f];if(s===void 0){o();return}let u=s[0],l=s[1];function p(){M3p.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=OmS(_,0),c>=l)){if(f===t.length-1){a.close(),a.removeAllListeners();return}f++;let h=t[f];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],l=h[1]}})})}function pmS(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;_mS(r.lineno,r,i)}}function _mS(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=D3p(e);n<e;n++){let a=r[n];if(a===void 0){t3p(t);return}t.pre_context.push(a)}if(r[e]===void 0){t3p(t);return}t.context_line=r[e];let i=B3p(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 t3p(e){delete e.pre_context,delete e.context_line,delete e.post_context}function hmS(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function ymS(e){return e.lineno!==void 0&&e.lineno>lmS||e.colno!==void 0&&e.colno>cmS}function bmS(e,t){let r=S0o.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 vmS(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=r3p(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+M7s:(n.push(i),i=r3p(a)),t++}return n}function r3p(e){return[D3p(e),B3p(e)]}function D3p(e){return Math.max(1,e-M7s)}function B3p(e){return e+M7s}function gmS(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function OmS(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 AmS="4.18.0",BH;(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"})(BH||(BH={}));var i3p;(function(e){e.Left="left",e.Right="right",e.Center="center"})(i3p||(i3p={}));var n3p;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(n3p||(n3p={}));var a3p;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(a3p||(a3p={}));var o3p;(function(e){e.Html="html",e.Text="text"})(o3p||(o3p={}));var u3p;(function(e){e.Number="number",e.Emoji="emoji"})(u3p||(u3p={}));var s3p;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(s3p||(s3p={}));var c3p;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(c3p||(c3p={}));var l3p;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(l3p||(l3p={}));var f3p;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(f3p||(f3p={}));var mmS=e=>{if("flags"in e){let t=jmS(e.flags),r=wmS(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,I3p(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,PmS(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function PmS(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 jmS=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,D7s(r)]).filter(([,t])=>t!==void 0)),wmS=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?I3p(i):void 0]}))},D7s=e=>e===void 0?void 0:e.variant??e.enabled,I3p=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},EmS=1,SmS=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"]),MmS="utf8";function DmS(e,t){if(!e||typeof e!="string"||BmS(e))throw new Error(t)}function BmS(e){return e.trim().length===0}function ImS(e){return e?.replace(/\/+$/,"")}async function CmS(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 d3p(){return new Date().getTime()}function y7s(){return new Date().toISOString()}function I0o(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function qmS(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function TmS(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 RmS(e,t=0,r){let i=TmS(e);return r?.has(i)?!1:parseInt(i,16)/4294967295<t}function p3p(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var cOa=String.fromCharCode,_3p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",E0o={};function zmS(e,t){if(!E0o[e]){E0o[e]={};for(let r=0;r<e.length;r++)E0o[e][e.charAt(r)]=r}return E0o[e][t]}var hTn={compressToBase64:function(e){if(e==null)return"";let t=hTn._compress(e,6,function(r){return _3p.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:hTn._decompress(e.length,32,function(t){return zmS(_3p,e.charAt(t))})},compress:function(e){return hTn._compress(e,16,function(t){return cOa(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],o,c,f="",s="",u="",l=2,p=3,_=2,h=0,y=0,b;for(b=0;b<e.length;b+=1)if(f=e.charAt(b),Object.prototype.hasOwnProperty.call(i,f)||(i[f]=p++,n[f]=!0),s=u+f,Object.prototype.hasOwnProperty.call(i,s))u=s;else{if(Object.prototype.hasOwnProperty.call(n,u)){if(u.charCodeAt(0)<256){for(o=0;o<_;o++)h=h<<1,y==t-1?(y=0,a.push(r(h)),h=0):y++;for(c=u.charCodeAt(0),o=0;o<8;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1}else{for(c=1,o=0;o<_;o++)h=h<<1|c,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=0;for(c=u.charCodeAt(0),o=0;o<16;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1}l--,l==0&&(l=Math.pow(2,_),_++),delete n[u]}else for(c=i[u],o=0;o<_;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1;l--,l==0&&(l=Math.pow(2,_),_++),i[s]=p++,u=String(f)}if(u!==""){if(Object.prototype.hasOwnProperty.call(n,u)){if(u.charCodeAt(0)<256){for(o=0;o<_;o++)h=h<<1,y==t-1?(y=0,a.push(r(h)),h=0):y++;for(c=u.charCodeAt(0),o=0;o<8;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1}else{for(c=1,o=0;o<_;o++)h=h<<1|c,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=0;for(c=u.charCodeAt(0),o=0;o<16;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1}l--,l==0&&(l=Math.pow(2,_),_++),delete n[u]}else for(c=i[u],o=0;o<_;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1;l--,l==0&&(l=Math.pow(2,_),_++)}for(c=2,o=0;o<_;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1;for(;;)if(h=h<<1,y==t-1){a.push(r(h));break}else y++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:hTn._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},o=4,c=4,f=3,s="",u,l,p,_,h,y,b;for(u=0;u<3;u+=1)i[u]=u;for(p=0,h=Math.pow(2,2),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;switch(p){case 0:for(p=0,h=Math.pow(2,8),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;b=cOa(p);break;case 1:for(p=0,h=Math.pow(2,16),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;b=cOa(p);break;case 2:return""}for(i[3]=b,l=b,n.push(b);;){if(a.index>e)return"";for(p=0,h=Math.pow(2,f),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;switch(b=p){case 0:for(p=0,h=Math.pow(2,8),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;i[c++]=cOa(p),b=c-1,o--;break;case 1:for(p=0,h=Math.pow(2,16),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;i[c++]=cOa(p),b=c-1,o--;break;case 2:return n.join("")}if(o==0&&(o=Math.pow(2,f),f++),i[b])s=i[b];else if(b===c)s=l+l.charAt(0);else return null;n.push(s),i[c++]=l+s.charAt(0),o--,l=s,o==0&&(o=Math.pow(2,f),f++)}}},O7s=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)}},vTn=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()}},lOa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function h3p(e){if(e instanceof vTn){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 b7s(e){return typeof e=="object"&&(e instanceof vTn||e instanceof lOa)}function y3p(e){return typeof e=="object"&&e instanceof vTn&&e.status===413}var A7s;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(A7s||(A7s={}));var m7s=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new O7s,this._isInitialized=!1,DmS(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=ImS(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:b7s},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(BH.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(BH.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(BH.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=g7s();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,o){this.wrap(()=>{let c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...o||{}}});this.enqueue("capture",c,n)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(n=>n.json()).catch(n=>{this.logMsgIfDebug(()=>console.error("Remote config could not be loaded",n)),this._events.emit("error",n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let c=RmS(this.apiKey,EmS,SmS)?`${this.host}/flags/?v=2`:`${this.host}/decide/?v=4`,f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.logMsgIfDebug(()=>console.log("PostHog Debug","Decide URL",c)),this.fetchWithRetry(c,f,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(s=>s.json()).then(s=>mmS(s)).catch(s=>{this._events.emit("error",s)})}async getFeatureFlagStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,i,n,a,o);if(c===void 0)return{response:void 0,requestId:void 0};let f=D7s(c.response);return f===void 0&&(f=!1),{response:f,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,i,n,a,o,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,i,n,a,o,[t]);if(!c)return;let f=c[t];return f===void 0?null:f}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)).payloads}async getFeatureFlagsStateless(t,r={},i={},n={},a,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,o);return c?{flags:c.featureFlags,payloads:c.featureFlagPayloads,requestId:c.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c={};(a??this.disableGeoip)&&(c.geoip_disable=!0),o&&(c.flag_keys_to_evaluate=o);let f=await this.getDecide(t,r,i,n,c);if(f!==void 0)return f.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),f.quotaLimited?.includes(A7s.FeatureFlags)?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:f?.requestId}):f}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this.logMsgIfDebug(()=>console.log("PostHog Debug","Loading surveys is disabled.")),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},n=(await this.fetchWithRetry(t,r).then(a=>{if(a.status!==200||!a.json){let o=`Surveys API could not be loaded: ${a.status}`,c=new Error(o);this.logMsgIfDebug(()=>console.error(c)),this._events.emit("error",new Error(o));return}return a.json()}).catch(a=>{this.logMsgIfDebug(()=>console.error("Surveys API could not be loaded",a)),this._events.emit("error",a)}))?.surveys;return n&&this.logMsgIfDebug(()=>console.log("PostHog Debug","Surveys fetched from API: ",JSON.stringify(n))),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(BH.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(BH.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(BH.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(BH.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(BH.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=I0o(()=>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:y7s()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),o=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${d3p()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,c=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(hTn.compressToBase64(a))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:a};try{await this.fetchWithRetry(o,c)}catch(f){this._events.emit("error",f)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:y7s(),uuid:i?.uuid?i.uuid:g7s()};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 h3p(t)})}async flush(){let t=p3p([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),p3p([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(BH.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(p=>p.message),o=()=>{let _=(this.getPersistedProperty(BH.Queue)||[]).slice(n.length);this.setPersistedProperty(BH.Queue,_),t=_},c={api_key:this.apiKey,batch:a,sent_at:y7s()};this.historicalMigration&&(c.historical_migration=!0);let f=JSON.stringify(c),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${d3p()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,u=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(hTn.compressToBase64(f))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:f},l={retryCheck:p=>y3p(p)?!1:b7s(p)};try{await this.fetchWithRetry(s,u,l)}catch(p){if(y3p(p)&&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 p instanceof lOa||o(),this._events.emit("error",p),p}o(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){var a;(a=AbortSignal).timeout??(a.timeout=function(s){let u=new AbortController;return setTimeout(()=>u.abort(),s),u.signal});let o=r.body?r.body:"",c=-1;try{c=Buffer.byteLength(o,MmS)}catch{c=new TextEncoder().encode(o).length}return await CmS(async()=>{let f=null;try{f=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(u){throw new lOa(u)}if(!(r.mode==="no-cors")&&(f.status<200||f.status>=400))throw new vTn(f,c);return f},{...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(BH.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!b7s(n))throw n;await h3p(n)}};return Promise.race([new Promise((n,a)=>{I0o(()=>{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}},P7s=qmS();if(!P7s){let e=KLp();P7s=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 C3p=P7s,C0o=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()}},q3p=new C0o(async()=>{try{return await import("crypto")}catch{return}});async function NmS(){return await q3p.getValue()}var FmS=new C0o(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await q3p.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function QmS(){return await FmS.getValue()}async function UmS(e){let t=await NmS();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await QmS();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 LmS=60*1e3,VmS=1152921504606847e3,WmS=["is_not"],yTn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},v1=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},j7s=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:o,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||C3p,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;for(let f of this.featureFlags)if(t===f.key){c=f;break}if(c!==void 0)try{o=await this.computeFlagLocally(c,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(f){f instanceof v1?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${f}`)):f instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${f}`))}return o}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let 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={},o={},c=this.featureFlags.length==0;return await Promise.all(this.featureFlags.map(async f=>{try{let s=await this.computeFlagLocally(f,t,r,i,n);a[f.key]=s;let u=await this.computeFeatureFlagPayloadLocally(f.key,s);u&&(o[f.key]=u)}catch(s){s instanceof v1||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${s}`)),c=!0}})),{response:a,payloads:o,fallbackToDecide:c}}async computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new v1("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let f=this.groupTypeMapping[String(c)];if(!f)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new v1("Flag has unknown group type index");if(!(f 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[f];return await this.matchFeatureFlagProperties(t,i[f],s)}else return await this.matchFeatureFlagProperties(t,r,n)}async matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],o=!1,c,f=[...a].sort((s,u)=>{let l=!!s.variant,p=!!u.variant;return l&&p?0:l?-1:p?1:0});for(let s of f)try{if(await this.isConditionMatch(t,r,s,i)){let u=s.variant,l=n.multivariate?.variants||[];u&&l.some(p=>p.key===u)?c=u:c=await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof v1)o=!0;else throw u}if(c!==void 0)return c;if(o)throw new v1("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,o=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((i.properties||[]).length>0){for(let c of i.properties){let f=c.type,s=!1;if(f==="cohort"?s=R3p(c,n,this.cohorts,this.debugMode):s=T3p(c,n,o),!s)return!1}if(a==null)return!0}return!(a!=null&&await b3p(t.key,r)>a/100)}async getMatchingVariant(t,r){let i=await b3p(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(LmS,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 yTn(`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 yTn(`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 yTn(`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 yTn&&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=I0o(()=>{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=I0o(()=>{a.abort()},this.timeout),i.signal=a.signal}try{return this.fetch(r,i)}finally{clearTimeout(n)}}};async function b3p(e,t,r=""){let i=await UmS(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/VmS}function T3p(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 v1("Operator is_not_set is not supported")}else throw new v1(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!WmS.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(l=>String(l).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function f(s,u,l){if(l==="gt")return s>u;if(l==="gte")return s>=u;if(l==="lt")return s<u;if(l==="lte")return s<=u;throw new Error(`Invalid operator: ${l}`)}switch(a){case"exact":return c(n,o);case"is_not":return!c(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return v3p(String(n))&&String(o).match(String(n))!==null;case"not_regex":return v3p(String(n))&&String(o).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&&o!=null?typeof o=="string"?f(o,String(n),a):f(o,s,a):f(String(o),String(n),a)}case"is_date_after":case"is_date_before":{let s=xmS(String(n));if(s==null&&(s=g3p(n)),s==null)throw new v1(`Invalid date: ${n}`);let u=g3p(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new v1(`Unknown operator: ${a}`)}}function R3p(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new v1("can't match cohort without a given cohort property value");let a=r[n];return z3p(a,t,r,i)}function z3p(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let f=z3p(c,t,r,i);if(n==="AND"){if(!f)return!1}else if(f)return!0}catch(f){if(f instanceof v1)i&&console.debug(`Failed to compute property ${c} locally: ${f}`),o=!0;else throw f}if(o)throw new v1("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let c of a)try{let f;c.type==="cohort"?f=R3p(c,t,r,i):f=T3p(c,t);let s=c.negation||!1;if(n==="AND"){if(!f&&!s||f&&s)return!1}else if(f&&!s||!f&&s)return!0}catch(f){if(f instanceof v1)i&&console.debug(`Failed to compute property ${c} locally: ${f}`),o=!0;else throw f}if(o)throw new v1("can't match cohort without a given cohort property value");return n==="AND"}}function v3p(e){try{return new RegExp(e),!0}catch{return!1}}function g3p(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 v1(`${e} is in an invalid date format`)}else throw new v1(`The date provided ${e} must be a string, number, or date object`)}function xmS(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 w7s=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},GmS=100,O3p=30*1e3,HmS=50*1e3,E7s=class extends m7s{constructor(t,r={}){if(super(t,r),this._memoryStorage=new w7s,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,GmS):O3p,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 j7s({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 bTn(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||HmS}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):C3p(t,r)}getLibraryVersion(){return AmS}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:o,timestamp:c,disableGeoip:f,uuid:s}=t,u=_=>{super.captureStateless(r,i,_,{timestamp:c,disableGeoip:f,uuid:s})},l=async(_,h,y)=>(await super.getFeatureFlagsStateless(_,h,void 0,void 0,y)).flags,p=Promise.resolve().then(async()=>{if(o)return await l(r,a,f);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let _={};for(let[h,y]of Object.entries(a||{}))_[h]=String(y);return await this.getAllFlags(r,{groups:_,disableGeoip:f,onlyEvaluateLocally:!0})}return{}}).then(_=>{let h={};if(_)for(let[b,v]of Object.entries(_))h[`$feature/${b}`]=v;let y=Object.keys(_||{}).filter(b=>_?.[b]!==!1).sort();return y.length>0&&(h.$active_feature_flags=y),h}).catch(()=>({})).then(_=>{u({..._,...n,$groups:a})});this.addPendingPromise(p)}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:o,timestamp:c,disableGeoip:f,uuid:s}=t,u=_=>super.captureStatelessImmediate(r,i,_,{timestamp:c,disableGeoip:f,uuid:s}),l=async(_,h,y)=>(await super.getFeatureFlagsStateless(_,h,void 0,void 0,y)).flags;await Promise.resolve().then(async()=>{if(o)return await l(r,a,f);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let _={};for(let[h,y]of Object.entries(a||{}))_[h]=String(y);return await this.getAllFlags(r,{groups:_,disableGeoip:f,onlyEvaluateLocally:!0})}return{}}).then(_=>{let h={};if(_)for(let[b,v]of Object.entries(_))h[`$feature/${b}`]=v;let y=Object.keys(_||{}).filter(b=>_?.[b]!==!1).sort();return y.length>0&&(h.$active_feature_flags=y),h}).catch(()=>({})).then(_=>{u({..._,...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=O3p){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:o,sendFeatureFlagEvents:c,personProperties:f,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,f,s);f=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,f,s),p=l!==void 0,_,h;if(!p&&!o){let b=await super.getFeatureFlagDetailStateless(t,r,n,f,s,a);if(b===void 0)return;h=b.response,l=D7s(h),_=b?.requestId}let y=`${t}_${l}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(y))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(y):this.distinctIdHasSentFlagCalls[r]=[y],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,$feature_flag_id:h?.metadata?.id,$feature_flag_version:h?.metadata?.version,$feature_flag_reason:h?.reason?.description??h?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:l,$feature_flag_request_id:_},groups:n,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,sendFeatureFlagEvents:f,personProperties:s,groupProperties:u}=n||{},l=this.addLocalPersonAndGroupProperties(r,a,s,u);s=l.allPersonProperties,u=l.allGroupProperties;let p;return this.featureFlagsPoller!==void 0&&(i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0,sendFeatureFlagEvents:!1})),i&&(p=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i))),c==null&&(c=!1),f==null&&(f=!0),c==null&&(c=!1),!(p!==void 0)&&!c&&(p=await super.getFeatureFlagPayloadStateless(t,r,a,s,u,o)),p}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:o,groupProperties:c}=r||{},f=this.addLocalPersonAndGroupProperties(t,i,o,c);o=f.allPersonProperties,c=f.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,o,c),u={},l={},p=!0;if(s&&(u=s.response,l=s.payloads,p=s.fallbackToDecide),p&&!a){let _=await super.getFeatureFlagsAndPayloadsStateless(t,i,o,c,n);u={...u,..._.flags||{}},l={...l,..._.payloads||{}}}return{featureFlags:u,featureFlagPayloads:l}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(),super._shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,i){let n=new Error("PostHog syntheticException");bTn.captureException(this,t,{syntheticException:n},r,i)}},A3p=/\(error: (.*)\)/,N3p=50,F3p="?";function KmS(e){let t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return i=>{let n=i.match(r);if(n){let a,o,c,f,s;if(n[1]){c=n[1];let p=c.lastIndexOf(".");if(c[p-1]==="."&&p--,p>0){a=c.slice(0,p),o=c.slice(p+1);let _=a.indexOf(".Module");_>0&&(c=c.slice(_+1),a=a.slice(0,_))}f=void 0}o&&(f=a,s=o),o==="<anonymous>"&&(s=void 0,c=void 0),c===void 0&&(s=s||F3p,c=f?`${f}.${s}`:s);let u=n[2]?.startsWith("file://")?n[2].slice(7):n[2],l=n[5]==="native";return u?.match(/\/[A-Z]:/)&&(u=u.slice(1)),!u&&n[5]&&!l&&(u=n[5]),{filename:u?decodeURI(u):void 0,module:e?e(u):void 0,function:c,lineno:m3p(n[3]),colno:m3p(n[4]),in_app:JmS(u||"",l),platform:"node:javascript"}}if(i.match(t))return{filename:i,platform:"node:javascript"}}}function JmS(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 m3p(e){return parseInt(e||"",10)||void 0}function $mS(e){return[90,KmS(e)]}function YmS(e){let r=[$mS(e)].sort((i,n)=>i[0]-n[0]).map(i=>i[1]);return(i,n=0)=>{let a=[],o=i.split(`
1150
- `);for(let c=n;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let s=A3p.test(f)?f.replace(A3p,"$1"):f;if(!s.match(/\S*Error: /)){for(let u of r){let l=u(s);if(l){a.push(l);break}}if(a.length>=N3p)break}}return XmS(a)}}function XmS(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,N3p).map(r=>({...r,filename:r.filename||ZmS(t).filename,function:r.function||F3p}))}function ZmS(e){return e[e.length-1]||{}}bTn.stackParser=YmS(smS());bTn.frameModifiers=[fmS];var gTn=class extends E7s{getLibraryId(){return"posthog-node"}};var q0o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new gTn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.26.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var fOa=class{async sendEvent(){}async identify(){}async flush(){}};var ATn=require("fs/promises"),V3p=require("os"),W3p=require("path");var Q3p=ce(require("crypto")),R0o=new Uint8Array(256),T0o=R0o.length;function B7s(){return T0o>R0o.length-16&&(Q3p.default.randomFillSync(R0o),T0o=0),R0o.slice(T0o,T0o+=16)}var zQ=[];for(let e=0;e<256;++e)zQ.push((e+256).toString(16).slice(1));function U3p(e,t=0){return zQ[e[t+0]]+zQ[e[t+1]]+zQ[e[t+2]]+zQ[e[t+3]]+"-"+zQ[e[t+4]]+zQ[e[t+5]]+"-"+zQ[e[t+6]]+zQ[e[t+7]]+"-"+zQ[e[t+8]]+zQ[e[t+9]]+"-"+zQ[e[t+10]]+zQ[e[t+11]]+zQ[e[t+12]]+zQ[e[t+13]]+zQ[e[t+14]]+zQ[e[t+15]]}var L3p=ce(require("crypto")),I7s={randomUUID:L3p.default.randomUUID};function kmS(e,t,r){if(I7s.randomUUID&&!t&&!e)return I7s.randomUUID();e=e||{};let i=e.random||(e.rng||B7s)();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 U3p(i)}var the=kmS;var e0S="id",t0S=".fern",dOa=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new gTn(r),this.userId=t==null?void 0:Z8s(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"3.26.1",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await SQ({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Bt(Br.of((0,V3p.homedir)()),Ye.of(t0S),Ye.of(e0S));await ji(t)||(await(0,ATn.mkdir)((0,W3p.dirname)(t),{recursive:!0}),await(0,ATn.writeFile)(t,the())),this.persistedDistinctId=(await(0,ATn.readFile)(t)).toString()}return this.persistedDistinctId}};var C7s;async function mTn(){return C7s==null&&(C7s=await r0S()),C7s}async function r0S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new fOa;let r=await Zyo();return r!=null?new dOa({token:r,posthogApiKey:e}):await wqn()!=null?new q0o({posthogApiKey:e}):new dOa({token:void 0,posthogApiKey:e})}catch{return new fOa}}function pOa(e,t){return function(){return e.apply(t,arguments)}}var{toString:i0S}=Object.prototype,{getPrototypeOf:T7s}=Object,{iterator:N0o,toStringTag:G3p}=Symbol,F0o=(e=>t=>{let r=i0S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),FNt=e=>(e=e.toLowerCase(),t=>F0o(t)===e),Q0o=e=>t=>typeof t===e,{isArray:jTn}=Array,PTn=Q0o("undefined");function _Oa(e){return e!==null&&!PTn(e)&&e.constructor!==null&&!PTn(e.constructor)&&IH(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var H3p=FNt("ArrayBuffer");function n0S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&H3p(e.buffer),t}var a0S=Q0o("string"),IH=Q0o("function"),K3p=Q0o("number"),hOa=e=>e!==null&&typeof e=="object",o0S=e=>e===!0||e===!1,z0o=e=>{if(F0o(e)!=="object")return!1;let t=T7s(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(G3p in e)&&!(N0o in e)},u0S=e=>{if(!hOa(e)||_Oa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},s0S=FNt("Date"),c0S=FNt("File"),l0S=FNt("Blob"),f0S=FNt("FileList"),d0S=e=>hOa(e)&&IH(e.pipe),p0S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||IH(e.append)&&((t=F0o(e))==="formdata"||t==="object"&&IH(e.toString)&&e.toString()==="[object FormData]"))},_0S=FNt("URLSearchParams"),[h0S,y0S,b0S,v0S]=["ReadableStream","Request","Response","Headers"].map(FNt),g0S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function yOa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),jTn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(_Oa(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(i=0;i<o;i++)c=a[i],t.call(null,e[c],c,e)}}function J3p(e,t){if(_Oa(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var K7i=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,$3p=e=>!PTn(e)&&e!==K7i;function q7s(){let{caseless:e,skipUndefined:t}=$3p(this)&&this||{},r={},i=(n,a)=>{let o=e&&J3p(r,a)||a;z0o(r[o])&&z0o(n)?r[o]=q7s(r[o],n):z0o(n)?r[o]=q7s({},n):jTn(n)?r[o]=n.slice():(!t||!PTn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&yOa(arguments[n],i);return r}var O0S=(e,t,r,{allOwnKeys:i}={})=>(yOa(t,(n,a)=>{r&&IH(n)?e[a]=pOa(n,r):e[a]=n},{allOwnKeys:i}),e),A0S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),m0S=(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)},P0S=(e,t,r,i)=>{let n,a,o,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)o=n[a],(!i||i(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&T7s(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},j0S=(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},w0S=e=>{if(!e)return null;if(jTn(e))return e;let t=e.length;if(!K3p(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},E0S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&T7s(Uint8Array)),S0S=(e,t)=>{let i=(e&&e[N0o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},M0S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},D0S=FNt("HTMLFormElement"),B0S=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),x3p=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),I0S=FNt("RegExp"),Y3p=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};yOa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},C0S=e=>{Y3p(e,(t,r)=>{if(IH(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(IH(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+"'")})}})},q0S=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return jTn(e)?i(e):i(String(e).split(t)),r},T0S=()=>{},R0S=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function z0S(e){return!!(e&&IH(e.append)&&e[G3p]==="FormData"&&e[N0o])}var N0S=e=>{let t=new Array(10),r=(i,n)=>{if(hOa(i)){if(t.indexOf(i)>=0)return;if(_Oa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=jTn(i)?[]:{};return yOa(i,(o,c)=>{let f=r(o,n+1);!PTn(f)&&(a[c]=f)}),t[n]=void 0,a}}return i};return r(e,0)},F0S=FNt("AsyncFunction"),Q0S=e=>e&&(hOa(e)||IH(e))&&IH(e.then)&&IH(e.catch),X3p=((e,t)=>e?setImmediate:t?((r,i)=>(K7i.addEventListener("message",({source:n,data:a})=>{n===K7i&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),K7i.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",IH(K7i.postMessage)),U0S=typeof queueMicrotask<"u"?queueMicrotask.bind(K7i):typeof process<"u"&&process.nextTick||X3p,L0S=e=>e!=null&&IH(e[N0o]),er={isArray:jTn,isArrayBuffer:H3p,isBuffer:_Oa,isFormData:p0S,isArrayBufferView:n0S,isString:a0S,isNumber:K3p,isBoolean:o0S,isObject:hOa,isPlainObject:z0o,isEmptyObject:u0S,isReadableStream:h0S,isRequest:y0S,isResponse:b0S,isHeaders:v0S,isUndefined:PTn,isDate:s0S,isFile:c0S,isBlob:l0S,isRegExp:I0S,isFunction:IH,isStream:d0S,isURLSearchParams:_0S,isTypedArray:E0S,isFileList:f0S,forEach:yOa,merge:q7s,extend:O0S,trim:g0S,stripBOM:A0S,inherits:m0S,toFlatObject:P0S,kindOf:F0o,kindOfTest:FNt,endsWith:j0S,toArray:w0S,forEachEntry:S0S,matchAll:M0S,isHTMLForm:D0S,hasOwnProperty:x3p,hasOwnProp:x3p,reduceDescriptors:Y3p,freezeMethods:C0S,toObjectSet:q0S,toCamelCase:B0S,noop:T0S,toFiniteNumber:R0S,findKey:J3p,global:K7i,isContextDefined:$3p,isSpecCompliantForm:z0S,toJSONObject:N0S,isAsyncFn:F0S,isThenable:Q0S,setImmediate:X3p,asap:U0S,isIterable:L0S};function wTn(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)}er.inherits(wTn,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:er.toJSONObject(this.config),code:this.code,status:this.status}}});var Z3p=wTn.prototype,k3p={};["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=>{k3p[e]={value:e}});Object.defineProperties(wTn,k3p);Object.defineProperty(Z3p,"isAxiosError",{value:!0});wTn.from=(e,t,r,i,n,a)=>{let o=Object.create(Z3p);er.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",f=t==null&&e?e.code:t;return wTn.call(o,c,f,r,i,n),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var ha=wTn;var e8p=ce(IGi(),1),U0o=e8p.default;function R7s(e){return er.isPlainObject(e)||er.isArray(e)}function r8p(e){return er.endsWith(e,"[]")?e.slice(0,-2):e}function t8p(e,t,r){return e?e.concat(t).map(function(n,a){return n=r8p(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function V0S(e){return er.isArray(e)&&!e.some(R7s)}var W0S=er.toFlatObject(er,{},null,function(t){return/^is[A-Z]/.test(t)});function x0S(e,t,r){if(!er.isObject(e))throw new TypeError("target must be an object");t=t||new(U0o||FormData),r=er.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!er.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&er.isSpecCompliantForm(t);if(!er.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(er.isDate(h))return h.toISOString();if(er.isBoolean(h))return h.toString();if(!f&&er.isBlob(h))throw new ha("Blob is not supported. Use a Buffer instead.");return er.isArrayBuffer(h)||er.isTypedArray(h)?f&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,b){let v=h;if(h&&!b&&typeof h=="object"){if(er.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(er.isArray(h)&&V0S(h)||(er.isFileList(h)||er.endsWith(y,"[]"))&&(v=er.toArray(h)))return y=r8p(y),v.forEach(function(A,g){!(er.isUndefined(A)||A===null)&&t.append(o===!0?t8p([y],g,a):o===null?y:y+"[]",s(A))}),!1}return R7s(h)?!0:(t.append(t8p(b,y,a),s(h)),!1)}let l=[],p=Object.assign(W0S,{defaultVisitor:u,convertValue:s,isVisitable:R7s});function _(h,y){if(!er.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),er.forEach(h,function(v,O){(!(er.isUndefined(v)||v===null)&&n.call(t,v,er.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),l.pop()}}if(!er.isObject(e))throw new TypeError("data must be an object");return _(e),t}var FBi=x0S;function i8p(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function n8p(e,t){this._pairs=[],e&&FBi(e,this,t)}var a8p=n8p.prototype;a8p.append=function(t,r){this._pairs.push([t,r])};a8p.toString=function(t){let r=t?function(i){return t.call(this,i,i8p)}:i8p;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var o8p=n8p;function G0S(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function J7i(e,t,r){if(!t)return e;let i=r&&r.encode||G0S;er.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=er.isURLSearchParams(t)?t.toString():new o8p(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var z7s=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){er.forEach(this.handlers,function(i){i!==null&&t(i)})}},N7s=z7s;var ETn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var l8p=ce(require("crypto"),1);var u8p=ce(require("url"),1),s8p=u8p.default.URLSearchParams;var F7s="abcdefghijklmnopqrstuvwxyz",c8p="0123456789",f8p={DIGIT:c8p,ALPHA:F7s,ALPHA_DIGIT:F7s+F7s.toUpperCase()+c8p},H0S=(e=16,t=f8p.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);l8p.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},d8p={isNode:!0,classes:{URLSearchParams:s8p,FormData:U0o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:f8p,generateString:H0S,protocols:["http","https","file","data"]};var L7s={};Yt(L7s,{hasBrowserEnv:()=>U7s,hasStandardBrowserEnv:()=>K0S,hasStandardBrowserWebWorkerEnv:()=>J0S,navigator:()=>Q7s,origin:()=>$0S});var U7s=typeof window<"u"&&typeof document<"u",Q7s=typeof navigator=="object"&&navigator||void 0,K0S=U7s&&(!Q7s||["ReactNative","NativeScript","NS"].indexOf(Q7s.product)<0),J0S=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",$0S=U7s&&window.location.href||"http://localhost";var OA={...L7s,...d8p};function V7s(e,t){return FBi(e,new OA.classes.URLSearchParams,{visitor:function(r,i,n,a){return OA.isNode&&er.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function Y0S(e){return er.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function X0S(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 Z0S(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),f=a>=r.length;return o=!o&&er.isArray(n)?n.length:o,f?(er.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!er.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&er.isArray(n[o])&&(n[o]=X0S(n[o])),!c)}if(er.isFormData(e)&&er.isFunction(e.entries)){let r={};return er.forEachEntry(e,(i,n)=>{t(Y0S(i),n,r,0)}),r}return null}var L0o=Z0S;function k0S(e,t,r){if(er.isString(e))try{return(t||JSON.parse)(e),er.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var W7s={transitional:ETn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=er.isObject(t);if(a&&er.isHTMLForm(t)&&(t=new FormData(t)),er.isFormData(t))return n?JSON.stringify(L0o(t)):t;if(er.isArrayBuffer(t)||er.isBuffer(t)||er.isStream(t)||er.isFile(t)||er.isBlob(t)||er.isReadableStream(t))return t;if(er.isArrayBufferView(t))return t.buffer;if(er.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return V7s(t,this.formSerializer).toString();if((c=er.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return FBi(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),k0S(t)):t}],transformResponse:[function(t){let r=this.transitional||W7s.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(er.isResponse(t)||er.isReadableStream(t))return t;if(t&&er.isString(t)&&(i&&!this.responseType||n)){let o=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?ha.from(c,ha.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:OA.classes.FormData,Blob:OA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};er.forEach(["delete","get","head","post","put","patch"],e=>{W7s.headers[e]={}});var STn=W7s;var ePS=er.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"]),p8p=e=>{let t={},r,i,n;return e&&e.split(`
1150
+ `);for(let c=n;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let s=A3p.test(f)?f.replace(A3p,"$1"):f;if(!s.match(/\S*Error: /)){for(let u of r){let l=u(s);if(l){a.push(l);break}}if(a.length>=N3p)break}}return XmS(a)}}function XmS(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,N3p).map(r=>({...r,filename:r.filename||ZmS(t).filename,function:r.function||F3p}))}function ZmS(e){return e[e.length-1]||{}}bTn.stackParser=YmS(smS());bTn.frameModifiers=[fmS];var gTn=class extends E7s{getLibraryId(){return"posthog-node"}};var q0o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new gTn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.26.2",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var fOa=class{async sendEvent(){}async identify(){}async flush(){}};var ATn=require("fs/promises"),V3p=require("os"),W3p=require("path");var Q3p=ce(require("crypto")),R0o=new Uint8Array(256),T0o=R0o.length;function B7s(){return T0o>R0o.length-16&&(Q3p.default.randomFillSync(R0o),T0o=0),R0o.slice(T0o,T0o+=16)}var zQ=[];for(let e=0;e<256;++e)zQ.push((e+256).toString(16).slice(1));function U3p(e,t=0){return zQ[e[t+0]]+zQ[e[t+1]]+zQ[e[t+2]]+zQ[e[t+3]]+"-"+zQ[e[t+4]]+zQ[e[t+5]]+"-"+zQ[e[t+6]]+zQ[e[t+7]]+"-"+zQ[e[t+8]]+zQ[e[t+9]]+"-"+zQ[e[t+10]]+zQ[e[t+11]]+zQ[e[t+12]]+zQ[e[t+13]]+zQ[e[t+14]]+zQ[e[t+15]]}var L3p=ce(require("crypto")),I7s={randomUUID:L3p.default.randomUUID};function kmS(e,t,r){if(I7s.randomUUID&&!t&&!e)return I7s.randomUUID();e=e||{};let i=e.random||(e.rng||B7s)();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 U3p(i)}var the=kmS;var e0S="id",t0S=".fern",dOa=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new gTn(r),this.userId=t==null?void 0:Z8s(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"3.26.2",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await SQ({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Bt(Br.of((0,V3p.homedir)()),Ye.of(t0S),Ye.of(e0S));await ji(t)||(await(0,ATn.mkdir)((0,W3p.dirname)(t),{recursive:!0}),await(0,ATn.writeFile)(t,the())),this.persistedDistinctId=(await(0,ATn.readFile)(t)).toString()}return this.persistedDistinctId}};var C7s;async function mTn(){return C7s==null&&(C7s=await r0S()),C7s}async function r0S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new fOa;let r=await Zyo();return r!=null?new dOa({token:r,posthogApiKey:e}):await wqn()!=null?new q0o({posthogApiKey:e}):new dOa({token:void 0,posthogApiKey:e})}catch{return new fOa}}function pOa(e,t){return function(){return e.apply(t,arguments)}}var{toString:i0S}=Object.prototype,{getPrototypeOf:T7s}=Object,{iterator:N0o,toStringTag:G3p}=Symbol,F0o=(e=>t=>{let r=i0S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),FNt=e=>(e=e.toLowerCase(),t=>F0o(t)===e),Q0o=e=>t=>typeof t===e,{isArray:jTn}=Array,PTn=Q0o("undefined");function _Oa(e){return e!==null&&!PTn(e)&&e.constructor!==null&&!PTn(e.constructor)&&IH(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var H3p=FNt("ArrayBuffer");function n0S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&H3p(e.buffer),t}var a0S=Q0o("string"),IH=Q0o("function"),K3p=Q0o("number"),hOa=e=>e!==null&&typeof e=="object",o0S=e=>e===!0||e===!1,z0o=e=>{if(F0o(e)!=="object")return!1;let t=T7s(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(G3p in e)&&!(N0o in e)},u0S=e=>{if(!hOa(e)||_Oa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},s0S=FNt("Date"),c0S=FNt("File"),l0S=FNt("Blob"),f0S=FNt("FileList"),d0S=e=>hOa(e)&&IH(e.pipe),p0S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||IH(e.append)&&((t=F0o(e))==="formdata"||t==="object"&&IH(e.toString)&&e.toString()==="[object FormData]"))},_0S=FNt("URLSearchParams"),[h0S,y0S,b0S,v0S]=["ReadableStream","Request","Response","Headers"].map(FNt),g0S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function yOa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),jTn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(_Oa(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(i=0;i<o;i++)c=a[i],t.call(null,e[c],c,e)}}function J3p(e,t){if(_Oa(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var K7i=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,$3p=e=>!PTn(e)&&e!==K7i;function q7s(){let{caseless:e,skipUndefined:t}=$3p(this)&&this||{},r={},i=(n,a)=>{let o=e&&J3p(r,a)||a;z0o(r[o])&&z0o(n)?r[o]=q7s(r[o],n):z0o(n)?r[o]=q7s({},n):jTn(n)?r[o]=n.slice():(!t||!PTn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&yOa(arguments[n],i);return r}var O0S=(e,t,r,{allOwnKeys:i}={})=>(yOa(t,(n,a)=>{r&&IH(n)?e[a]=pOa(n,r):e[a]=n},{allOwnKeys:i}),e),A0S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),m0S=(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)},P0S=(e,t,r,i)=>{let n,a,o,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)o=n[a],(!i||i(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&T7s(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},j0S=(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},w0S=e=>{if(!e)return null;if(jTn(e))return e;let t=e.length;if(!K3p(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},E0S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&T7s(Uint8Array)),S0S=(e,t)=>{let i=(e&&e[N0o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},M0S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},D0S=FNt("HTMLFormElement"),B0S=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),x3p=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),I0S=FNt("RegExp"),Y3p=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};yOa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},C0S=e=>{Y3p(e,(t,r)=>{if(IH(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(IH(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+"'")})}})},q0S=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return jTn(e)?i(e):i(String(e).split(t)),r},T0S=()=>{},R0S=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function z0S(e){return!!(e&&IH(e.append)&&e[G3p]==="FormData"&&e[N0o])}var N0S=e=>{let t=new Array(10),r=(i,n)=>{if(hOa(i)){if(t.indexOf(i)>=0)return;if(_Oa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=jTn(i)?[]:{};return yOa(i,(o,c)=>{let f=r(o,n+1);!PTn(f)&&(a[c]=f)}),t[n]=void 0,a}}return i};return r(e,0)},F0S=FNt("AsyncFunction"),Q0S=e=>e&&(hOa(e)||IH(e))&&IH(e.then)&&IH(e.catch),X3p=((e,t)=>e?setImmediate:t?((r,i)=>(K7i.addEventListener("message",({source:n,data:a})=>{n===K7i&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),K7i.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",IH(K7i.postMessage)),U0S=typeof queueMicrotask<"u"?queueMicrotask.bind(K7i):typeof process<"u"&&process.nextTick||X3p,L0S=e=>e!=null&&IH(e[N0o]),er={isArray:jTn,isArrayBuffer:H3p,isBuffer:_Oa,isFormData:p0S,isArrayBufferView:n0S,isString:a0S,isNumber:K3p,isBoolean:o0S,isObject:hOa,isPlainObject:z0o,isEmptyObject:u0S,isReadableStream:h0S,isRequest:y0S,isResponse:b0S,isHeaders:v0S,isUndefined:PTn,isDate:s0S,isFile:c0S,isBlob:l0S,isRegExp:I0S,isFunction:IH,isStream:d0S,isURLSearchParams:_0S,isTypedArray:E0S,isFileList:f0S,forEach:yOa,merge:q7s,extend:O0S,trim:g0S,stripBOM:A0S,inherits:m0S,toFlatObject:P0S,kindOf:F0o,kindOfTest:FNt,endsWith:j0S,toArray:w0S,forEachEntry:S0S,matchAll:M0S,isHTMLForm:D0S,hasOwnProperty:x3p,hasOwnProp:x3p,reduceDescriptors:Y3p,freezeMethods:C0S,toObjectSet:q0S,toCamelCase:B0S,noop:T0S,toFiniteNumber:R0S,findKey:J3p,global:K7i,isContextDefined:$3p,isSpecCompliantForm:z0S,toJSONObject:N0S,isAsyncFn:F0S,isThenable:Q0S,setImmediate:X3p,asap:U0S,isIterable:L0S};function wTn(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)}er.inherits(wTn,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:er.toJSONObject(this.config),code:this.code,status:this.status}}});var Z3p=wTn.prototype,k3p={};["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=>{k3p[e]={value:e}});Object.defineProperties(wTn,k3p);Object.defineProperty(Z3p,"isAxiosError",{value:!0});wTn.from=(e,t,r,i,n,a)=>{let o=Object.create(Z3p);er.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",f=t==null&&e?e.code:t;return wTn.call(o,c,f,r,i,n),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var ha=wTn;var e8p=ce(IGi(),1),U0o=e8p.default;function R7s(e){return er.isPlainObject(e)||er.isArray(e)}function r8p(e){return er.endsWith(e,"[]")?e.slice(0,-2):e}function t8p(e,t,r){return e?e.concat(t).map(function(n,a){return n=r8p(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function V0S(e){return er.isArray(e)&&!e.some(R7s)}var W0S=er.toFlatObject(er,{},null,function(t){return/^is[A-Z]/.test(t)});function x0S(e,t,r){if(!er.isObject(e))throw new TypeError("target must be an object");t=t||new(U0o||FormData),r=er.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!er.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&er.isSpecCompliantForm(t);if(!er.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(er.isDate(h))return h.toISOString();if(er.isBoolean(h))return h.toString();if(!f&&er.isBlob(h))throw new ha("Blob is not supported. Use a Buffer instead.");return er.isArrayBuffer(h)||er.isTypedArray(h)?f&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,b){let v=h;if(h&&!b&&typeof h=="object"){if(er.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(er.isArray(h)&&V0S(h)||(er.isFileList(h)||er.endsWith(y,"[]"))&&(v=er.toArray(h)))return y=r8p(y),v.forEach(function(A,g){!(er.isUndefined(A)||A===null)&&t.append(o===!0?t8p([y],g,a):o===null?y:y+"[]",s(A))}),!1}return R7s(h)?!0:(t.append(t8p(b,y,a),s(h)),!1)}let l=[],p=Object.assign(W0S,{defaultVisitor:u,convertValue:s,isVisitable:R7s});function _(h,y){if(!er.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),er.forEach(h,function(v,O){(!(er.isUndefined(v)||v===null)&&n.call(t,v,er.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),l.pop()}}if(!er.isObject(e))throw new TypeError("data must be an object");return _(e),t}var FBi=x0S;function i8p(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function n8p(e,t){this._pairs=[],e&&FBi(e,this,t)}var a8p=n8p.prototype;a8p.append=function(t,r){this._pairs.push([t,r])};a8p.toString=function(t){let r=t?function(i){return t.call(this,i,i8p)}:i8p;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var o8p=n8p;function G0S(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function J7i(e,t,r){if(!t)return e;let i=r&&r.encode||G0S;er.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=er.isURLSearchParams(t)?t.toString():new o8p(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var z7s=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){er.forEach(this.handlers,function(i){i!==null&&t(i)})}},N7s=z7s;var ETn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var l8p=ce(require("crypto"),1);var u8p=ce(require("url"),1),s8p=u8p.default.URLSearchParams;var F7s="abcdefghijklmnopqrstuvwxyz",c8p="0123456789",f8p={DIGIT:c8p,ALPHA:F7s,ALPHA_DIGIT:F7s+F7s.toUpperCase()+c8p},H0S=(e=16,t=f8p.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);l8p.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},d8p={isNode:!0,classes:{URLSearchParams:s8p,FormData:U0o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:f8p,generateString:H0S,protocols:["http","https","file","data"]};var L7s={};Yt(L7s,{hasBrowserEnv:()=>U7s,hasStandardBrowserEnv:()=>K0S,hasStandardBrowserWebWorkerEnv:()=>J0S,navigator:()=>Q7s,origin:()=>$0S});var U7s=typeof window<"u"&&typeof document<"u",Q7s=typeof navigator=="object"&&navigator||void 0,K0S=U7s&&(!Q7s||["ReactNative","NativeScript","NS"].indexOf(Q7s.product)<0),J0S=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",$0S=U7s&&window.location.href||"http://localhost";var OA={...L7s,...d8p};function V7s(e,t){return FBi(e,new OA.classes.URLSearchParams,{visitor:function(r,i,n,a){return OA.isNode&&er.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function Y0S(e){return er.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function X0S(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 Z0S(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),f=a>=r.length;return o=!o&&er.isArray(n)?n.length:o,f?(er.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!er.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&er.isArray(n[o])&&(n[o]=X0S(n[o])),!c)}if(er.isFormData(e)&&er.isFunction(e.entries)){let r={};return er.forEachEntry(e,(i,n)=>{t(Y0S(i),n,r,0)}),r}return null}var L0o=Z0S;function k0S(e,t,r){if(er.isString(e))try{return(t||JSON.parse)(e),er.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var W7s={transitional:ETn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=er.isObject(t);if(a&&er.isHTMLForm(t)&&(t=new FormData(t)),er.isFormData(t))return n?JSON.stringify(L0o(t)):t;if(er.isArrayBuffer(t)||er.isBuffer(t)||er.isStream(t)||er.isFile(t)||er.isBlob(t)||er.isReadableStream(t))return t;if(er.isArrayBufferView(t))return t.buffer;if(er.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return V7s(t,this.formSerializer).toString();if((c=er.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return FBi(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),k0S(t)):t}],transformResponse:[function(t){let r=this.transitional||W7s.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(er.isResponse(t)||er.isReadableStream(t))return t;if(t&&er.isString(t)&&(i&&!this.responseType||n)){let o=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?ha.from(c,ha.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:OA.classes.FormData,Blob:OA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};er.forEach(["delete","get","head","post","put","patch"],e=>{W7s.headers[e]={}});var STn=W7s;var ePS=er.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"]),p8p=e=>{let t={},r,i,n;return e&&e.split(`
1151
1151
  `).forEach(function(o){n=o.indexOf(":"),r=o.substring(0,n).trim().toLowerCase(),i=o.substring(n+1).trim(),!(!r||t[r]&&ePS[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var _8p=Symbol("internals");function bOa(e){return e&&String(e).trim().toLowerCase()}function V0o(e){return e===!1||e==null?e:er.isArray(e)?e.map(V0o):String(e)}function tPS(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 rPS=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function x7s(e,t,r,i,n){if(er.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!er.isString(t)){if(er.isString(i))return t.indexOf(i)!==-1;if(er.isRegExp(i))return i.test(t)}}function iPS(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function nPS(e,t){let r=er.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,o){return this[i].call(this,t,n,a,o)},configurable:!0})})}var MTn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(c,f,s){let u=bOa(f);if(!u)throw new Error("header name must be a non-empty string");let l=er.findKey(n,u);(!l||n[l]===void 0||s===!0||s===void 0&&n[l]!==!1)&&(n[l||f]=V0o(c))}let o=(c,f)=>er.forEach(c,(s,u)=>a(s,u,f));if(er.isPlainObject(t)||t instanceof this.constructor)o(t,r);else if(er.isString(t)&&(t=t.trim())&&!rPS(t))o(p8p(t),r);else if(er.isObject(t)&&er.isIterable(t)){let c={},f,s;for(let u of t){if(!er.isArray(u))throw TypeError("Object iterator must return a key-value pair");c[s=u[0]]=(f=c[s])?er.isArray(f)?[...f,u[1]]:[f,u[1]]:u[1]}o(c,r)}else t!=null&&a(r,t,i);return this}get(t,r){if(t=bOa(t),t){let i=er.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return tPS(n);if(er.isFunction(r))return r.call(this,n,i);if(er.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=bOa(t),t){let i=er.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||x7s(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(o){if(o=bOa(o),o){let c=er.findKey(i,o);c&&(!r||x7s(i,i[c],c,r))&&(delete i[c],n=!0)}}return er.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||x7s(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return er.forEach(this,(n,a)=>{let o=er.findKey(i,a);if(o){r[o]=V0o(n),delete r[a];return}let c=t?iPS(a):String(a).trim();c!==a&&delete r[a],r[c]=V0o(n),i[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return er.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&er.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(`
1152
1152
  `)}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[_8p]=this[_8p]={accessors:{}}).accessors,n=this.prototype;function a(o){let c=bOa(o);i[c]||(nPS(n,o),i[c]=!0)}return er.isArray(t)?t.forEach(a):a(t),this}};MTn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);er.reduceDescriptors(MTn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});er.freezeMethods(MTn);var QS=MTn;function vOa(e,t){let r=this||STn,i=t||r,n=QS.from(i.headers),a=i.data;return er.forEach(e,function(c){a=c.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function gOa(e){return!!(e&&e.__CANCEL__)}function h8p(e,t,r){ha.call(this,e??"canceled",ha.ERR_CANCELED,t,r),this.name="CanceledError"}er.inherits(h8p,ha,{__CANCEL__:!0});var rhe=h8p;function u6t(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new ha("Request failed with status code "+r.status,[ha.ERR_BAD_REQUEST,ha.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function G7s(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function H7s(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function $7i(e,t,r){let i=!G7s(t);return e&&(i||r==!1)?H7s(e,t):t}var I8p=ce(c0o(),1),C8p=ce(require("http"),1),q8p=ce(require("https"),1),T8p=ce(require("util"),1),R8p=ce(KGs(),1),Lbi=ce(require("zlib"),1);var Y7i="1.12.2";function OOa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var aPS=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function K7s(e,t,r){let i=r&&r.Blob||OA.classes.Blob,n=OOa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=aPS.exec(e);if(!a)throw new ha("Invalid URL",ha.ERR_INVALID_URL);let o=a[1],c=a[2],f=a[3],s=Buffer.from(decodeURIComponent(f),c?"base64":"utf8");if(t){if(!i)throw new ha("Blob is not supported",ha.ERR_NOT_SUPPORT);return new i([s],{type:o})}return s}throw new ha("Unsupported protocol "+n,ha.ERR_NOT_SUPPORT)}var Z7i=ce(require("stream"),1);var y8p=ce(require("stream"),1);var J7s=Symbol("internals"),$7s=class extends y8p.default.Transform{constructor(t){t=er.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!er.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[J7s]={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[J7s];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[J7s],a=n.maxRate,o=this.readableHighWaterMark,c=n.timeWindow,f=1e3/c,s=a/f,u=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,l=(_,h)=>{let y=Buffer.byteLength(_);n.bytesSeen+=y,n.bytes+=y,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(_)?process.nextTick(h):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(h)}},p=(_,h)=>{let y=Buffer.byteLength(_),b=null,v=o,O,A=0;if(a){let g=Date.now();(!n.ts||(A=g-n.ts)>=c)&&(n.ts=g,O=s-n.bytes,n.bytes=O<0?-O:0,A=0),O=s-n.bytes}if(a){if(O<=0)return setTimeout(()=>{h(null,_)},c-A);O<v&&(v=O)}v&&y>v&&y-v>u&&(b=_.subarray(v),_=_.subarray(0,v)),l(_,b?()=>{process.nextTick(h,null,b)}:h)};p(t,function _(h,y){if(h)return i(h);y?p(y,_):i(null)})}},Y7s=$7s;var z8p=require("events");var v8p=ce(require("util"),1),g8p=require("stream");var{asyncIterator:b8p}=Symbol,oPS=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[b8p]?yield*e[b8p]():yield e},W0o=oPS;var uPS=OA.ALPHABET.ALPHA_DIGIT+"-_",AOa=typeof TextEncoder=="function"?new TextEncoder:new v8p.default.TextEncoder,X7i=`\r
1153
1153
  `,sPS=AOa.encode(X7i),cPS=2,X7s=class{constructor(t,r){let{escapeName:i}=this.constructor,n=er.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${X7i}`;n?r=AOa.encode(String(r).replace(/\r?\n|\r\n?/g,X7i)):a+=`Content-Type: ${r.type||"application/octet-stream"}${X7i}`,this.headers=AOa.encode(a+X7i),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+cPS,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;er.isTypedArray(t)?yield t:yield*W0o(t),yield sPS}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},lPS=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+OA.generateString(n,uPS)}=r||{};if(!er.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let o=AOa.encode("--"+a+X7i),c=AOa.encode("--"+a+"--"+X7i),f=c.byteLength,s=Array.from(e.entries()).map(([l,p])=>{let _=new X7s(l,p);return f+=_.size,_});f+=o.byteLength*s.length,f=er.toFiniteNumber(f);let u={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(f)&&(u["Content-Length"]=f),t&&t(u),g8p.Readable.from((async function*(){for(let l of s)yield o,yield*l.encode();yield c})())},O8p=lPS;var A8p=ce(require("stream"),1),Z7s=class extends A8p.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)}},m8p=Z7s;var fPS=(e,t)=>er.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,P8p=fPS;function dPS(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,o;return t=t!==void 0?t:1e3,function(f){let s=Date.now(),u=i[a];o||(o=s),r[n]=f,i[n]=s;let l=a,p=0;for(;l!==n;)p+=r[l++],l=l%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-o<t)return;let _=u&&s-u;return _?Math.round(p*1e3/_):void 0}}var j8p=dPS;function pPS(e,t){let r=0,i=1e3/t,n,a,o=(s,u=Date.now())=>{r=u,n=null,a&&(clearTimeout(a),a=null),e(...s)};return[(...s)=>{let u=Date.now(),l=u-r;l>=i?o(s,u):(n=s,a||(a=setTimeout(()=>{a=null,o(n)},i-l)))},()=>n&&o(n)]}var w8p=pPS;var Ubi=(e,t,r=3)=>{let i=0,n=j8p(50,250);return w8p(a=>{let o=a.loaded,c=a.lengthComputable?a.total:void 0,f=o-i,s=n(f),u=o<=c;i=o;let l={loaded:o,total:c,progress:c?o/c:void 0,bytes:f,rate:s||void 0,estimated:s&&c&&u?(c-o)/s:void 0,event:a,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(l)},r)},DTn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},BTn=e=>(...t)=>er.asap(()=>e(...t));function k7s(e){if(!e||typeof e!="string"||!e.startsWith("data:"))return 0;let t=e.indexOf(",");if(t<0)return 0;let r=e.slice(5,t),i=e.slice(t+1);if(/;base64/i.test(r)){let a=i.length,o=i.length;for(let p=0;p<o;p++)if(i.charCodeAt(p)===37&&p+2<o){let _=i.charCodeAt(p+1),h=i.charCodeAt(p+2);(_>=48&&_<=57||_>=65&&_<=70||_>=97&&_<=102)&&(h>=48&&h<=57||h>=65&&h<=70||h>=97&&h<=102)&&(a-=2,p+=2)}let c=0,f=o-1,s=p=>p>=2&&i.charCodeAt(p-2)===37&&i.charCodeAt(p-1)===51&&(i.charCodeAt(p)===68||i.charCodeAt(p)===100);f>=0&&(i.charCodeAt(f)===61?(c++,f--):s(f)&&(c++,f-=3)),c===1&&f>=0&&(i.charCodeAt(f)===61||s(f))&&c++;let l=Math.floor(a/4)*3-(c||0);return l>0?l:0}return Buffer.byteLength(i,"utf8")}var E8p={flush:Lbi.default.constants.Z_SYNC_FLUSH,finishFlush:Lbi.default.constants.Z_SYNC_FLUSH},_PS={flush:Lbi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:Lbi.default.constants.BROTLI_OPERATION_FLUSH},S8p=er.isFunction(Lbi.default.createBrotliDecompress),{http:hPS,https:yPS}=R8p.default,bPS=/https:?/,M8p=OA.protocols.map(e=>e+":"),D8p=(e,[t,r])=>(e.on("end",r).on("error",r),t);function vPS(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function N8p(e,t,r){let i=t;if(!i&&i!==!1){let n=I8p.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){N8p(a,t,a.href)}}var gPS=typeof process<"u"&&er.kindOf(process)==="process",OPS=e=>new Promise((t,r)=>{let i,n,a=(f,s)=>{n||(n=!0,i&&i(f,s))},o=f=>{a(f),t(f)},c=f=>{a(f,!0),r(f)};e(o,c,f=>i=f).catch(c)}),APS=({address:e,family:t})=>{if(!er.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},B8p=(e,t)=>APS(er.isObject(e)?e:{address:e,family:t}),F8p=gPS&&function(t){return OPS(async function(i,n,a){let{data:o,lookup:c,family:f}=t,{responseType:s,responseEncoding:u}=t,l=t.method.toUpperCase(),p,_=!1,h;if(c){let J=P8p(c,fe=>er.isArray(fe)?fe:[fe]);c=(fe,be,V)=>{J(fe,be,(U,Se,ue)=>{if(U)return V(U);let we=er.isArray(Se)?Se.map(Le=>B8p(Le)):[B8p(Se,ue)];be.all?V(U,we):V(U,we[0].address,we[0].family)})}}let y=new z8p.EventEmitter,b=()=>{t.cancelToken&&t.cancelToken.unsubscribe(v),t.signal&&t.signal.removeEventListener("abort",v),y.removeAllListeners()};a((J,fe)=>{p=!0,fe&&(_=!0,b())});function v(J){y.emit("abort",!J||J.type?new rhe(null,t,h):J)}y.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(v),t.signal&&(t.signal.aborted?v():t.signal.addEventListener("abort",v)));let O=$7i(t.baseURL,t.url,t.allowAbsoluteUrls),A=new URL(O,OA.hasBrowserEnv?OA.origin:void 0),g=A.protocol||M8p[0];if(g==="data:"){if(t.maxContentLength>-1){let fe=String(t.url||O||"");if(k7s(fe)>t.maxContentLength)return n(new ha("maxContentLength size of "+t.maxContentLength+" exceeded",ha.ERR_BAD_RESPONSE,t))}let J;if(l!=="GET")return u6t(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{J=K7s(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(fe){throw ha.from(fe,ha.ERR_BAD_REQUEST,t)}return s==="text"?(J=J.toString(u),(!u||u==="utf8")&&(J=er.stripBOM(J))):s==="stream"&&(J=Z7i.default.Readable.from(J)),u6t(i,n,{data:J,status:200,statusText:"OK",headers:new QS,config:t})}if(M8p.indexOf(g)===-1)return n(new ha("Unsupported protocol "+g,ha.ERR_BAD_REQUEST,t));let m=QS.from(t.headers).normalize();m.set("User-Agent","axios/"+Y7i,!1);let{onUploadProgress:j,onDownloadProgress:S}=t,E=t.maxRate,D,B;if(er.isSpecCompliantForm(o)){let J=m.getContentType(/boundary=([-_\w\d]{10,70})/i);o=O8p(o,fe=>{m.set(fe)},{tag:`axios-${Y7i}-boundary`,boundary:J&&J[1]||void 0})}else if(er.isFormData(o)&&er.isFunction(o.getHeaders)){if(m.set(o.getHeaders()),!m.hasContentLength())try{let J=await T8p.default.promisify(o.getLength).call(o);Number.isFinite(J)&&J>=0&&m.setContentLength(J)}catch{}}else if(er.isBlob(o)||er.isFile(o))o.size&&m.setContentType(o.type||"application/octet-stream"),m.setContentLength(o.size||0),o=Z7i.default.Readable.from(W0o(o));else if(o&&!er.isStream(o)){if(!Buffer.isBuffer(o))if(er.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else if(er.isString(o))o=Buffer.from(o,"utf-8");else return n(new ha("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",ha.ERR_BAD_REQUEST,t));if(m.setContentLength(o.length,!1),t.maxBodyLength>-1&&o.length>t.maxBodyLength)return n(new ha("Request body larger than maxBodyLength limit",ha.ERR_BAD_REQUEST,t))}let F=er.toFiniteNumber(m.getContentLength());er.isArray(E)?(D=E[0],B=E[1]):D=B=E,o&&(j||D)&&(er.isStream(o)||(o=Z7i.default.Readable.from(o,{objectMode:!1})),o=Z7i.default.pipeline([o,new Y7s({maxRate:er.toFiniteNumber(D)})],er.noop),j&&o.on("progress",D8p(o,DTn(F,Ubi(BTn(j),!1,3)))));let N;if(t.auth){let J=t.auth.username||"",fe=t.auth.password||"";N=J+":"+fe}if(!N&&A.username){let J=A.username,fe=A.password;N=J+":"+fe}N&&m.delete("authorization");let R;try{R=J7i(A.pathname+A.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(J){let fe=new Error(J.message);return fe.config=t,fe.url=t.url,fe.exists=!0,n(fe)}m.set("Accept-Encoding","gzip, compress, deflate"+(S8p?", br":""),!1);let z={path:R,method:l,headers:m.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:N,protocol:g,family:f,beforeRedirect:vPS,beforeRedirects:{}};!er.isUndefined(c)&&(z.lookup=c),t.socketPath?z.socketPath=t.socketPath:(z.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,z.port=A.port,N8p(z,t.proxy,g+"//"+A.hostname+(A.port?":"+A.port:"")+z.path));let L,H=bPS.test(z.protocol);if(z.agent=H?t.httpsAgent:t.httpAgent,t.transport?L=t.transport:t.maxRedirects===0?L=H?q8p.default:C8p.default:(t.maxRedirects&&(z.maxRedirects=t.maxRedirects),t.beforeRedirect&&(z.beforeRedirects.config=t.beforeRedirect),L=H?yPS:hPS),t.maxBodyLength>-1?z.maxBodyLength=t.maxBodyLength:z.maxBodyLength=1/0,t.insecureHTTPParser&&(z.insecureHTTPParser=t.insecureHTTPParser),h=L.request(z,function(fe){if(h.destroyed)return;let be=[fe],V=+fe.headers["content-length"];if(S||B){let Le=new Y7s({maxRate:er.toFiniteNumber(B)});S&&Le.on("progress",D8p(Le,DTn(V,Ubi(BTn(S),!0,3)))),be.push(Le)}let U=fe,Se=fe.req||h;if(t.decompress!==!1&&fe.headers["content-encoding"])switch((l==="HEAD"||fe.statusCode===204)&&delete fe.headers["content-encoding"],(fe.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":be.push(Lbi.default.createUnzip(E8p)),delete fe.headers["content-encoding"];break;case"deflate":be.push(new m8p),be.push(Lbi.default.createUnzip(E8p)),delete fe.headers["content-encoding"];break;case"br":S8p&&(be.push(Lbi.default.createBrotliDecompress(_PS)),delete fe.headers["content-encoding"])}U=be.length>1?Z7i.default.pipeline(be,er.noop):be[0];let ue=Z7i.default.finished(U,()=>{ue(),b()}),we={status:fe.statusCode,statusText:fe.statusMessage,headers:new QS(fe.headers),config:t,request:Se};if(s==="stream")we.data=U,u6t(i,n,we);else{let Le=[],se=0;U.on("data",function(Ge){Le.push(Ge),se+=Ge.length,t.maxContentLength>-1&&se>t.maxContentLength&&(_=!0,U.destroy(),n(new ha("maxContentLength size of "+t.maxContentLength+" exceeded",ha.ERR_BAD_RESPONSE,t,Se)))}),U.on("aborted",function(){if(_)return;let Ge=new ha("stream has been aborted",ha.ERR_BAD_RESPONSE,t,Se);U.destroy(Ge),n(Ge)}),U.on("error",function(Ge){h.destroyed||n(ha.from(Ge,null,t,Se))}),U.on("end",function(){try{let Ge=Le.length===1?Le[0]:Buffer.concat(Le);s!=="arraybuffer"&&(Ge=Ge.toString(u),(!u||u==="utf8")&&(Ge=er.stripBOM(Ge))),we.data=Ge}catch(Ge){return n(ha.from(Ge,null,t,we.request,we))}u6t(i,n,we)})}y.once("abort",Le=>{U.destroyed||(U.emit("error",Le),U.destroy())})}),y.once("abort",J=>{n(J),h.destroy(J)}),h.on("error",function(fe){n(ha.from(fe,null,t,h))}),h.on("socket",function(fe){fe.setKeepAlive(!0,1e3*60)}),t.timeout){let J=parseInt(t.timeout,10);if(Number.isNaN(J)){n(new ha("error trying to parse `config.timeout` to int",ha.ERR_BAD_OPTION_VALUE,t,h));return}h.setTimeout(J,function(){if(p)return;let be=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",V=t.transitional||ETn;t.timeoutErrorMessage&&(be=t.timeoutErrorMessage),n(new ha(be,V.clarifyTimeoutError?ha.ETIMEDOUT:ha.ECONNABORTED,t,h)),v()})}if(er.isStream(o)){let J=!1,fe=!1;o.on("end",()=>{J=!0}),o.once("error",be=>{fe=!0,h.destroy(be)}),o.on("close",()=>{!J&&!fe&&v(new rhe("Request stream has been aborted",t,h))}),o.pipe(h)}else h.end(o)})};var Q8p=OA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,OA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(OA.origin),OA.navigator&&/(msie|trident)/i.test(OA.navigator.userAgent)):()=>!0;var U8p=OA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let o=[e+"="+encodeURIComponent(t)];er.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),er.isString(i)&&o.push("path="+i),er.isString(n)&&o.push("domain="+n),a===!0&&o.push("secure"),document.cookie=o.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var L8p=e=>e instanceof QS?{...e}:e;function QNt(e,t){t=t||{};let r={};function i(s,u,l,p){return er.isPlainObject(s)&&er.isPlainObject(u)?er.merge.call({caseless:p},s,u):er.isPlainObject(u)?er.merge({},u):er.isArray(u)?u.slice():u}function n(s,u,l,p){if(er.isUndefined(u)){if(!er.isUndefined(s))return i(void 0,s,l,p)}else return i(s,u,l,p)}function a(s,u){if(!er.isUndefined(u))return i(void 0,u)}function o(s,u){if(er.isUndefined(u)){if(!er.isUndefined(s))return i(void 0,s)}else return i(void 0,u)}function c(s,u,l){if(l in t)return i(s,u);if(l in e)return i(void 0,s)}let f={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:c,headers:(s,u,l)=>n(L8p(s),L8p(u),l,!0)};return er.forEach(Object.keys({...e,...t}),function(u){let l=f[u]||n,p=l(e[u],t[u],u);er.isUndefined(p)&&l!==c||(r[u]=p)}),r}var x0o=e=>{let t=QNt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=QS.from(o),t.url=J7i($7i(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),er.isFormData(r)){if(OA.hasStandardBrowserEnv||OA.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(er.isFunction(r.getHeaders)){let f=r.getHeaders(),s=["content-type","content-length"];Object.entries(f).forEach(([u,l])=>{s.includes(u.toLowerCase())&&o.set(u,l)})}}if(OA.hasStandardBrowserEnv&&(i&&er.isFunction(i)&&(i=i(t)),i||i!==!1&&Q8p(t.url))){let f=n&&a&&U8p.read(a);f&&o.set(n,f)}return t};var mPS=typeof XMLHttpRequest<"u",V8p=mPS&&function(e){return new Promise(function(r,i){let n=x0o(e),a=n.data,o=QS.from(n.headers).normalize(),{responseType:c,onUploadProgress:f,onDownloadProgress:s}=n,u,l,p,_,h;function y(){_&&_(),h&&h(),n.cancelToken&&n.cancelToken.unsubscribe(u),n.signal&&n.signal.removeEventListener("abort",u)}let b=new XMLHttpRequest;b.open(n.method.toUpperCase(),n.url,!0),b.timeout=n.timeout;function v(){if(!b)return;let A=QS.from("getAllResponseHeaders"in b&&b.getAllResponseHeaders()),m={data:!c||c==="text"||c==="json"?b.responseText:b.response,status:b.status,statusText:b.statusText,headers:A,config:e,request:b};u6t(function(S){r(S),y()},function(S){i(S),y()},m),b=null}"onloadend"in b?b.onloadend=v:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(v)},b.onabort=function(){b&&(i(new ha("Request aborted",ha.ECONNABORTED,e,b)),b=null)},b.onerror=function(g){let m=g&&g.message?g.message:"Network Error",j=new ha(m,ha.ERR_NETWORK,e,b);j.event=g||null,i(j),b=null},b.ontimeout=function(){let g=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",m=n.transitional||ETn;n.timeoutErrorMessage&&(g=n.timeoutErrorMessage),i(new ha(g,m.clarifyTimeoutError?ha.ETIMEDOUT:ha.ECONNABORTED,e,b)),b=null},a===void 0&&o.setContentType(null),"setRequestHeader"in b&&er.forEach(o.toJSON(),function(g,m){b.setRequestHeader(m,g)}),er.isUndefined(n.withCredentials)||(b.withCredentials=!!n.withCredentials),c&&c!=="json"&&(b.responseType=n.responseType),s&&([p,h]=Ubi(s,!0),b.addEventListener("progress",p)),f&&b.upload&&([l,_]=Ubi(f),b.upload.addEventListener("progress",l),b.upload.addEventListener("loadend",_)),(n.cancelToken||n.signal)&&(u=A=>{b&&(i(!A||A.type?new rhe(null,e,b):A),b.abort(),b=null)},n.cancelToken&&n.cancelToken.subscribe(u),n.signal&&(n.signal.aborted?u():n.signal.addEventListener("abort",u)));let O=OOa(n.url);if(O&&OA.protocols.indexOf(O)===-1){i(new ha("Unsupported protocol "+O+":",ha.ERR_BAD_REQUEST,e));return}b.send(a||null)})};var PPS=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,c();let u=s instanceof Error?s:this.reason;i.abort(u instanceof ha?u:new rhe(u instanceof Error?u.message:u))}},o=t&&setTimeout(()=>{o=null,a(new ha(`timeout ${t} of ms exceeded`,ha.ETIMEDOUT))},t),c=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:f}=i;return f.unsubscribe=()=>er.asap(c),f}},W8p=PPS;var jPS=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},wPS=async function*(e,t){for await(let r of EPS(e))yield*jPS(r,t)},EPS=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()}},eHs=(e,t,r,i)=>{let n=wPS(e,t),a=0,o,c=f=>{o||(o=!0,i&&i(f))};return new ReadableStream({async pull(f){try{let{done:s,value:u}=await n.next();if(s){c(),f.close();return}let l=u.byteLength;if(r){let p=a+=l;r(p)}f.enqueue(new Uint8Array(u))}catch(s){throw c(s),s}},cancel(f){return c(f),n.return()}},{highWaterMark:2})};var x8p=64*1024,{isFunction:G0o}=er,SPS=(({Request:e,Response:t})=>({Request:e,Response:t}))(er.global),{ReadableStream:G8p,TextEncoder:H8p}=er.global,K8p=(e,...t)=>{try{return!!e(...t)}catch{return!1}},MPS=e=>{e=er.merge.call({skipUndefined:!0},SPS,e);let{fetch:t,Request:r,Response:i}=e,n=t?G0o(t):typeof fetch=="function",a=G0o(r),o=G0o(i);if(!n)return!1;let c=n&&G0o(G8p),f=n&&(typeof H8p=="function"?(h=>y=>h.encode(y))(new H8p):async h=>new Uint8Array(await new r(h).arrayBuffer())),s=a&&c&&K8p(()=>{let h=!1,y=new r(OA.origin,{body:new G8p,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!y}),u=o&&c&&K8p(()=>er.isReadableStream(new i("").body)),l={stream:u&&(h=>h.body)};n&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!l[h]&&(l[h]=(y,b)=>{let v=y&&y[h];if(v)return v.call(y);throw new ha(`Response type '${h}' is not supported`,ha.ERR_NOT_SUPPORT,b)})});let p=async h=>{if(h==null)return 0;if(er.isBlob(h))return h.size;if(er.isSpecCompliantForm(h))return(await new r(OA.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(er.isArrayBufferView(h)||er.isArrayBuffer(h))return h.byteLength;if(er.isURLSearchParams(h)&&(h=h+""),er.isString(h))return(await f(h)).byteLength},_=async(h,y)=>{let b=er.toFiniteNumber(h.getContentLength());return b??p(y)};return async h=>{let{url:y,method:b,data:v,signal:O,cancelToken:A,timeout:g,onDownloadProgress:m,onUploadProgress:j,responseType:S,headers:E,withCredentials:D="same-origin",fetchOptions:B}=x0o(h),F=t||fetch;S=S?(S+"").toLowerCase():"text";let N=W8p([O,A&&A.toAbortSignal()],g),R=null,z=N&&N.unsubscribe&&(()=>{N.unsubscribe()}),L;try{if(j&&s&&b!=="get"&&b!=="head"&&(L=await _(E,v))!==0){let U=new r(y,{method:"POST",body:v,duplex:"half"}),Se;if(er.isFormData(v)&&(Se=U.headers.get("content-type"))&&E.setContentType(Se),U.body){let[ue,we]=DTn(L,Ubi(BTn(j)));v=eHs(U.body,x8p,ue,we)}}er.isString(D)||(D=D?"include":"omit");let H=a&&"credentials"in r.prototype,J={...B,signal:N,method:b.toUpperCase(),headers:E.normalize().toJSON(),body:v,duplex:"half",credentials:H?D:void 0};R=a&&new r(y,J);let fe=await(a?F(R,B):F(y,J)),be=u&&(S==="stream"||S==="response");if(u&&(m||be&&z)){let U={};["status","statusText","headers"].forEach(Le=>{U[Le]=fe[Le]});let Se=er.toFiniteNumber(fe.headers.get("content-length")),[ue,we]=m&&DTn(Se,Ubi(BTn(m),!0))||[];fe=new i(eHs(fe.body,x8p,ue,()=>{we&&we(),z&&z()}),U)}S=S||"text";let V=await l[er.findKey(l,S)||"text"](fe,h);return!be&&z&&z(),await new Promise((U,Se)=>{u6t(U,Se,{data:V,headers:QS.from(fe.headers),status:fe.status,statusText:fe.statusText,config:h,request:R})})}catch(H){throw z&&z(),H&&H.name==="TypeError"&&/Load failed|fetch/i.test(H.message)?Object.assign(new ha("Network Error",ha.ERR_NETWORK,h,R),{cause:H.cause||H}):ha.from(H,H&&H.code,h,R)}}},DPS=new Map,tHs=e=>{let t=e?e.env:{},{fetch:r,Request:i,Response:n}=t,a=[i,n,r],o=a.length,c=o,f,s,u=DPS;for(;c--;)f=a[c],s=u.get(f),s===void 0&&u.set(f,s=c?new Map:MPS(t)),u=s;return s},Dg5=tHs();var rHs={http:F8p,xhr:V8p,fetch:{get:tHs}};er.forEach(rHs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var J8p=e=>`- ${e}`,IPS=e=>er.isFunction(e)||e===null||e===!1,H0o={getAdapter:(e,t)=>{e=er.isArray(e)?e:[e];let{length:r}=e,i,n,a={};for(let o=0;o<r;o++){i=e[o];let c;if(n=i,!IPS(i)&&(n=rHs[(c=String(i)).toLowerCase()],n===void 0))throw new ha(`Unknown adapter '${c}'`);if(n&&(er.isFunction(n)||(n=n.get(t))))break;a[c||"#"+o]=n}if(!n){let o=Object.entries(a).map(([f,s])=>`adapter ${f} `+(s===!1?"is not supported by the environment":"is not available in the build")),c=r?o.length>1?`since :
@@ -1391,7 +1391,7 @@ ${g}${O}${m}${mQn}`});function TQo({message:e,error:t,logger:r,logLevel:i=$s.Err
1391
1391
  Run ${Ut.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1392
1392
  Run ${Ut.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),LBi(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function Nuc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!Uf_(e))return;let n=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let o=a.sort((c,f)=>c.generatorName.localeCompare(f.generatorName)||c.currentVersion.localeCompare(f.currentVersion));for(let c of o)n+=`
1393
1393
  ${await bZS(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Ut.dim(c.currentVersion)+Ut.reset(" \u2192 ")+Ut.green(c.latestVersion);return n+=`
1394
- `,i?LBi(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function bZS(e){let r=await new Qf_.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 vZS({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await Vf_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=QMi(u.name,l),_=await pNt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:l});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await Vf_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,f,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][f]==null&&(o.versions[c][f]={});let l=QMi(s.name,u),p=await pNt({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][f][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function Vf_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await Y_e({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let f=i!=null?DR(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)f!=null&&u.name!==f||await r(a.workspaceName,s.groupName,u,o)})}))}function Wf_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let f=eK(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:f,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function FQo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await vZS({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[f,s]of Object.entries(c.versions))o.push(...Wf_(s,f,t.logger));else o.push(...Wf_(c.versions,void 0,t.logger))}return o}var TPa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var EQn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Fuc=(()=>{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})(),xf_=typeof globalThis.AbortController=="function",Gf_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Hf_=typeof globalThis.ReadableStream=="function",Kf_=typeof globalThis.FormData=="function",QQo=["get","post","put","patch","head","delete"],gZS=()=>{};gZS();var Jf_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},UQo=2147483647,$f_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,LQo=Symbol("stop"),Yf_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Xf_={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 OZS=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=$f_,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},Zf_=(e,t,r)=>{let i,n=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),i){n+=i.byteLength;let c=t===0?0:n/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,n),transferredBytes:n},i)}i=a},flush(){i&&(n+=i.byteLength,r?.({percent:1,totalBytes:Math.max(t,n),transferredBytes:n},i))}}))},kf_=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let r=Number(e.headers.get("content-length"))||0;return new Response(Zf_(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},ed_=(e,t,r)=>{if(!e.body)return e;let i=OZS(r??e.body);return new Request(e,{duplex:"half",body:Zf_(e.body,i,t)})};var SQn=e=>e!==null&&typeof e=="object";var RPa=(...e)=>{for(let t of e)if((!SQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Luc({},...e)},Quc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,o]of n.entries())i&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function VQo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Luc(e[r]??[],t[r]??[])}var Uuc=(e={},t={})=>({beforeRequest:VQo(e,t,"beforeRequest"),beforeRetry:VQo(e,t,"beforeRetry"),afterResponse:VQo(e,t,"afterResponse"),beforeError:VQo(e,t,"beforeError")}),Luc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(SQn(n)){for(let[a,o]of Object.entries(n))SQn(o)&&a in t&&(o=Luc(t[a],o)),t={...t,[a]:o};SQn(n.hooks)&&(i=Uuc(i,n.hooks),t.hooks=i),SQn(n.headers)&&(r=Quc(r,n.headers),t.headers=r)}return t};var rd_=e=>QQo.includes(e)?e.toUpperCase():e,AZS=["get","put","head","delete","options","trace"],mZS=[408,413,429,500,502,503,504],PZS=[413,429,503],td_={limit:2,methods:AZS,statusCodes:mZS,afterStatusCodes:PZS,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},id_=(e={})=>{if(typeof e=="number")return{...td_,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{...td_,...e}};async function Vuc(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new EQn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function Wuc(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 nd_=(e,t)=>{let r={};for(let i in t)!(i in Xf_)&&!(i in Yf_)&&!(i in e)&&(r[i]=t[i]);return r},ad_=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;var zPa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>UQo)throw new RangeError(`The \`timeout\` option cannot be greater than ${UQo}`);await Promise.resolve();let c=await i._fetch();for(let f of i._options.hooks.afterResponse){let s=await f(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let f=new TPa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)f=await s(f);throw f}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Hf_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return kf_(c.clone(),i._options.onDownloadProgress)}return c},o=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{let c=i._originalRequest,f=[];c&&!c.bodyUsed&&f.push(c.body?.cancel()),i.request.bodyUsed||f.push(i.request.body?.cancel()),await Promise.all(f)});for(let[c,f]of Object.entries(Jf_))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||f);let s=await o;if(c==="json"){if(s.status===204)return"";let u=await s.text();return u===""?"":r.parseJson?r.parseJson(u):JSON.parse(u)}return s[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:Quc(this._input.headers,r.headers),hooks:Uuc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:rd_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:id_(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(xf_&&Gf_){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(Fuc&&(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),ad_(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Kf_&&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(!Fuc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=ed_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof EQn)throw t;if(t instanceof TPa){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),UQo);if(this._retryCount<1)throw r;await Wuc(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})===LQo)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=nd_(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):Vuc(this._originalRequest,t,this.abortController,this._options)}};var xuc=e=>{let t=(r,i)=>zPa.create(r,RPa(e,i));for(let r of QQo)t[r]=(i,n)=>zPa.create(i,RPa(e,n,{method:r}));return t.create=r=>xuc(RPa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),xuc(RPa(e,r))),t.stop=LQo,t},jZS=xuc(),od_=jZS;var Dd_=ce(Md_(),1);function $uc(e){let t=(0,Dd_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Pp_=ce(mp_(),1),jp_=ce(P_e(),1),ssc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},csc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function lsc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??$uc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,Pp_.default)(a.toString(),{recursive:!0}),f={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete f.accept,c&&(f.authorization=`${c.type} ${c.token}`);let s;try{s=await od_(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new ssc(e):l}if(t.allVersions)return s;let u=new csc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!l){let _=Object.keys(s.versions);if(r=jp_.default.maxSatisfying(_,r),!r)throw u}let{time:p}=s;if(s=s.versions[r],s.time=p,!s)throw u}return s}async function VPa(e,t){let{version:r}=await lsc(e.toLowerCase(),t);return r}async function RCi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:VPa(e.packageName,{version:t?"prerelease":"latest"})}var wp_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],eUo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=$s.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new NQo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.26.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Ut.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new TE}failWithoutThrowing(t,r){this.didSucceed=!1,TQo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await mTn()).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 Lf_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1394
+ `,i?LBi(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function bZS(e){let r=await new Qf_.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 vZS({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await Vf_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=QMi(u.name,l),_=await pNt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:l});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await Vf_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,f,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][f]==null&&(o.versions[c][f]={});let l=QMi(s.name,u),p=await pNt({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][f][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function Vf_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await Y_e({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let f=i!=null?DR(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)f!=null&&u.name!==f||await r(a.workspaceName,s.groupName,u,o)})}))}function Wf_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let f=eK(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:f,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function FQo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await vZS({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[f,s]of Object.entries(c.versions))o.push(...Wf_(s,f,t.logger));else o.push(...Wf_(c.versions,void 0,t.logger))}return o}var TPa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var EQn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Fuc=(()=>{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})(),xf_=typeof globalThis.AbortController=="function",Gf_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Hf_=typeof globalThis.ReadableStream=="function",Kf_=typeof globalThis.FormData=="function",QQo=["get","post","put","patch","head","delete"],gZS=()=>{};gZS();var Jf_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},UQo=2147483647,$f_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,LQo=Symbol("stop"),Yf_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Xf_={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 OZS=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=$f_,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},Zf_=(e,t,r)=>{let i,n=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),i){n+=i.byteLength;let c=t===0?0:n/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,n),transferredBytes:n},i)}i=a},flush(){i&&(n+=i.byteLength,r?.({percent:1,totalBytes:Math.max(t,n),transferredBytes:n},i))}}))},kf_=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let r=Number(e.headers.get("content-length"))||0;return new Response(Zf_(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},ed_=(e,t,r)=>{if(!e.body)return e;let i=OZS(r??e.body);return new Request(e,{duplex:"half",body:Zf_(e.body,i,t)})};var SQn=e=>e!==null&&typeof e=="object";var RPa=(...e)=>{for(let t of e)if((!SQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Luc({},...e)},Quc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,o]of n.entries())i&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function VQo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Luc(e[r]??[],t[r]??[])}var Uuc=(e={},t={})=>({beforeRequest:VQo(e,t,"beforeRequest"),beforeRetry:VQo(e,t,"beforeRetry"),afterResponse:VQo(e,t,"afterResponse"),beforeError:VQo(e,t,"beforeError")}),Luc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(SQn(n)){for(let[a,o]of Object.entries(n))SQn(o)&&a in t&&(o=Luc(t[a],o)),t={...t,[a]:o};SQn(n.hooks)&&(i=Uuc(i,n.hooks),t.hooks=i),SQn(n.headers)&&(r=Quc(r,n.headers),t.headers=r)}return t};var rd_=e=>QQo.includes(e)?e.toUpperCase():e,AZS=["get","put","head","delete","options","trace"],mZS=[408,413,429,500,502,503,504],PZS=[413,429,503],td_={limit:2,methods:AZS,statusCodes:mZS,afterStatusCodes:PZS,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},id_=(e={})=>{if(typeof e=="number")return{...td_,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{...td_,...e}};async function Vuc(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new EQn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function Wuc(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 nd_=(e,t)=>{let r={};for(let i in t)!(i in Xf_)&&!(i in Yf_)&&!(i in e)&&(r[i]=t[i]);return r},ad_=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e=="object"?Object.keys(e).length>0:typeof e=="string"?e.trim().length>0:!!e;var zPa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>UQo)throw new RangeError(`The \`timeout\` option cannot be greater than ${UQo}`);await Promise.resolve();let c=await i._fetch();for(let f of i._options.hooks.afterResponse){let s=await f(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let f=new TPa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)f=await s(f);throw f}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Hf_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return kf_(c.clone(),i._options.onDownloadProgress)}return c},o=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{let c=i._originalRequest,f=[];c&&!c.bodyUsed&&f.push(c.body?.cancel()),i.request.bodyUsed||f.push(i.request.body?.cancel()),await Promise.all(f)});for(let[c,f]of Object.entries(Jf_))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||f);let s=await o;if(c==="json"){if(s.status===204)return"";let u=await s.text();return u===""?"":r.parseJson?r.parseJson(u):JSON.parse(u)}return s[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:Quc(this._input.headers,r.headers),hooks:Uuc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:rd_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:id_(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(xf_&&Gf_){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(Fuc&&(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),ad_(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Kf_&&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(!Fuc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=ed_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof EQn)throw t;if(t instanceof TPa){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),UQo);if(this._retryCount<1)throw r;await Wuc(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})===LQo)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=nd_(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):Vuc(this._originalRequest,t,this.abortController,this._options)}};var xuc=e=>{let t=(r,i)=>zPa.create(r,RPa(e,i));for(let r of QQo)t[r]=(i,n)=>zPa.create(i,RPa(e,n,{method:r}));return t.create=r=>xuc(RPa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),xuc(RPa(e,r))),t.stop=LQo,t},jZS=xuc(),od_=jZS;var Dd_=ce(Md_(),1);function $uc(e){let t=(0,Dd_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Pp_=ce(mp_(),1),jp_=ce(P_e(),1),ssc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},csc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function lsc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??$uc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,Pp_.default)(a.toString(),{recursive:!0}),f={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete f.accept,c&&(f.authorization=`${c.type} ${c.token}`);let s;try{s=await od_(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new ssc(e):l}if(t.allVersions)return s;let u=new csc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!l){let _=Object.keys(s.versions);if(r=jp_.default.maxSatisfying(_,r),!r)throw u}let{time:p}=s;if(s=s.versions[r],s.time=p,!s)throw u}return s}async function VPa(e,t){let{version:r}=await lsc(e.toLowerCase(),t);return r}async function RCi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:VPa(e.packageName,{version:t?"prerelease":"latest"})}var wp_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],eUo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=$s.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new NQo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.26.2"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Ut.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new TE}failWithoutThrowing(t,r){this.didSucceed=!1,TQo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await mTn()).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 Lf_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1395
1395
  `)||(r+=`
1396
1396
  `),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=_ws(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 MPa(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 TE}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await mTn()).sendEvent(t)}logger=Y8t((t,...r)=>this.log(t,...r));stderr=Y8t((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=Ep_(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?Ep_(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=wp_[this.numTasks++%wp_.length],o=Ut.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===yj.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=>oMi.indexOf(n.level)>=oMi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===$s.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 RCi({cliEnvironment:this.environment,includePreReleases:t}),i=eK(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await FQo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await wuc({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Ut.yellow("?"),style:{answer:n=>Ut.cyan(n),message:n=>Ut.bold(n),highlight:n=>Ut.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
1397
1397
  Cancelled by user.`),new TE):i}}async getInput(t){return await Auc({message:t.message,default:t.default})}};function Ep_(e){return`[${e}]:`}var yFt=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}};function tUo(e,t,r,i){if(typeof r!="function")throw new Error("method for before hook must be a function");return i||(i={}),Array.isArray(t)?t.reverse().reduce((n,a)=>tUo.bind(null,e,a,n,i),r)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((n,a)=>a.hook.bind(null,n,i),r)():r(i))}function Sp_(e,t,r,i){let n=i;e.registry[r]||(e.registry[r]=[]),t==="before"&&(i=(a,o)=>Promise.resolve().then(n.bind(null,o)).then(a.bind(null,o))),t==="after"&&(i=(a,o)=>{let c;return Promise.resolve().then(a.bind(null,o)).then(f=>(c=f,n(c,o))).then(()=>c)}),t==="error"&&(i=(a,o)=>Promise.resolve().then(a.bind(null,o)).catch(c=>n(c,o))),e.registry[r].push({hook:i,orig:n})}function Mp_(e,t,r){if(!e.registry[t])return;let i=e.registry[t].map(n=>n.orig).indexOf(r);i!==-1&&e.registry[t].splice(i,1)}var Dp_=Function.bind,Bp_=Dp_.bind(Dp_);function Ip_(e,t,r){let i=Bp_(Mp_,null).apply(null,r?[t,r]:[t]);e.api={remove:i},e.remove=i,["before","error","after","wrap"].forEach(n=>{let a=r?[t,n,r]:[t,n];e[n]=e.api[n]=Bp_(Sp_,null).apply(null,a)})}function B2S(){let e=Symbol("Singular"),t={registry:{}},r=tUo.bind(null,t,e);return Ip_(r,t,e),r}function I2S(){let e={registry:{}},t=tUo.bind(null,e);return Ip_(t,e),t}var Cp_={Singular:B2S,Collection:I2S};var C2S="0.0.0-development",q2S=`octokit-endpoint.js/${C2S} ${TR()}`,T2S={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":q2S},mediaType:{format:""}};function R2S(e){return e?Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{}):{}}function z2S(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}function Rp_(e,t){let r=Object.assign({},e);return Object.keys(t).forEach(i=>{z2S(t[i])?i in e?r[i]=Rp_(e[i],t[i]):Object.assign(r,{[i]:t[i]}):Object.assign(r,{[i]:t[i]})}),r}function qp_(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function dsc(e,t,r){if(typeof t=="string"){let[n,a]=t.split(" ");r=Object.assign(a?{method:n,url:a}:{url:n},r)}else r=Object.assign({},t);r.headers=R2S(r.headers),qp_(r),qp_(r.headers);let i=Rp_(e||{},r);return r.url==="/graphql"&&(e&&e.mediaType.previews?.length&&(i.mediaType.previews=e.mediaType.previews.filter(n=>!i.mediaType.previews.includes(n)).concat(i.mediaType.previews)),i.mediaType.previews=(i.mediaType.previews||[]).map(n=>n.replace(/-preview/,""))),i}function N2S(e,t){let r=/\?/.test(e)?"&":"?",i=Object.keys(t);return i.length===0?e:e+r+i.map(n=>n==="q"?"q="+t.q.split("+").map(encodeURIComponent).join("+"):`${n}=${encodeURIComponent(t[n])}`).join("&")}var F2S=/\{[^{}}]+\}/g;function Q2S(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function U2S(e){let t=e.match(F2S);return t?t.map(Q2S).reduce((r,i)=>r.concat(i),[]):[]}function Tp_(e,t){let r={__proto__:null};for(let i of Object.keys(e))t.indexOf(i)===-1&&(r[i]=e[i]);return r}function zp_(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map(function(t){return/%[0-9A-Fa-f]/.test(t)||(t=encodeURI(t).replace(/%5B/g,"[").replace(/%5D/g,"]")),t}).join("")}function RQn(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}function WPa(e,t,r){return t=e==="+"||e==="#"?zp_(t):RQn(t),r?RQn(r)+"="+t:t}function TQn(e){return e!=null}function fsc(e){return e===";"||e==="&"||e==="?"}function L2S(e,t,r,i){var n=e[r],a=[];if(TQn(n)&&n!=="")if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")n=n.toString(),i&&i!=="*"&&(n=n.substring(0,parseInt(i,10))),a.push(WPa(t,n,fsc(t)?r:""));else if(i==="*")Array.isArray(n)?n.filter(TQn).forEach(function(o){a.push(WPa(t,o,fsc(t)?r:""))}):Object.keys(n).forEach(function(o){TQn(n[o])&&a.push(WPa(t,n[o],o))});else{let o=[];Array.isArray(n)?n.filter(TQn).forEach(function(c){o.push(WPa(t,c))}):Object.keys(n).forEach(function(c){TQn(n[c])&&(o.push(RQn(c)),o.push(WPa(t,n[c].toString())))}),fsc(t)?a.push(RQn(r)+"="+o.join(",")):o.length!==0&&a.push(o.join(","))}else t===";"?TQn(n)&&a.push(RQn(r)):n===""&&(t==="&"||t==="?")?a.push(RQn(r)+"="):n===""&&a.push("");return a}function V2S(e){return{expand:W2S.bind(null,e)}}function W2S(e,t){var r=["+","#",".","/",";","?","&"];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(i,n,a){if(n){let c="",f=[];if(r.indexOf(n.charAt(0))!==-1&&(c=n.charAt(0),n=n.substr(1)),n.split(/,/g).forEach(function(s){var u=/([^:\*]*)(?::(\d+)|(\*))?/.exec(s);f.push(L2S(t,c,u[1],u[2]||u[3]))}),c&&c!=="+"){var o=",";return c==="?"?o="&":c!=="#"&&(o=c),(f.length!==0?c:"")+f.join(o)}else return f.join(",")}else return zp_(a)}),e==="/"?e:e.replace(/\/$/,"")}function Np_(e){let t=e.method.toUpperCase(),r=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),i=Object.assign({},e.headers),n,a=Tp_(e,["method","baseUrl","url","headers","request","mediaType"]),o=U2S(r);r=V2S(r).expand(a),/^http/.test(r)||(r=e.baseUrl+r);let c=Object.keys(e).filter(u=>o.includes(u)).concat("baseUrl"),f=Tp_(a,c);if(!/application\/octet-stream/i.test(i.accept)&&(e.mediaType.format&&(i.accept=i.accept.split(/,/).map(u=>u.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`)).join(",")),r.endsWith("/graphql")&&e.mediaType.previews?.length)){let u=i.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g)||[];i.accept=u.concat(e.mediaType.previews).map(l=>{let p=e.mediaType.format?`.${e.mediaType.format}`:"+json";return`application/vnd.github.${l}-preview${p}`}).join(",")}return["GET","HEAD"].includes(t)?r=N2S(r,f):"data"in f?n=f.data:Object.keys(f).length&&(n=f),!i["content-type"]&&typeof n<"u"&&(i["content-type"]="application/json; charset=utf-8"),["PATCH","PUT"].includes(t)&&typeof n>"u"&&(n=""),Object.assign({method:t,url:r,headers:i},typeof n<"u"?{body:n}:null,e.request?{request:e.request}:null)}function x2S(e,t,r){return Np_(dsc(e,t,r))}function Fp_(e,t){let r=dsc(e,t),i=x2S.bind(null,r);return Object.assign(i,{DEFAULTS:r,defaults:Fp_.bind(null,r),merge:dsc.bind(null,r),parse:Np_})}var Qp_=Fp_(null,T2S);var Gp_=ce(Wp_(),1);var bFt=class extends Error{name;status;request;response;constructor(t,r,i){super(t),this.name="HttpError",this.status=Number.parseInt(r),Number.isNaN(this.status)&&(this.status=0),"response"in i&&(this.response=i.response);let n=Object.assign({},i.request);i.request.headers.authorization&&(n.headers=Object.assign({},i.request.headers,{authorization:i.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),n.url=n.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=n}};var G2S="10.0.6",H2S={headers:{"user-agent":`octokit-request.js/${G2S} ${TR()}`}};function K2S(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}async function xp_(e){let t=e.request?.fetch||globalThis.fetch;if(!t)throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");let r=e.request?.log||console,i=e.request?.parseSuccessResponseBody!==!1,n=K2S(e.body)||Array.isArray(e.body)?JSON.stringify(e.body):e.body,a=Object.fromEntries(Object.entries(e.headers).map(([l,p])=>[l,String(p)])),o;try{o=await t(e.url,{method:e.method,body:n,redirect:e.request?.redirect,headers:a,signal:e.request?.signal,...e.body&&{duplex:"half"}})}catch(l){let p="Unknown Error";if(l instanceof Error){if(l.name==="AbortError")throw l.status=500,l;p=l.message,l.name==="TypeError"&&"cause"in l&&(l.cause instanceof Error?p=l.cause.message:typeof l.cause=="string"&&(p=l.cause))}let _=new bFt(p,500,{request:e});throw _.cause=l,_}let c=o.status,f=o.url,s={};for(let[l,p]of o.headers)s[l]=p;let u={url:f,status:c,headers:s,data:""};if("deprecation"in s){let l=s.link&&s.link.match(/<([^<>]+)>; rel="deprecation"/),p=l&&l.pop();r.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${s.sunset}${p?`. See ${p}`:""}`)}if(c===204||c===205)return u;if(e.method==="HEAD"){if(c<400)return u;throw new bFt(o.statusText,c,{response:u,request:e})}if(c===304)throw u.data=await psc(o),new bFt("Not modified",c,{response:u,request:e});if(c>=400)throw u.data=await psc(o),new bFt($2S(u.data),c,{response:u,request:e});return u.data=i?await psc(o):o.body,u}async function psc(e){let t=e.headers.get("content-type");if(!t)return e.text().catch(()=>"");let r=(0,Gp_.safeParse)(t);if(J2S(r)){let i="";try{return i=await e.text(),JSON.parse(i)}catch{return i}}else return r.type.startsWith("text/")||r.parameters.charset?.toLowerCase()==="utf-8"?e.text().catch(()=>""):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function J2S(e){return e.type==="application/json"||e.type==="application/scim+json"}function $2S(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return"Unknown error";if("message"in e){let t="documentation_url"in e?` - ${e.documentation_url}`:"";return Array.isArray(e.errors)?`${e.message}: ${e.errors.map(r=>JSON.stringify(r)).join(", ")}${t}`:`${e.message}${t}`}return`Unknown error: ${JSON.stringify(e)}`}function _sc(e,t){let r=e.defaults(t);return Object.assign(function(n,a){let o=r.merge(n,a);if(!o.request||!o.request.hook)return xp_(r.parse(o));let c=(f,s)=>xp_(r.parse(r.merge(f,s)));return Object.assign(c,{endpoint:r,defaults:_sc.bind(null,r)}),o.request.hook(c,o)},{endpoint:r,defaults:_sc.bind(null,r)})}var VO=_sc(Qp_,H2S);var Y2S="0.0.0-development";function X2S(e){return`Request failed due to following response errors:
@@ -1783,7 +1783,7 @@ A valid API configuration was not found at the path: fern/apis/${t.apiName}.
1783
1783
  Learn more about project structure:
1784
1784
  https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`:`Failed to load API Definition referenced in docs.
1785
1785
  Learn more about project structure:
1786
- https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`;throw new Error(r)}async toRootNode(){let t=Ct.V1.SlugGenerator.init(Ct.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Ct.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return Kxi(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Ct.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??Rw(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,o=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:o}}async toVersionedNode(t,r){let i=this.#e.get("versioned"),n=t.versions[0];if(n?.hidden===!0)throw new Error(`The default version "${n.version}" cannot be hidden. Please set a non-hidden version as the first version in your versions list, or remove the hidden flag from the default version.`);return{id:i,type:"versioned",children:await Promise.all(t.versions.map((a,o)=>this.toVersionNode(a,r,o===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(o=>this.toProductNode(o,i)))}}async toProductNode(t,r){if(t.type==="internal"){let i=r.setProductSlug(t.slug??Rw(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:Ot(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Ct.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}else return{type:"productLink",id:this.#e.get(t.product),productId:Ct.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",href:NW.Url(t.href??""),target:t.target,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,viewers:t.viewers,orphaned:t.orphaned}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??Rw(t.version)),o=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Ct.VersionId(t.version),title:t.version,slug:a.get(),child:o,default:i,availability:t.availability!=null?UFM(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(c=>this.toNavigationChild({prefix:n,item:c,parentSlug:i}))),o=[];return a.forEach(c=>{if(c.type==="apiReference"){o.push(c);return}if(c.type==="section"&&!c.collapsed){o.push(c);return}let f=o.length>0?o[o.length-1]:void 0,s;f?.type==="sidebarGroup"?s=f:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},o.push(s)),s.children.push(c)}),{type:"sidebarRoot",id:n,children:o}}async toSidebarRootNodeWithVariants(t,r,i){let n=this.#e.get(`${t}/root`);return{type:"sidebarRoot",id:n,children:[{type:"varianted",id:n,children:await Promise.all(r.map(a=>this.toVariantNode(a,n,i)))}]}}async toVariantNode(t,r,i){let n=this.#e.get(`${r}/variant/${t.slug??Rw(t.title)}`),a=i.apply({urlSlug:t.slug??Rw(t.title),skipUrlSlug:t.skipUrlSlug}),o=await Promise.all(t.layout.map(c=>this.toVariantChild(c,n,a)));return{type:"variant",id:n,variantId:Ct.V1.VariantId(t.title),subtitle:t.subtitle??"",default:t.default??!1,image:void 0,children:o,title:t.title,slug:a.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,pointsTo:void 0}}async toVariantChild(t,r,i){return Kxi(t)._visit({page:async n=>this.toPageNode({item:n,parentSlug:i}),apiSection:async n=>this.toApiSectionNode({item:n,parentSlug:i}),section:async n=>this.toSectionNode({prefix:r,item:n,parentSlug:i}),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i)})}async toNavigationChild({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){return Kxi(r)._visit({page:async o=>this.toPageNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),apiSection:async o=>this.toApiSectionNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),section:async o=>this.toSectionNode({prefix:t,item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),link:async o=>this.toLinkNode(o),changelog:async o=>this.toChangelogNode(o,i,n)})}async toApiSectionNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=sN_(t.snippetsConfiguration),o,c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),f=this.parsedDocsConfig.experimental?.openapiParserV3,s=f==null||f;if(s)try{o=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1})}catch{}let u;if(t.tagDescriptionPages&&s)try{let b=await this.getOpenApiWorkspaceForApiSection(t).getOpenAPIIr({context:this.taskContext});b.tags.tagsById&&(u=Object.fromEntries(Object.entries(b.tags.tagsById).filter(([v,O])=>O.description&&O.description.trim().length>0).map(([v,O])=>[v,{id:String(O.id),description:O.description}])))}catch(y){this.taskContext.logger.warn("Failed to extract OpenAPI tags for tag description pages",String(y))}o==null&&(o=kw({workspace:c,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new Zw(this.taskContext,c)})),this.docsWorkspace.config.settings?.substituteEnvVars&&(o=dR(o,{onError:y=>this.taskContext.failAndThrow(`Error substituting environment variables in API spec: ${y}`)},{substituteAsEmpty:!1}));let l=await this.registerApi({ir:o,snippetsConfig:a,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName,workspace:c}),p=eSa({ir:o,apiDefinitionId:l,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext}),_=new F9o(t,p,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,this.collectedFileIds,c,i,n??t.availability,u),h=_.getTagDescriptionContent();for(let[y,b]of h.entries()){let v=y.split("/").pop()||y,O=Ye.of(v),A=b;this.docsWorkspace.config.settings?.substituteEnvVars&&(A=dR(b,{onError:g=>this.taskContext.logger.error(`Error in tag description environment variable substitution: ${g}`)},{substituteAsEmpty:!1})),this.rawMarkdownFiles[O]=A,this.parsedDocsConfig.pages[O]=A}return _.get()}async toChangelogNode(t,r,i){return new W$i(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Ct.V1.Url(t.url),icon:this.resolveIconFileId(t.icon),target:t.target}}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Ct.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??Rw(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Ct.PageId(o):void 0,f=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??Rw(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,l=n||r.hidden;return{id:f,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:l,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(p=>this.toNavigationChild({prefix:f,item:p,parentSlug:s,hideChildren:l,parentAvailability:r.availability??a}))),authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return Kxi(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new W$i(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Ct.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??Rw(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??Rw(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):NW.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(ts),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:NW.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return Kxi(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:NW.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function QFM(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${F1(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function UFM(e){switch(e){case"beta":return Ct.V1.NavigationV1Availability.Beta;case"deprecated":return Ct.V1.NavigationV1Availability.Deprecated;case"ga":return Ct.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Ct.V1.NavigationV1Availability.Stable;default:Ot(e)}}async function sU(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof Xw?t:null))).filter(ts)}async function fgc(e,t,r){if(e instanceof Q9t){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof Xw))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});return zx({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var Qs={};Yt(Qs,{AlgoliaSearchIndex:()=>MN_,ApiDefinitionId:()=>$N_,ApiId:()=>kN_,Availability:()=>_F_,DocsConfigId:()=>eF_,EndpointId:()=>rF_,EndpointPathLiteral:()=>dF_,EnvironmentId:()=>tF_,FileId:()=>uF_,HttpMethod:()=>pF_,IndexSegmentId:()=>DN_,JqString:()=>cF_,OrgId:()=>XN_,PageId:()=>oF_,PayloadLocation:()=>LF_,PropertyKey:()=>lF_,PullRequestState:()=>zF_,RoleId:()=>fF_,TokenId:()=>ZN_,TypeId:()=>aF_,Url:()=>sF_,VersionId:()=>YN_,WebSocketId:()=>iF_,WebhookId:()=>nF_,algolia:()=>dgc,api:()=>mgc,commons:()=>Pgc,diff:()=>hF_,docs:()=>Cgc,generators:()=>Tgc,git:()=>Rgc,navigation:()=>Fgc,sdks:()=>Ugc,snippets:()=>QF_,snippetsFactory:()=>UF_,templates:()=>Lgc,tokens:()=>VF_});var dgc={};Yt(dgc,{AlgoliaSearchIndex:()=>MN_,IndexSegmentId:()=>DN_});function MN_(e){return e}function DN_(e){return e}var mgc={};Yt(mgc,{latest:()=>hgc,v1:()=>Agc});var hgc={};Yt(hgc,{AuthSchemeId:()=>BN_,WebhookHttpMethod:()=>TN_,auth:()=>pgc,commons:()=>IN_,endpoint:()=>CN_,type_:()=>qN_,webhook:()=>_gc,websocket:()=>RN_});var pgc={};Yt(pgc,{AuthSchemeId:()=>BN_});function BN_(e){return e}var IN_={};var CN_={};var qN_={};var _gc={};Yt(_gc,{WebhookHttpMethod:()=>TN_});var TN_={Get:"GET",Post:"POST"};var RN_={};var Agc={};Yt(Agc,{SubpackageId:()=>GN_,WebSocketMessageId:()=>HN_,WebSocketMessageOrigin:()=>KN_,WebhookHttpMethod:()=>JN_,commons:()=>Ogc,db:()=>ygc,read:()=>vgc,register:()=>ggc});var ygc={};Yt(ygc,{endpoint:()=>zN_});var zN_={};var vgc={};Yt(vgc,{SupportedLanguage:()=>NN_,endpoint:()=>bgc,type_:()=>FN_,webhook:()=>QN_,websocket:()=>UN_});var bgc={};Yt(bgc,{SupportedLanguage:()=>NN_});var NN_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var FN_={};var QN_={};var UN_={};var ggc={};Yt(ggc,{SourceId:()=>LFM,endpoint:()=>LN_,type_:()=>VN_,webhook:()=>WN_,websocket:()=>xN_});var LN_={};var VN_={};var WN_={};var xN_={};function LFM(e){return e}var Ogc={};Yt(Ogc,{SubpackageId:()=>GN_,WebSocketMessageId:()=>HN_,WebSocketMessageOrigin:()=>KN_,WebhookHttpMethod:()=>JN_});function GN_(e){return e}function HN_(e){return e}var KN_={Client:"client",Server:"server"};var JN_={Get:"GET",Post:"POST"};var Pgc={};Yt(Pgc,{ApiDefinitionId:()=>$N_,ApiId:()=>kN_,Availability:()=>_F_,DocsConfigId:()=>eF_,EndpointId:()=>rF_,EndpointPathLiteral:()=>dF_,EnvironmentId:()=>tF_,FileId:()=>uF_,HttpMethod:()=>pF_,JqString:()=>cF_,OrgId:()=>XN_,PageId:()=>oF_,PropertyKey:()=>lF_,RoleId:()=>fF_,TokenId:()=>ZN_,TypeId:()=>aF_,Url:()=>sF_,VersionId:()=>YN_,WebSocketId:()=>iF_,WebhookId:()=>nF_});function $N_(e){return e}function YN_(e){return e}function XN_(e){return e}function ZN_(e){return e}function kN_(e){return e}function eF_(e){return e}function tF_(e){return e}function rF_(e){return e}function iF_(e){return e}function nF_(e){return e}function aF_(e){return e}function oF_(e){return e}function uF_(e){return e}function sF_(e){return e}function cF_(e){return e}function lF_(e){return e}function fF_(e){return e}function dF_(e){return e}var pF_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var _F_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var hF_={};var Cgc={};Yt(Cgc,{latest:()=>Egc,v1:()=>Bgc,v2:()=>Igc});var Egc={};Yt(Egc,{Layout:()=>bF_,MdxEngine:()=>VFM,TwitterCardSetting:()=>vF_,commons:()=>yF_,frontmatter:()=>jgc,seo:()=>wgc});var VFM={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var yF_={};var jgc={};Yt(jgc,{Layout:()=>bF_});var bF_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var wgc={};Yt(wgc,{TwitterCardSetting:()=>vF_});var vF_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Bgc={};Yt(Bgc,{commons:()=>Dgc,db:()=>gF_,read:()=>OF_,write:()=>Sgc});var gF_={};var OF_={};var Sgc={};Yt(Sgc,{DocsRegistrationId:()=>xFM,FilePath:()=>WFM});function WFM(e){return e}function xFM(e){return e}var Dgc={};Yt(Dgc,{ContentAlignment:()=>jF_,FontDisplay:()=>DF_,FontStyle:()=>MF_,HeaderPosition:()=>wF_,JsScriptStrategy:()=>SF_,ProgrammingLanguage:()=>AF_,SearchbarPlacement:()=>mF_,TabsPlacement:()=>PF_,TwitterCardSetting:()=>EF_,commons:()=>Mgc});var Mgc={};Yt(Mgc,{ContentAlignment:()=>jF_,FontDisplay:()=>DF_,FontStyle:()=>MF_,HeaderPosition:()=>wF_,JsScriptStrategy:()=>SF_,ProgrammingLanguage:()=>AF_,SearchbarPlacement:()=>mF_,TabsPlacement:()=>PF_,TwitterCardSetting:()=>EF_});var AF_={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var mF_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var PF_={Header:"HEADER",Sidebar:"SIDEBAR"};var jF_={Center:"CENTER",Left:"LEFT"};var wF_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var EF_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var SF_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var MF_={Normal:"normal",Italic:"italic"};var DF_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Igc={};Yt(Igc,{read:()=>BF_,write:()=>IF_});var BF_={};var IF_={};var Tgc={};Yt(Tgc,{ChangelogEntryType:()=>qF_,GeneratorId:()=>GFM,GeneratorLanguage:()=>HFM,ReleaseType:()=>TF_,cli:()=>CF_,commons:()=>qgc,versions:()=>RF_});var CF_={};var qgc={};Yt(qgc,{ChangelogEntryType:()=>qF_,ReleaseType:()=>TF_});var qF_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var TF_={Ga:"GA",Rc:"RC"};var RF_={};function GFM(e){return e}var HFM={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Rgc={};Yt(Rgc,{PullRequestState:()=>zF_});var zF_={Open:"open",Closed:"closed",Merged:"merged"};var Fgc={};Yt(Fgc,{latest:()=>zgc,v1:()=>Ngc});var zgc={};Yt(zgc,{NodeId:()=>$FM,ProductId:()=>YFM,Slug:()=>KFM,TabId:()=>JFM});function KFM(e){return e}function JFM(e){return e}function $FM(e){return e}function YFM(e){return e}var Ngc={};Yt(Ngc,{NavigationV1Availability:()=>tQM,NodeId:()=>kFM,ProductId:()=>eQM,Slug:()=>XFM,TabId:()=>ZFM});function XFM(e){return e}function ZFM(e){return e}function kFM(e){return e}function eQM(e){return e}var tQM={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var Ugc={};Yt(Ugc,{Language:()=>NF_,VersionBump:()=>FF_,versions:()=>Qgc});var Qgc={};Yt(Qgc,{Language:()=>NF_,VersionBump:()=>FF_});var NF_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var FF_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var QF_={};var UF_={};var Lgc={};Yt(Lgc,{PayloadLocation:()=>LF_});var LF_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var VF_={};var K9o=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function mo(e){return e!=null}var xF_=ce(_da(),1);var WF_=["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 Z9t(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,xF_.default)(e,{special:WF_}).replace(/V\s(\d)/g,"V$1")}function GF_({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let o=[...n,a],c=Qs.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:Z9t(a)},n.push(a)})}),r}var J9o=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function HF_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var $a=class extends J9o{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((o,c)=>o===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${HF_(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},LB=class extends $a{},OK=class extends LB{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var KF_="x-fern-base-path",JF_="x-fern-availability",$9o="x-fern-sdk-group-name",$F_="x-fern-global-headers",YF_="x-fern-sdk-method-name";var XF_="x-fern-webhook",ZF_="x-fern-access-token-locator",kF_="x-fern-basic",eQ_="x-fern-username-variable-name",tQ_="x-fern-password-variable-name",rQ_="x-fern-bearer",iQ_="x-fern-token-variable-name",nQ_="x-fern-header",aQ_="x-fern-header-variable-name",oQ_="x-fern-server-name",uQ_="x-fern-examples";var Y9o=class extends $a{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[oQ_]}convert(){if(this.serverName!=null)return this.serverName}};var X9o=class extends $a{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new Y9o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:Qs.EnvironmentId(t),baseUrl:this.url}}};function h1i(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),o=(t??[]).filter(c=>!a.has(c.url)).map((c,f)=>new X9o({input:c,context:r,accessPath:i,pathId:["servers",`${f}`]}));return[...n,...o]}function sv(e){return typeof e=="object"&&mo(e)&&"$ref"in e&&typeof e.$ref=="string"}function cU(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(sv(n)&&(n=cU(n,t,r)),n)}function Z9o(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return sv(r)?cU(r,t,void 0):r}var EQ_=ce(zE());var k9o=class extends $a{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[kF_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var eGo=class extends $a{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[tQ_]}convert(){return this.passwordVariableName}};var tGo=class extends $a{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[eQ_]}convert(){return this.usernameVariableName}};var rGo=class extends $a{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[rQ_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var iGo=class extends $a{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[iQ_]}convert(){return this.tokenVariableName}};function sQ_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var cQ_="x-bearer-format",lQ_="x-code-samples",fQ_="x-codeSamples";var nGo=class extends $a{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[cQ_]}convert(){return this.bearerFormat}};var aGo=class extends $a{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[nQ_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var oGo=class extends $a{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[aQ_]}convert(){return this.headerVariableName}};function dQ_(e){return e.type==="apiKey"}var VLn=class extends $a{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){dQ_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new aGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new oGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new nGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function uGo(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function WLn(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function tSa(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(tSa).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function sGo(e){if(Array.isArray(e))return e.map(WLn);if(typeof e=="symbol")return[e];e=tSa(e);let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",o=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:o?c==='"'||c==="'"?a=c:c==="]"?(o=!1,t.push(n),n=""):n+=c:c==="["?(o=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function rSa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(hso(t))return r;let i=e[t];return i===void 0?uGo(t)?rSa(e,sGo(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=WLn(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return rQM(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),hso(t))return r;let i=e[t];return i===void 0?r:i}}}function rQM(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||hso(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function pQ_(e){return function(t){return rSa(t,e)}}function _Q_(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function Vgc(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function xgc(e,t,r){return typeof r!="function"?xgc(e,t,()=>{}):Wgc(e,t,function i(n,a,o,c,f,s){let u=r(n,a,o,c,f,s);return u!==void 0?!!u:Wgc(n,a,i,s)},new Map)}function Wgc(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return iQM(e,t,r,i);case"function":return Object.keys(t).length>0?Wgc(e,{...t},r,i):Vgc(e,t);default:return _Q_(e)?typeof t=="string"?t==="":!0:Vgc(e,t)}}function iQM(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return hQ_(e,t,r,i);if(t instanceof Map)return nQM(e,t,r,i);if(t instanceof Set)return aQM(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i?.has(t))return i.get(t)===e;i?.set(t,e);try{for(let a=0;a<n.length;a++){let o=n[a];if(!cso(e)&&!(o in e)||t[o]===void 0&&e[o]!==void 0||t[o]===null&&e[o]!==null||!r(e[o],t[o],o,e,t,i))return!1}return!0}finally{i?.delete(t)}}function nQM(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let o=e.get(n);if(r(o,a,n,e,t,i)===!1)return!1}return!0}function hQ_(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let o=t[a],c=!1;for(let f=0;f<e.length;f++){if(n.has(f))continue;let s=e[f],u=!1;if(r(s,o,a,e,t,i)&&(u=!0),u){n.add(f),c=!0;break}}if(!c)return!1}return!0}function aQM(e,t,r,i){return t.size===0?!0:e instanceof Set?hQ_([...e],[...t],r,i):!1}function cGo(e,t){return xgc(e,t,()=>{})}function yQ_(e){return e=IUd(e),t=>cGo(t,e)}function bQ_(e,t){return BUd(e,(r,i,n,a)=>{let o=t?.(r,i,n,a);if(o!==void 0)return o;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case dso:case fso:case pso:{let c=new e.constructor(e?.valueOf());return bzt(c,e),c}case _so:{let c={};return bzt(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function vQ_(e){return bQ_(e)}var oQM=/^(?:0|[1-9]\d*)$/;function gQ_(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return oQM.test(e)}}function OQ_(e){return e!==null&&typeof e=="object"&&lso(e)==="[object Arguments]"}function AQ_(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&uGo(t)&&e?.[t]==null?r=sGo(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||OQ_(i))&&gQ_(a)&&a<i.length))return!1;i=i[a]}return!0}function mQ_(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=WLn(e);break}}return t=vQ_(t),function(r){let i=rSa(r,e);return i===void 0?AQ_(r,e):t===void 0?i===void 0:cGo(i,t)}}function PQ_(e){if(e==null)return nco;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?mQ_(e[0],e[1]):yQ_(e);case"string":case"symbol":case"number":return pQ_(e)}}function lGo(e,t=nco){return e==null?{}:iQ(e,PQ_(t))}function jQ_(e){return typeof e!="string"&&(e=tSa(e)),e.replace(/['\u2019]/g,"")}function HFt(e){return qUd(jQ_(e))}function km(e){if(e!=null)return Array.isArray(e)?e:[e]}function fGo({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:o}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${uQM(o)}${sQM(e)}.${cQM(i,n,a,c)}`}function uQM(e){return e?"webhook_":"endpoint_"}function sQM(e){return e!=null?km(e)?.map(t=>HFt(t)).join("/"):""}function cQM(e,t,r,i){return e||t||HFt(r??"")||HFt(i??"")}function wQ_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var dGo=class extends $a{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[ZF_],this.accessTokenLocator!=null&&(wQ_(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var pGo=class extends $a{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new VLn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new dGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=fGo({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Qs.EndpointId(r),accessTokenLocator:Qs.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var xLn=class extends $a{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new k9o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new tGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new eGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new rGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new iGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{sQ_(this.input)?(this.authScheme="header",this.headerAuthNode=new VLn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new pGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new EQ_.UnreachableCaseError(this.authScheme);return}}};var GLn=class extends $a{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=Z9o(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new xLn({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(mo))}};var _Go=class extends $a{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[KF_],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function SQ_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function MQ_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function HLn(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>km(n.convert())?.map(o=>((t!=null&&!t.includes(i)||t==null&&!SQ_(n))&&(o=MQ_(o,o.type==="enum"?o.default:void 0)),{key:Qs.PropertyKey(i),valueShape:o,description:n.description,availability:n.availability?.convert()})).filter(mo)).filter(mo).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]])}function hGo(e,t){return sv(e)?cU(e,t,void 0):e}function y1i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function DQ_(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function BQ_(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var IQ_=ce(zE());var Ggc=["decimal","decimal128","double-int","double","float","sf-decimal"],Hgc=["int16","int32","int64","int8","sf-integer","uint8"],Kgc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],Jgc=["beta","pre-release","in-development","generally-available","deprecated"];function VB(e,t){return sv(e)?cU(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var EPe=class extends $a{availability;constructor(t){super(t),this.safeParse()}parse(){if(VB(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[JF_];r!=null&&(Jgc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${Jgc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return Qs.Availability.Beta;case"in-development":return Qs.Availability.InDevelopment;case"generally-available":return Qs.Availability.GenerallyAvailable;case"deprecated":return Qs.Availability.Deprecated;case void 0:return;default:new IQ_.UnreachableCaseError(this.availability);return}}};var bGo=ce(zE());function CQ_(e){return typeof e=="object"&&e!=null&&"language"in e}function qQ_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function TQ_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function RQ_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function yGo(e){return typeof e=="object"&&e!=null&&"event"in e}function $gc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(yGo)}function b1i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function zQ_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var vGo=class extends $a{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[uQ_]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let o=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return b1i(o)?[n,{type:"filenameWithData",filename:o.filename,data:Qs.FileId(o.data)}]:o!=null?[n,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>b1i(c)))return[n,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:Qs.FileId(c.data)}))}];if(o.every(c=>typeof c=="string"))return[n,{type:"filenames",value:o}]}return}case"property":return[n,{type:"json",value:o}];case void 0:return;default:new bGo.UnreachableCaseError(a.multipartType);return}}).filter(mo))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=zQ_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new bGo.UnreachableCaseError(n.contentType);break}let o;switch(i.contentType){case"application/json":{TQ_(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{$gc(r.response)&&(o={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!$gc(r.response)&&RQ_(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new bGo.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(l=>{CQ_(l)?l.language!=null&&(c[l.language]??=[],c[l.language]?.push({name:l.name,language:l.language,install:l.install,code:l.code,generated:!1,description:l.docs})):qQ_(l)&&l.sdk!=null&&(c[l.sdk]??=[],c[l.sdk]?.push({name:l.name,language:l.sdk,install:void 0,code:l.code,generated:!1,description:l.docs}))});let f=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([l,p])=>[Qs.PropertyKey(l),p])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,p])=>[Qs.PropertyKey(l),p])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([l,p])=>[Qs.PropertyKey(l),p]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(f).length>0?f:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(u).length>0?u:void 0,requestBody:a,responseBody:o,snippets:c}}))}};var iSa=class extends $a{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[$9o]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>Qs.api.v1.SubpackageId(HFt(r)))}};var gGo=class extends $a{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[YF_]}convert(){return this.sdkMethodName}};var OGo=class extends $a{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[XF_]}convert(){return this.isWebhook}};var AGo=class extends $a{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[lQ_]??[],...this.input[fQ_]??[]],this.codeSamples.forEach(t=>{[...Object.values(Qs.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var x$i=ce(zE());function Ygc(e,t){return sv(e)?cU(e,t,void 0):e}function NQ_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var Dz="",k9t=class extends $a{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(b1i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>b1i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new x$i.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=Ygc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=Ygc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new x$i.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(yGo)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new x$i.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return b1i(n)?[r,{type:"filenameWithData",filename:n.filename,data:Qs.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>b1i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:Qs.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new x$i.UnreachableCaseError(i.multipartType);return}}).filter(mo))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new x$i.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new x$i.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([o,c])=>[o,c.example({includeOptionals:!1,override:o})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(mo));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(mo));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:NQ_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?Z9t(this.name):this.summary!=null?Z9t(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function FQ_(e,t){return sv(e)?cU(e,t,void 0):e}var XQ_=ce(zE());var QQ_="#/components/schemas/";function KLn(e){if(e.$ref.startsWith(QQ_))return e.$ref.replace(QQ_,"")}function Wgi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function v1i(e){return typeof e.type=="string"&&e.type==="array"}function UQ_(e){return e.type==="boolean"}function LQ_(e){return e.type==="integer"}function g1i(e){return!Array.isArray(e.type)&&!v1i(e)}function VQ_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||g1i(t)||v1i(t))}function WQ_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function xQ_(e){return e.type==="null"}function GQ_(e){return e.type==="number"}function Xgc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function HQ_(e){return e.type==="string"}var mGo=class extends OK{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new YP({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return km(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var PGo=class extends LB{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new EPe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var jGo=class extends OK{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new YP({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(mo)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>km(n.convert())?.map(o=>({displayName:n.name,shape:o,description:n.description,availability:n.availability?.convert()}))).filter(mo).reduce((n,a)=>n.flatMap(o=>a.length>0?a.map(c=>[...o,c]):[[...o]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(Wgi).filter(mo):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function wGo(e){return e!=null&&e.length>0?e:[void 0]}var JLn=class extends OK{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new YP({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new YP({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(sv(t))return KLn(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new YP({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(mo))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return HLn(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:km(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(mo)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>wGo(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>Qs.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=VB(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,o])=>[a,new YP({input:o,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var EGo=class extends OK{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>VB(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>VB(t,this.context.document)?.type!=="null"?new YP({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(mo);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=VB({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new YP({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(mo);return this.isNullable&&n!=null?n.map(Wgi).filter(mo):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:Qs.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>km(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??Z9t(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(mo)).filter(mo)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>km(n.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?Z9t(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(o.type==="alias"&&o.value.type==="id"?Z9t(o.value.id):c),shape:o,description:n.description,availability:n.availability?.convert()}}).filter(mo)).filter(mo)}:void 0,i=this.isNullable?Wgi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var SGo=class extends LB{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var O1i=class extends LB{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(sv(r)){let n=VB(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(mo),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var KQ_=ce(zE());function lQM(e){return Hgc.includes(e)}var MGo=class extends LB{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(lQM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Hgc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new KQ_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var DGo=class extends LB{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return Wgi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var JQ_=ce(zE());function fQM(e){return Ggc.includes(e)}var BGo=class extends LB{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(fQM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Ggc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new JQ_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var $Q_=ce(zE());function dQM(e){return Kgc.includes(e)}var IGo=class extends LB{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new $Q_.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(dQM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Kgc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new O1i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var YQ_=ce(zE());var CGo=class extends LB{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,YQ_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var G$i=class extends OK{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=KLn(this.input);let t=VB(this.input,this.context.document);t?.enum!=null&&g1i(t)&&(this.maybeEnumConverterNode=new O1i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:Qs.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=VB(this.input,this.context.document);if(r!=null)return new YP({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var YP=class e extends OK{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new EPe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),g1i(this.input)&&WQ_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),sv(this.input)){let t=KLn(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new G$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new PGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(VQ_(this.input))this.typeShapeNode=new jGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(g1i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new EGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Xgc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new JLn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(g1i(this.input)&&this.input.enum!=null)this.typeShapeNode=new O1i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":Xgc(this.input)&&(this.typeShapeNode=new JLn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":v1i(this.input)&&(this.typeShapeNode=new mGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":UQ_(this.input)&&(this.typeShapeNode=new SGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":LQ_(this.input)&&(this.typeShapeNode=new MGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":GQ_(this.input)&&(this.typeShapeNode=new BGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":HQ_(this.input)&&(this.typeShapeNode=new IGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":xQ_(this.input)&&(this.typeShapeNode=new DGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new XQ_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new JLn({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new CGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!sv(this.input)&&(!v1i(this.input)&&this.input==null||v1i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=km(t)?.map(i=>this.nullable?Wgi(i):i).filter(mo);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function A1i(e){if(e!=null)return HLn(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(mo))}var eGt=class extends LB{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;sv(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new EPe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new YP({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=FQ_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function ZQ_(e,t){return sv(e)?cU(e,t,void 0):e}var Zgc=ce(zE());function qGo(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[Qs.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var kQ_=ce(kjs(),1),$Ln=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,o){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=o}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=kQ_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function pQM(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var TGo=class extends $a{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new YP({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),pQM(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(sv(r)?n=Z9o(r.$ref,this.context.document):n=r,n!=null)return[t,new xLn({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(mo)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[Qs.api.latest.AuthSchemeId(t),i]}).filter(mo)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=km(r.convert());return n==null?[t,void 0]:[Qs.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>mo(r))):void 0}}};var RGo=class extends YP{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=VB(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${sv(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=VB(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var zGo=class extends $a{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=VB(this.input.schema,this.context.document);this.availability=new EPe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=sv(this.input.schema)?new G$i({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=$Ln.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new YP({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,o])=>{if(o!=null)return[a,new RGo({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(mo))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[Dz]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[Dz]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:km(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=HFt([this.method,this.path,this.contentType,"request"].join("_"));return qGo({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Qs.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new Zgc.UnreachableCaseError(n);return}}).filter(mo)}convert(){if(this.schema instanceof G$i)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:Qs.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:Qs.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=km(n.convert()),o=n.multipartType;return a?.map(c=>({type:o,key:Qs.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new Zgc.UnreachableCaseError(n.multipartType),[]}}).filter(mo).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var NGo=class extends $a{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=ZQ_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new zGo({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>km(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(mo)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>km(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(mo)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var eU_={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function tU_(e,t){if(sv(e)){let r=cU(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var FGo=ce(zE());var rU_="application/json";var iU_="application/octet-stream";function nU_(e,t){return e===t||t===Dz||e===Dz}var nSa=class extends $a{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,o,c,f){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=o,this.requests=c,this.shapes=f,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,o]of Object.entries(n?.examples??{}))for(let[c,f]of Object.entries(r))for(let s of f)nU_(c,a)&&(i.add(c),this.examples?.push(new k9t({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,y1i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[o,c]of r){if(a===i){let[f,s,u]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(l=>new k9t({input:{requestExample:u,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,y1i(s,o),{requestBody:f,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,o]=r[r.length-1]??[void 0,void 0],[c,f,s]=n??[void 0,void 0,void 0];this.examples?.push(...(o??[void 0]).map(u=>new k9t({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:f!=null&&f!==""?["examples",f]:"examples"},this.path,this.statusCode,y1i(f,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,o]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,f]of r.slice(t.length))this.examples?.push(...f.map(s=>new k9t({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,y1i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[Dz];if(a!=null)for(let o of a)this.examples?.push(new k9t({input:{requestExample:n,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,y1i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=$Ln.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=rU_,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new YP({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=iU_,this.contentSubtype=VB(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new YP({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=lGo(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[Dz]??=[],r[Dz]=[{value:this.input.example}]);let i=VB(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=lGo(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[Dz]??=[],r[Dz]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[Dz]??=[],r[Dz]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([f])=>!n.has(f)&&f!==Dz).map(([f,s])=>[c,f,s]));let o=Object.entries(r).filter(([c,f])=>!n.has(c)&&mo(f)&&c!==Dz);Object.keys(r).every(c=>c===Dz)||this.matchExamplesByIndex(a,o),!n.has(Dz)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return km(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new FGo.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return km(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=HFt([this.method,this.path,this.statusCode,"response"].join("_"));return qGo({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Qs.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new FGo.UnreachableCaseError(i);return}}).filter(mo)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new FGo.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var aSa=class extends $a{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,o){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=o,this.safeParse()}parse(t){this.description=this.input.description;let r=tU_(this.input,this.context.document);if(r==null){this.context.errors.error({message:sv(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new eGt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new nSa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new nSa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(mo)}};var QGo=class extends $a{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new aSa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new aSa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return wGo(A1i(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(o=>(o.examples??[]).map(c=>c.convert()).filter(mo))})))}).filter(mo)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=km(n?.convert());if(n!=null)return a?.map(o=>({statusCode:parseInt(t),shape:o,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??eU_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let f=c.convert();if(f!=null&&f.responseBody?.type==="json")return{name:f.name,description:f.description,responseBody:f.responseBody}}).filter(mo)})).filter(mo)})).filter(mo)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var m1i=class extends $a{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new k9t({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,y1i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new EPe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=h1i(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new OGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(sv(i)){let a=hGo(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new eGt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new eGt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new eGt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new AGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new NGo({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new QGo({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,o])=>{this.pushEmptyResponseExample(o,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new GLn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new iSa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new iSa({input:{[$9o]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new gGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>fGo({namespace:km(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(mo),this.xFernExamplesNode=new vGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(mo)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:Qs.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(u=>u.convert()).filter(mo),n=BQ_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:DQ_(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:Qs.WebhookId(u),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[l]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(p=>p.value.toString())??[],queryParameters:A1i(this.queryParameters)?.flat(),headers:A1i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(mo)}}).filter(mo);let a=this.servers?.map(u=>u.convert()).filter(mo),o=this.convertPathToPathParts();if(o==null)return;let c,f=this.auth?.convert();f!=null&&(c=Object.keys(f));let s=t?.flatMap(u=>u.headers).filter(mo);return this.endpointIds.map((u,l)=>({id:Qs.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(p=>Qs.api.v1.SubpackageId(p)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(p=>Qs.api.latest.AuthSchemeId(p)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:A1i(this.pathParameters)?.flat(),queryParameters:A1i(this.queryParameters)?.flat(),requestHeaders:A1i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(p=>p.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var YLn=class extends $a{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=h1i(t,this.input.servers,this.context,this.accessPath),o=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new m1i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:o,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new m1i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:o,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new m1i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:o,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new m1i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:o,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new m1i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:o,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(mo)}};function UGo(e){return"payloads"in e}var LGo=class extends $a{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new YLn({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:h1i(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(mo)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{UGo(a)?r[Qs.WebhookId(a.id)]=a:t[Qs.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var VGo=class extends $a{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[$F_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||hGo(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new eGt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return HLn(this.globalHeaders,this.requiredProperties)?.flat()}};function aU_(e,t){if(sv(e)){let r=cU(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var WGo=class extends $a{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let o=aU_(a,this.context.document);if(o!=null)return new YLn({input:o,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(mo)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{UGo(i)&&(t[Qs.WebhookId(i.id)]=i)}),t),{})}};var xGo=class extends $a{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=h1i(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new GLn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new _Go({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new LGo({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new WGo({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new TGo({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new VGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=the(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=GF_({endpoints:i,webhookEndpoints:n}),{types:o,auths:c}=this.components?.convert()??{};return{id:Qs.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...o,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};async function kgc(e,t){if(e instanceof Q9t){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof Xw))return;let r=new zFt(e.absoluteFilePath),i=await bPe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let o of n){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new K9o,generatedTypes:{}},f=new xGo({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=hws(a,f.convert())}return a}var PG_=ce(rOc(),1),jG_=ce(C7o(),1),rKo=require("fs/promises"),wG_=ce(require("http"),1),EG_=ce(require("path"),1);var cV_=require("events"),N7o=ce(require("fs"),1),tYi=ce(require("path"),1);var G8_=ce(require("os"),1),H8_=300,D1i=20,MSa=1e7,K8_=G8_.default.platform();var R5M=K8_==="darwin",mAc=K8_==="win32",B1i=R5M||mAc,J8_=3e3,$8_=2e4,PAc=1250;var nGt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(nGt||(nGt={}));var eYi;(function(e){e.CHANGE="change",e.RENAME="rename"})(eYi||(eYi={}));var DSa;(function(e){e.CHANGE="change",e.ERROR="error"})(DSa||(DSa={}));var Il;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Il||(Il={}));var Qx;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(Qx||(Qx={}));var z5M=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,f=0,s=0,u=()=>{let g=Date.now(),m=g-f,j=g-s,S=m>=t||j>=a;return[g,S]},l=g=>{if(s=g,!o)return;let m=o;o=void 0,e.apply(void 0,m)},p=()=>{O(0)},_=()=>{c&&(p(),l(Date.now()))},h=g=>{if(s=g,i)return l(g)},y=g=>{if(n&&o)return l(g);o=void 0},b=()=>{c=void 0;let[g,m]=u();return m?y(g):v(g)},v=g=>{let m=g-f,j=g-s,S=t-m,E=a-j,D=Math.min(S,E);return O(D)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},A=(...g)=>{let[m,j]=u(),S=!!c;if(o=g,f=m,(j||!c)&&O(t),j)return S?l(m):h(m)};return A.cancel=p,A.flush=_,A},q7o=z5M;var SAc=ce(require("fs"),1),R7o=ce(require("path"),1);var bO=ce(require("fs"),1),lU=require("util");var Ggi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},aGt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var jAc=ce(require("process"),1),Y8_=jAc.default.getuid?!jAc.default.getuid():!1,X8_=1e4,jK=()=>{};var BSa={isChangeErrorOk:e=>{if(!BSa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!Y8_&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!BSa.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!BSa.isNodeError(e))throw e;if(!BSa.isChangeErrorOk(e))throw e}},WB=BSa;var wAc=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=X8_,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},Z8_=new wAc;var Hgi=(e,t)=>function(i){return function n(...a){return Z8_.schedule().then(o=>{let c=s=>(o(),s),f=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,f)})}},Kgi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var N5M={attempt:{chmod:Ggi((0,lU.promisify)(bO.default.chmod),WB.onChangeError),chown:Ggi((0,lU.promisify)(bO.default.chown),WB.onChangeError),close:Ggi((0,lU.promisify)(bO.default.close),jK),fsync:Ggi((0,lU.promisify)(bO.default.fsync),jK),mkdir:Ggi((0,lU.promisify)(bO.default.mkdir),jK),realpath:Ggi((0,lU.promisify)(bO.default.realpath),jK),stat:Ggi((0,lU.promisify)(bO.default.stat),jK),unlink:Ggi((0,lU.promisify)(bO.default.unlink),jK),chmodSync:aGt(bO.default.chmodSync,WB.onChangeError),chownSync:aGt(bO.default.chownSync,WB.onChangeError),closeSync:aGt(bO.default.closeSync,jK),existsSync:aGt(bO.default.existsSync,jK),fsyncSync:aGt(bO.default.fsync,jK),mkdirSync:aGt(bO.default.mkdirSync,jK),realpathSync:aGt(bO.default.realpathSync,jK),statSync:aGt(bO.default.statSync,jK),unlinkSync:aGt(bO.default.unlinkSync,jK)},retry:{close:Hgi((0,lU.promisify)(bO.default.close),WB.isRetriableError),fsync:Hgi((0,lU.promisify)(bO.default.fsync),WB.isRetriableError),open:Hgi((0,lU.promisify)(bO.default.open),WB.isRetriableError),readFile:Hgi((0,lU.promisify)(bO.default.readFile),WB.isRetriableError),rename:Hgi((0,lU.promisify)(bO.default.rename),WB.isRetriableError),stat:Hgi((0,lU.promisify)(bO.default.stat),WB.isRetriableError),write:Hgi((0,lU.promisify)(bO.default.write),WB.isRetriableError),writeFile:Hgi((0,lU.promisify)(bO.default.writeFile),WB.isRetriableError),closeSync:Kgi(bO.default.closeSync,WB.isRetriableError),fsyncSync:Kgi(bO.default.fsyncSync,WB.isRetriableError),openSync:Kgi(bO.default.openSync,WB.isRetriableError),readFileSync:Kgi(bO.default.readFileSync,WB.isRetriableError),renameSync:Kgi(bO.default.renameSync,WB.isRetriableError),statSync:Kgi(bO.default.statSync,WB.isRetriableError),writeSync:Kgi(bO.default.writeSync,WB.isRetriableError),writeFileSync:Kgi(bO.default.writeFileSync,WB.isRetriableError)}},k8_=N5M;var T7o=ce(require("fs"),1),ISa=ce(require("path"),1);var EAc=()=>{};var F5M=()=>{let e=EAc,t=EAc,r=!1,i=!1;return{promise:new Promise((f,s)=>{e=u=>(r=!0,f(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},eV_=F5M;var Q5M=()=>{let{promise:e,resolve:t,isPending:r}=eV_(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},tV_=Q5M;var rV_={then:e=>{e()}};var iV_=e=>Array.isArray(e)?e:[e],nV_=e=>typeof e=="function";var U5M=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=iV_(a).map(V=>nV_(V)?V:U=>V.test(U)),c=V=>o.some(U=>U(V)),f=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],l=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,O={},A={},g=new Set,m={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:l,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:A},{promise:S,increment:E,decrement:D}=tV_(),B=0,F=(V,U,Se,ue)=>{g.has(U)||B>=n||(B+=1,V.directories.push(U),V.directoriesNames.add(Se),u.push(U),l.add(Se),p.propertyIsEnumerable(Se)||(p[Se]=[]),p[Se].push(U),g.add(U),!(ue>=i)&&(B>=n||J(U,ue+1)))},N=(V,U,Se)=>{g.has(U)||B>=n||(B+=1,V.files.push(U),V.filesNames.add(Se),_.push(U),h.add(Se),y.propertyIsEnumerable(Se)||(y[Se]=[]),y[Se].push(U),g.add(U))},R=(V,U,Se,ue)=>{g.has(U)||B>=n||(B+=1,V.symlinks.push(U),V.symlinksNames.add(Se),b.push(U),v.add(Se),O.propertyIsEnumerable(Se)||(O[Se]=[]),O[Se].push(U),g.add(U),r&&(ue>=i||B>=n||fe(U,ue+1)))},z=(V,U,Se,ue,we)=>{f.aborted||c(U)||(ue.isDirectory()?F(V,U,Se,we):ue.isFile()?N(V,U,Se):ue.isSymbolicLink()&&R(V,U,Se,we))},L=(V,U,Se,ue)=>{if(f.aborted)return;let we=U===ISa.default.sep?"":ISa.default.sep,Le=Se.name,se=`${U}${we}${Le}`;c(se)||(Se.isDirectory()?F(V,se,Le,ue):Se.isFile()?N(V,se,Le):Se.isSymbolicLink()&&R(V,se,Le,ue))},H=(V,U,Se,ue)=>{for(let we=0,Le=Se.length;we<Le;we++)L(V,U,Se[we],ue)},J=(V,U)=>{f.aborted||U>i||B>=n||(E(),T7o.default.readdir(V,{withFileTypes:!0},(Se,ue)=>{if(Se||f.aborted||!ue.length)return D();(s(ue)||rV_).then(()=>{let Le=A[V]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};H(Le,V,ue,U),D()})}))},fe=(V,U)=>{E(),T7o.default.realpath(V,(Se,ue)=>{if(Se||f.aborted)return D();T7o.default.stat(ue,(we,Le)=>{if(we||f.aborted)return D();let se=ISa.default.basename(ue),ne=A[V]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(ne,ue,se,Le,U),D()})})};return(async(V,U=1)=>(V=ISa.default.normalize(V),g.add(V),J(V,U),await S,f.aborted?m:j))(e)},aV_=U5M;var oGt={lang:{debounce:q7o,attempt:e=>{try{return e()}catch(t){return oGt.lang.castError(t)}},castArray:e=>oGt.lang.isArray(e)?e:[e],castError:e=>oGt.lang.isError(e)?e:oGt.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(oGt.lang.isNaN(e))return oGt.lang.isNaN(t);if(oGt.lang.isPrimitive(e)||oGt.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(R7o.default.sep).length-1),getRealPath:(e,t)=>{try{return t?SAc.default.realpathSync.native(e):SAc.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===R7o.default.sep&&t.length-e.length>R7o.default.sep.length,poll:(e,t=$8_)=>k8_.retry.stat(t)(e,{bigint:!0}).catch(oGt.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await aV_(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},cp=oGt;var z7o=ce(require("path"),1);var MAc=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||cp.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=H8_){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,f)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...f]),l=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(l)},o=cp.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,f="",s=!1)=>{s?await this.eventsPopulate([f],i,!0):n.add(f),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===Il.CHANGE&&c===Il.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===Il.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Il.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??D1i:Math.min(1,this.options.depth??D1i),o=this.options.limit??MSa,[c,f]=await cp.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...f];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())cp.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Il.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!B1i&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Il.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Il.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(z7o.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Il.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(z7o.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Il.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Il.ADD?this.onTargetAdd(i):r===Il.ADD_DIR?this.onTargetAddDir(i):r===Il.CHANGE?this.onTargetChange(i):r===Il.UNLINK?this.onTargetUnlink(i):r===Il.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=eYi.CHANGE,r){if(this.watcher.isClosed())return;let i=z7o.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){mAc&&t.code==="EPERM"?this.onWatcherChange(eYi.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(DSa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(DSa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(eYi.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&B1i&&this.options.native!==!1?this.options.depth??D1i:Math.min(1,this.options.depth??D1i),i=this.options.limit??MSa,[n,a]=await cp.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(eYi.CHANGE,c,t)}))}}},oV_=MAc;var Ux={interval:100,intervalId:void 0,fns:new Map,init:()=>{Ux.intervalId||(Ux.intervalId=setInterval(Ux.resolve,Ux.interval))},reset:()=>{Ux.intervalId&&(clearInterval(Ux.intervalId),delete Ux.intervalId)},add:(e,t)=>{Ux.fns.set(e,Date.now()+t),Ux.init()},remove:e=>{Ux.fns.delete(e)},resolve:()=>{if(!Ux.fns.size)return Ux.reset();let e=Date.now();for(let[t,r]of Ux.fns)r>=e||(Ux.remove(t),t())}},CSa=Ux;var qSa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=PAc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let l=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(l&&l!==n){if(cp.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return c();let f=()=>{o.add.delete(i),CSa.remove(s)},s=()=>{f(),c()};CSa.add(s,r);let u=()=>{let l=o.unlink.get(i);if(!l)return;f();let p=l();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=PAc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let f=()=>{o.unlink.delete(i),CSa.remove(s)},s=()=>{f(),c()};CSa.add(s,r);let u=()=>(f(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,Il.ADD,nGt.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,Il.ADD_DIR,nGt.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,Il.UNLINK,nGt.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,Il.UNLINK_DIR,nGt.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};qSa.DIR_EVENTS={add:Il.ADD_DIR,rename:Il.RENAME_DIR,unlink:Il.UNLINK_DIR};qSa.FILE_EVENTS={add:Il.ADD,change:Il.CHANGE,rename:Il.RENAME,unlink:Il.UNLINK};var uV_=qSa;var DAc=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(cp.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(cp.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(cp.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(cp.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return cp.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);cp.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},BAc=DAc;var IAc=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},sV_=IAc;var CAc=class{constructor(){this.inos={},this.paths=new BAc,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await cp.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new sV_(i)}reset(){this.inos={},this.paths=new BAc,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,Il.ADD,n),[Il.ADD];if(n.isDirectory())return this.updateIno(t,Il.ADD_DIR,n),[Il.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Il.UNLINK,i),[Il.UNLINK];if(i.isDirectory())return this.updateIno(t,Il.UNLINK_DIR,i),[Il.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Il.CHANGE,n),[Il.CHANGE]);if(n.isDirectory())return this.updateIno(t,Il.UNLINK,i),this.updateIno(t,Il.ADD_DIR,n),[Il.UNLINK,Il.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Il.UNLINK_DIR,i),this.updateIno(t,Il.ADD,n),[Il.UNLINK_DIR,Il.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Il.UNLINK_DIR,i),this.updateIno(t,Il.ADD_DIR,n),[Il.UNLINK_DIR,Il.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?nGt.FILE:nGt.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},qAc=CAc;var TAc=class e extends cV_.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(Qx.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(Qx.CLOSE,n)),this._readyWait=new Promise(n=>this.on(Qx.READY,n)),this._locker=new uV_(this),this._roots=new Set,this._poller=new qAc,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(cp.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(Qx.CLOSE))}error(t){if(this.isClosed())return!1;let r=cp.lang.castError(t);return this.emit(Qx.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(Qx.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(Qx.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&cp.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&cp.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)cp.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new oV_(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=cp.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=tYi.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??D1i))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&B1i&&u.options.native!==!1)))return!0;if(!B1i)break;let s=tYi.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=cp.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let f=!r.recursive||B1i&&r.native!==!1?r:{...r,recursive:!1},u={watcher:N7o.default.watch(c,f),handler:i,options:r,folderPath:c,filePath:n},l=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=tYi.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,l)}}catch(f){this.error(f)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||B1i&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??D1i,c=r.limit??MSa,[f]=await cp.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(f.length){let u=cp.fs.getDepth(t);for(let l of f){let p=cp.fs.getDepth(l),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([l],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(f(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(Qx.CLOSE,f),o.watchFile(t,r,a)},f=()=>{this._subwatchers.delete(n),this.removeListener(Qx.CLOSE,f),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=tYi.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new qAc,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return cp.lang.noop;if(this.pollerExists(t,r))return cp.lang.noop;let n={...r,interval:r.pollingInterval??J8_},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(Qx.CLOSE,c),N7o.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(Qx.CLOSE,c),N7o.default.unwatchFile(t,i)};return cp.lang.attempt(o),()=>cp.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=cp.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,f)=>f===o||!cp.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=tYi.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await cp.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=tYi.default.dirname(t);return(await cp.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=cp.lang.noop){if(cp.lang.isFunction(t))return this.watch([],{},t);if(cp.lang.isUndefined(t))return this.watch([],r,i);if(cp.lang.isFunction(r))return this.watch(t,{},r);if(cp.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=cp.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==cp.lang.noop&&this.on(Qx.ALL,i),r.readdirMap=void 0,this.ready())}},F7o=TAc;TMo();var d3n=require("fs/promises"),lV_=require("os"),fV_=ce(require("path"),1),L5M=".fern",V5M="logs";function W5M(){return"cli@3.26.1"}var TSa=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Bt(Br.of((0,lV_.homedir)()),Ye.of(L5M)),r=Bt(t,Ye.of(V5M));await ji(r)||await(0,d3n.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Bt(r,Ye.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${fV_.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
1786
+ https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`;throw new Error(r)}async toRootNode(){let t=Ct.V1.SlugGenerator.init(Ct.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Ct.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return Kxi(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Ct.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??Rw(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,o=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:o}}async toVersionedNode(t,r){let i=this.#e.get("versioned"),n=t.versions[0];if(n?.hidden===!0)throw new Error(`The default version "${n.version}" cannot be hidden. Please set a non-hidden version as the first version in your versions list, or remove the hidden flag from the default version.`);return{id:i,type:"versioned",children:await Promise.all(t.versions.map((a,o)=>this.toVersionNode(a,r,o===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(o=>this.toProductNode(o,i)))}}async toProductNode(t,r){if(t.type==="internal"){let i=r.setProductSlug(t.slug??Rw(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:Ot(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Ct.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}else return{type:"productLink",id:this.#e.get(t.product),productId:Ct.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",href:NW.Url(t.href??""),target:t.target,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,viewers:t.viewers,orphaned:t.orphaned}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??Rw(t.version)),o=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Ct.VersionId(t.version),title:t.version,slug:a.get(),child:o,default:i,availability:t.availability!=null?UFM(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(c=>this.toNavigationChild({prefix:n,item:c,parentSlug:i}))),o=[];return a.forEach(c=>{if(c.type==="apiReference"){o.push(c);return}if(c.type==="section"&&!c.collapsed){o.push(c);return}let f=o.length>0?o[o.length-1]:void 0,s;f?.type==="sidebarGroup"?s=f:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},o.push(s)),s.children.push(c)}),{type:"sidebarRoot",id:n,children:o}}async toSidebarRootNodeWithVariants(t,r,i){let n=this.#e.get(`${t}/root`);return{type:"sidebarRoot",id:n,children:[{type:"varianted",id:n,children:await Promise.all(r.map(a=>this.toVariantNode(a,n,i)))}]}}async toVariantNode(t,r,i){let n=this.#e.get(`${r}/variant/${t.slug??Rw(t.title)}`),a=i.apply({urlSlug:t.slug??Rw(t.title),skipUrlSlug:t.skipUrlSlug}),o=await Promise.all(t.layout.map(c=>this.toVariantChild(c,n,a)));return{type:"variant",id:n,variantId:Ct.V1.VariantId(t.title),subtitle:t.subtitle??"",default:t.default??!1,image:void 0,children:o,title:t.title,slug:a.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,pointsTo:void 0}}async toVariantChild(t,r,i){return Kxi(t)._visit({page:async n=>this.toPageNode({item:n,parentSlug:i}),apiSection:async n=>this.toApiSectionNode({item:n,parentSlug:i}),section:async n=>this.toSectionNode({prefix:r,item:n,parentSlug:i}),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i)})}async toNavigationChild({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){return Kxi(r)._visit({page:async o=>this.toPageNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),apiSection:async o=>this.toApiSectionNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),section:async o=>this.toSectionNode({prefix:t,item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),link:async o=>this.toLinkNode(o),changelog:async o=>this.toChangelogNode(o,i,n)})}async toApiSectionNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=sN_(t.snippetsConfiguration),o,c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),f=this.parsedDocsConfig.experimental?.openapiParserV3,s=f==null||f;if(s)try{o=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1})}catch{}let u;if(t.tagDescriptionPages&&s)try{let b=await this.getOpenApiWorkspaceForApiSection(t).getOpenAPIIr({context:this.taskContext});b.tags.tagsById&&(u=Object.fromEntries(Object.entries(b.tags.tagsById).filter(([v,O])=>O.description&&O.description.trim().length>0).map(([v,O])=>[v,{id:String(O.id),description:O.description}])))}catch(y){this.taskContext.logger.warn("Failed to extract OpenAPI tags for tag description pages",String(y))}o==null&&(o=kw({workspace:c,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new Zw(this.taskContext,c)})),this.docsWorkspace.config.settings?.substituteEnvVars&&(o=dR(o,{onError:y=>this.taskContext.failAndThrow(`Error substituting environment variables in API spec: ${y}`)},{substituteAsEmpty:!1}));let l=await this.registerApi({ir:o,snippetsConfig:a,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName,workspace:c}),p=eSa({ir:o,apiDefinitionId:l,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext}),_=new F9o(t,p,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,this.collectedFileIds,c,i,n??t.availability,u),h=_.getTagDescriptionContent();for(let[y,b]of h.entries()){let v=y.split("/").pop()||y,O=Ye.of(v),A=b;this.docsWorkspace.config.settings?.substituteEnvVars&&(A=dR(b,{onError:g=>this.taskContext.logger.error(`Error in tag description environment variable substitution: ${g}`)},{substituteAsEmpty:!1})),this.rawMarkdownFiles[O]=A,this.parsedDocsConfig.pages[O]=A}return _.get()}async toChangelogNode(t,r,i){return new W$i(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Ct.V1.Url(t.url),icon:this.resolveIconFileId(t.icon),target:t.target}}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Ct.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??Rw(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Ct.PageId(o):void 0,f=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??Rw(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,l=n||r.hidden;return{id:f,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:l,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(p=>this.toNavigationChild({prefix:f,item:p,parentSlug:s,hideChildren:l,parentAvailability:r.availability??a}))),authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return Kxi(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new W$i(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Ct.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??Rw(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??Rw(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):NW.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(ts),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:NW.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return Kxi(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:NW.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function QFM(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${F1(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function UFM(e){switch(e){case"beta":return Ct.V1.NavigationV1Availability.Beta;case"deprecated":return Ct.V1.NavigationV1Availability.Deprecated;case"ga":return Ct.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Ct.V1.NavigationV1Availability.Stable;default:Ot(e)}}async function sU(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof Xw?t:null))).filter(ts)}async function fgc(e,t,r){if(e instanceof Q9t){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof Xw))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});return zx({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var Qs={};Yt(Qs,{AlgoliaSearchIndex:()=>MN_,ApiDefinitionId:()=>$N_,ApiId:()=>kN_,Availability:()=>_F_,DocsConfigId:()=>eF_,EndpointId:()=>rF_,EndpointPathLiteral:()=>dF_,EnvironmentId:()=>tF_,FileId:()=>uF_,HttpMethod:()=>pF_,IndexSegmentId:()=>DN_,JqString:()=>cF_,OrgId:()=>XN_,PageId:()=>oF_,PayloadLocation:()=>LF_,PropertyKey:()=>lF_,PullRequestState:()=>zF_,RoleId:()=>fF_,TokenId:()=>ZN_,TypeId:()=>aF_,Url:()=>sF_,VersionId:()=>YN_,WebSocketId:()=>iF_,WebhookId:()=>nF_,algolia:()=>dgc,api:()=>mgc,commons:()=>Pgc,diff:()=>hF_,docs:()=>Cgc,generators:()=>Tgc,git:()=>Rgc,navigation:()=>Fgc,sdks:()=>Ugc,snippets:()=>QF_,snippetsFactory:()=>UF_,templates:()=>Lgc,tokens:()=>VF_});var dgc={};Yt(dgc,{AlgoliaSearchIndex:()=>MN_,IndexSegmentId:()=>DN_});function MN_(e){return e}function DN_(e){return e}var mgc={};Yt(mgc,{latest:()=>hgc,v1:()=>Agc});var hgc={};Yt(hgc,{AuthSchemeId:()=>BN_,WebhookHttpMethod:()=>TN_,auth:()=>pgc,commons:()=>IN_,endpoint:()=>CN_,type_:()=>qN_,webhook:()=>_gc,websocket:()=>RN_});var pgc={};Yt(pgc,{AuthSchemeId:()=>BN_});function BN_(e){return e}var IN_={};var CN_={};var qN_={};var _gc={};Yt(_gc,{WebhookHttpMethod:()=>TN_});var TN_={Get:"GET",Post:"POST"};var RN_={};var Agc={};Yt(Agc,{SubpackageId:()=>GN_,WebSocketMessageId:()=>HN_,WebSocketMessageOrigin:()=>KN_,WebhookHttpMethod:()=>JN_,commons:()=>Ogc,db:()=>ygc,read:()=>vgc,register:()=>ggc});var ygc={};Yt(ygc,{endpoint:()=>zN_});var zN_={};var vgc={};Yt(vgc,{SupportedLanguage:()=>NN_,endpoint:()=>bgc,type_:()=>FN_,webhook:()=>QN_,websocket:()=>UN_});var bgc={};Yt(bgc,{SupportedLanguage:()=>NN_});var NN_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var FN_={};var QN_={};var UN_={};var ggc={};Yt(ggc,{SourceId:()=>LFM,endpoint:()=>LN_,type_:()=>VN_,webhook:()=>WN_,websocket:()=>xN_});var LN_={};var VN_={};var WN_={};var xN_={};function LFM(e){return e}var Ogc={};Yt(Ogc,{SubpackageId:()=>GN_,WebSocketMessageId:()=>HN_,WebSocketMessageOrigin:()=>KN_,WebhookHttpMethod:()=>JN_});function GN_(e){return e}function HN_(e){return e}var KN_={Client:"client",Server:"server"};var JN_={Get:"GET",Post:"POST"};var Pgc={};Yt(Pgc,{ApiDefinitionId:()=>$N_,ApiId:()=>kN_,Availability:()=>_F_,DocsConfigId:()=>eF_,EndpointId:()=>rF_,EndpointPathLiteral:()=>dF_,EnvironmentId:()=>tF_,FileId:()=>uF_,HttpMethod:()=>pF_,JqString:()=>cF_,OrgId:()=>XN_,PageId:()=>oF_,PropertyKey:()=>lF_,RoleId:()=>fF_,TokenId:()=>ZN_,TypeId:()=>aF_,Url:()=>sF_,VersionId:()=>YN_,WebSocketId:()=>iF_,WebhookId:()=>nF_});function $N_(e){return e}function YN_(e){return e}function XN_(e){return e}function ZN_(e){return e}function kN_(e){return e}function eF_(e){return e}function tF_(e){return e}function rF_(e){return e}function iF_(e){return e}function nF_(e){return e}function aF_(e){return e}function oF_(e){return e}function uF_(e){return e}function sF_(e){return e}function cF_(e){return e}function lF_(e){return e}function fF_(e){return e}function dF_(e){return e}var pF_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var _F_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var hF_={};var Cgc={};Yt(Cgc,{latest:()=>Egc,v1:()=>Bgc,v2:()=>Igc});var Egc={};Yt(Egc,{Layout:()=>bF_,MdxEngine:()=>VFM,TwitterCardSetting:()=>vF_,commons:()=>yF_,frontmatter:()=>jgc,seo:()=>wgc});var VFM={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var yF_={};var jgc={};Yt(jgc,{Layout:()=>bF_});var bF_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var wgc={};Yt(wgc,{TwitterCardSetting:()=>vF_});var vF_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Bgc={};Yt(Bgc,{commons:()=>Dgc,db:()=>gF_,read:()=>OF_,write:()=>Sgc});var gF_={};var OF_={};var Sgc={};Yt(Sgc,{DocsRegistrationId:()=>xFM,FilePath:()=>WFM});function WFM(e){return e}function xFM(e){return e}var Dgc={};Yt(Dgc,{ContentAlignment:()=>jF_,FontDisplay:()=>DF_,FontStyle:()=>MF_,HeaderPosition:()=>wF_,JsScriptStrategy:()=>SF_,ProgrammingLanguage:()=>AF_,SearchbarPlacement:()=>mF_,TabsPlacement:()=>PF_,TwitterCardSetting:()=>EF_,commons:()=>Mgc});var Mgc={};Yt(Mgc,{ContentAlignment:()=>jF_,FontDisplay:()=>DF_,FontStyle:()=>MF_,HeaderPosition:()=>wF_,JsScriptStrategy:()=>SF_,ProgrammingLanguage:()=>AF_,SearchbarPlacement:()=>mF_,TabsPlacement:()=>PF_,TwitterCardSetting:()=>EF_});var AF_={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var mF_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var PF_={Header:"HEADER",Sidebar:"SIDEBAR"};var jF_={Center:"CENTER",Left:"LEFT"};var wF_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var EF_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var SF_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var MF_={Normal:"normal",Italic:"italic"};var DF_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Igc={};Yt(Igc,{read:()=>BF_,write:()=>IF_});var BF_={};var IF_={};var Tgc={};Yt(Tgc,{ChangelogEntryType:()=>qF_,GeneratorId:()=>GFM,GeneratorLanguage:()=>HFM,ReleaseType:()=>TF_,cli:()=>CF_,commons:()=>qgc,versions:()=>RF_});var CF_={};var qgc={};Yt(qgc,{ChangelogEntryType:()=>qF_,ReleaseType:()=>TF_});var qF_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var TF_={Ga:"GA",Rc:"RC"};var RF_={};function GFM(e){return e}var HFM={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Rgc={};Yt(Rgc,{PullRequestState:()=>zF_});var zF_={Open:"open",Closed:"closed",Merged:"merged"};var Fgc={};Yt(Fgc,{latest:()=>zgc,v1:()=>Ngc});var zgc={};Yt(zgc,{NodeId:()=>$FM,ProductId:()=>YFM,Slug:()=>KFM,TabId:()=>JFM});function KFM(e){return e}function JFM(e){return e}function $FM(e){return e}function YFM(e){return e}var Ngc={};Yt(Ngc,{NavigationV1Availability:()=>tQM,NodeId:()=>kFM,ProductId:()=>eQM,Slug:()=>XFM,TabId:()=>ZFM});function XFM(e){return e}function ZFM(e){return e}function kFM(e){return e}function eQM(e){return e}var tQM={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var Ugc={};Yt(Ugc,{Language:()=>NF_,VersionBump:()=>FF_,versions:()=>Qgc});var Qgc={};Yt(Qgc,{Language:()=>NF_,VersionBump:()=>FF_});var NF_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var FF_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var QF_={};var UF_={};var Lgc={};Yt(Lgc,{PayloadLocation:()=>LF_});var LF_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var VF_={};var K9o=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function mo(e){return e!=null}var xF_=ce(_da(),1);var WF_=["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 Z9t(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,xF_.default)(e,{special:WF_}).replace(/V\s(\d)/g,"V$1")}function GF_({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let o=[...n,a],c=Qs.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:Z9t(a)},n.push(a)})}),r}var J9o=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function HF_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var $a=class extends J9o{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((o,c)=>o===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${HF_(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},LB=class extends $a{},OK=class extends LB{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var KF_="x-fern-base-path",JF_="x-fern-availability",$9o="x-fern-sdk-group-name",$F_="x-fern-global-headers",YF_="x-fern-sdk-method-name";var XF_="x-fern-webhook",ZF_="x-fern-access-token-locator",kF_="x-fern-basic",eQ_="x-fern-username-variable-name",tQ_="x-fern-password-variable-name",rQ_="x-fern-bearer",iQ_="x-fern-token-variable-name",nQ_="x-fern-header",aQ_="x-fern-header-variable-name",oQ_="x-fern-server-name",uQ_="x-fern-examples";var Y9o=class extends $a{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[oQ_]}convert(){if(this.serverName!=null)return this.serverName}};var X9o=class extends $a{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new Y9o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:Qs.EnvironmentId(t),baseUrl:this.url}}};function h1i(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),o=(t??[]).filter(c=>!a.has(c.url)).map((c,f)=>new X9o({input:c,context:r,accessPath:i,pathId:["servers",`${f}`]}));return[...n,...o]}function sv(e){return typeof e=="object"&&mo(e)&&"$ref"in e&&typeof e.$ref=="string"}function cU(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(sv(n)&&(n=cU(n,t,r)),n)}function Z9o(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return sv(r)?cU(r,t,void 0):r}var EQ_=ce(zE());var k9o=class extends $a{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[kF_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var eGo=class extends $a{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[tQ_]}convert(){return this.passwordVariableName}};var tGo=class extends $a{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[eQ_]}convert(){return this.usernameVariableName}};var rGo=class extends $a{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[rQ_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var iGo=class extends $a{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[iQ_]}convert(){return this.tokenVariableName}};function sQ_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var cQ_="x-bearer-format",lQ_="x-code-samples",fQ_="x-codeSamples";var nGo=class extends $a{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[cQ_]}convert(){return this.bearerFormat}};var aGo=class extends $a{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[nQ_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var oGo=class extends $a{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[aQ_]}convert(){return this.headerVariableName}};function dQ_(e){return e.type==="apiKey"}var VLn=class extends $a{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){dQ_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new aGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new oGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new nGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function uGo(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function WLn(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function tSa(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(tSa).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function sGo(e){if(Array.isArray(e))return e.map(WLn);if(typeof e=="symbol")return[e];e=tSa(e);let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",o=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:o?c==='"'||c==="'"?a=c:c==="]"?(o=!1,t.push(n),n=""):n+=c:c==="["?(o=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function rSa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(hso(t))return r;let i=e[t];return i===void 0?uGo(t)?rSa(e,sGo(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=WLn(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return rQM(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),hso(t))return r;let i=e[t];return i===void 0?r:i}}}function rQM(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||hso(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function pQ_(e){return function(t){return rSa(t,e)}}function _Q_(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function Vgc(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function xgc(e,t,r){return typeof r!="function"?xgc(e,t,()=>{}):Wgc(e,t,function i(n,a,o,c,f,s){let u=r(n,a,o,c,f,s);return u!==void 0?!!u:Wgc(n,a,i,s)},new Map)}function Wgc(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return iQM(e,t,r,i);case"function":return Object.keys(t).length>0?Wgc(e,{...t},r,i):Vgc(e,t);default:return _Q_(e)?typeof t=="string"?t==="":!0:Vgc(e,t)}}function iQM(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return hQ_(e,t,r,i);if(t instanceof Map)return nQM(e,t,r,i);if(t instanceof Set)return aQM(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i?.has(t))return i.get(t)===e;i?.set(t,e);try{for(let a=0;a<n.length;a++){let o=n[a];if(!cso(e)&&!(o in e)||t[o]===void 0&&e[o]!==void 0||t[o]===null&&e[o]!==null||!r(e[o],t[o],o,e,t,i))return!1}return!0}finally{i?.delete(t)}}function nQM(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let o=e.get(n);if(r(o,a,n,e,t,i)===!1)return!1}return!0}function hQ_(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let o=t[a],c=!1;for(let f=0;f<e.length;f++){if(n.has(f))continue;let s=e[f],u=!1;if(r(s,o,a,e,t,i)&&(u=!0),u){n.add(f),c=!0;break}}if(!c)return!1}return!0}function aQM(e,t,r,i){return t.size===0?!0:e instanceof Set?hQ_([...e],[...t],r,i):!1}function cGo(e,t){return xgc(e,t,()=>{})}function yQ_(e){return e=IUd(e),t=>cGo(t,e)}function bQ_(e,t){return BUd(e,(r,i,n,a)=>{let o=t?.(r,i,n,a);if(o!==void 0)return o;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case dso:case fso:case pso:{let c=new e.constructor(e?.valueOf());return bzt(c,e),c}case _so:{let c={};return bzt(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function vQ_(e){return bQ_(e)}var oQM=/^(?:0|[1-9]\d*)$/;function gQ_(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return oQM.test(e)}}function OQ_(e){return e!==null&&typeof e=="object"&&lso(e)==="[object Arguments]"}function AQ_(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&uGo(t)&&e?.[t]==null?r=sGo(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||OQ_(i))&&gQ_(a)&&a<i.length))return!1;i=i[a]}return!0}function mQ_(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=WLn(e);break}}return t=vQ_(t),function(r){let i=rSa(r,e);return i===void 0?AQ_(r,e):t===void 0?i===void 0:cGo(i,t)}}function PQ_(e){if(e==null)return nco;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?mQ_(e[0],e[1]):yQ_(e);case"string":case"symbol":case"number":return pQ_(e)}}function lGo(e,t=nco){return e==null?{}:iQ(e,PQ_(t))}function jQ_(e){return typeof e!="string"&&(e=tSa(e)),e.replace(/['\u2019]/g,"")}function HFt(e){return qUd(jQ_(e))}function km(e){if(e!=null)return Array.isArray(e)?e:[e]}function fGo({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:o}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${uQM(o)}${sQM(e)}.${cQM(i,n,a,c)}`}function uQM(e){return e?"webhook_":"endpoint_"}function sQM(e){return e!=null?km(e)?.map(t=>HFt(t)).join("/"):""}function cQM(e,t,r,i){return e||t||HFt(r??"")||HFt(i??"")}function wQ_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var dGo=class extends $a{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[ZF_],this.accessTokenLocator!=null&&(wQ_(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var pGo=class extends $a{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new VLn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new dGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=fGo({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:Qs.EndpointId(r),accessTokenLocator:Qs.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var xLn=class extends $a{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new k9o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new tGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new eGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new rGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new iGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{sQ_(this.input)?(this.authScheme="header",this.headerAuthNode=new VLn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new pGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new EQ_.UnreachableCaseError(this.authScheme);return}}};var GLn=class extends $a{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=Z9o(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new xLn({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(mo))}};var _Go=class extends $a{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[KF_],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function SQ_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function MQ_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function HLn(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>km(n.convert())?.map(o=>((t!=null&&!t.includes(i)||t==null&&!SQ_(n))&&(o=MQ_(o,o.type==="enum"?o.default:void 0)),{key:Qs.PropertyKey(i),valueShape:o,description:n.description,availability:n.availability?.convert()})).filter(mo)).filter(mo).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]])}function hGo(e,t){return sv(e)?cU(e,t,void 0):e}function y1i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function DQ_(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function BQ_(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var IQ_=ce(zE());var Ggc=["decimal","decimal128","double-int","double","float","sf-decimal"],Hgc=["int16","int32","int64","int8","sf-integer","uint8"],Kgc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],Jgc=["beta","pre-release","in-development","generally-available","deprecated"];function VB(e,t){return sv(e)?cU(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var EPe=class extends $a{availability;constructor(t){super(t),this.safeParse()}parse(){if(VB(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[JF_];r!=null&&(Jgc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${Jgc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return Qs.Availability.Beta;case"in-development":return Qs.Availability.InDevelopment;case"generally-available":return Qs.Availability.GenerallyAvailable;case"deprecated":return Qs.Availability.Deprecated;case void 0:return;default:new IQ_.UnreachableCaseError(this.availability);return}}};var bGo=ce(zE());function CQ_(e){return typeof e=="object"&&e!=null&&"language"in e}function qQ_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function TQ_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function RQ_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function yGo(e){return typeof e=="object"&&e!=null&&"event"in e}function $gc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(yGo)}function b1i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function zQ_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var vGo=class extends $a{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[uQ_]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let o=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return b1i(o)?[n,{type:"filenameWithData",filename:o.filename,data:Qs.FileId(o.data)}]:o!=null?[n,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>b1i(c)))return[n,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:Qs.FileId(c.data)}))}];if(o.every(c=>typeof c=="string"))return[n,{type:"filenames",value:o}]}return}case"property":return[n,{type:"json",value:o}];case void 0:return;default:new bGo.UnreachableCaseError(a.multipartType);return}}).filter(mo))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=zQ_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new bGo.UnreachableCaseError(n.contentType);break}let o;switch(i.contentType){case"application/json":{TQ_(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{$gc(r.response)&&(o={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!$gc(r.response)&&RQ_(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new bGo.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(l=>{CQ_(l)?l.language!=null&&(c[l.language]??=[],c[l.language]?.push({name:l.name,language:l.language,install:l.install,code:l.code,generated:!1,description:l.docs})):qQ_(l)&&l.sdk!=null&&(c[l.sdk]??=[],c[l.sdk]?.push({name:l.name,language:l.sdk,install:void 0,code:l.code,generated:!1,description:l.docs}))});let f=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([l,p])=>[Qs.PropertyKey(l),p])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,p])=>[Qs.PropertyKey(l),p])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([l,p])=>[Qs.PropertyKey(l),p]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(f).length>0?f:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(u).length>0?u:void 0,requestBody:a,responseBody:o,snippets:c}}))}};var iSa=class extends $a{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[$9o]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>Qs.api.v1.SubpackageId(HFt(r)))}};var gGo=class extends $a{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[YF_]}convert(){return this.sdkMethodName}};var OGo=class extends $a{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[XF_]}convert(){return this.isWebhook}};var AGo=class extends $a{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[lQ_]??[],...this.input[fQ_]??[]],this.codeSamples.forEach(t=>{[...Object.values(Qs.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var x$i=ce(zE());function Ygc(e,t){return sv(e)?cU(e,t,void 0):e}function NQ_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var Dz="",k9t=class extends $a{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(b1i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>b1i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new x$i.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=Ygc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=Ygc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new x$i.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(yGo)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new x$i.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return b1i(n)?[r,{type:"filenameWithData",filename:n.filename,data:Qs.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>b1i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:Qs.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new x$i.UnreachableCaseError(i.multipartType);return}}).filter(mo))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new x$i.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new x$i.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([o,c])=>[o,c.example({includeOptionals:!1,override:o})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(mo));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(mo));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:NQ_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?Z9t(this.name):this.summary!=null?Z9t(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function FQ_(e,t){return sv(e)?cU(e,t,void 0):e}var XQ_=ce(zE());var QQ_="#/components/schemas/";function KLn(e){if(e.$ref.startsWith(QQ_))return e.$ref.replace(QQ_,"")}function Wgi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function v1i(e){return typeof e.type=="string"&&e.type==="array"}function UQ_(e){return e.type==="boolean"}function LQ_(e){return e.type==="integer"}function g1i(e){return!Array.isArray(e.type)&&!v1i(e)}function VQ_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||g1i(t)||v1i(t))}function WQ_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function xQ_(e){return e.type==="null"}function GQ_(e){return e.type==="number"}function Xgc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function HQ_(e){return e.type==="string"}var mGo=class extends OK{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new YP({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return km(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var PGo=class extends LB{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new EPe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var jGo=class extends OK{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new YP({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(mo)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>km(n.convert())?.map(o=>({displayName:n.name,shape:o,description:n.description,availability:n.availability?.convert()}))).filter(mo).reduce((n,a)=>n.flatMap(o=>a.length>0?a.map(c=>[...o,c]):[[...o]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(Wgi).filter(mo):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function wGo(e){return e!=null&&e.length>0?e:[void 0]}var JLn=class extends OK{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new YP({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new YP({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(sv(t))return KLn(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new YP({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(mo))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return HLn(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:km(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(mo)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>wGo(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>Qs.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=VB(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,o])=>[a,new YP({input:o,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var EGo=class extends OK{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>VB(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>VB(t,this.context.document)?.type!=="null"?new YP({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(mo);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=VB({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new YP({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(mo);return this.isNullable&&n!=null?n.map(Wgi).filter(mo):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:Qs.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>km(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??Z9t(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(mo)).filter(mo)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>km(n.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?Z9t(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(o.type==="alias"&&o.value.type==="id"?Z9t(o.value.id):c),shape:o,description:n.description,availability:n.availability?.convert()}}).filter(mo)).filter(mo)}:void 0,i=this.isNullable?Wgi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var SGo=class extends LB{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var O1i=class extends LB{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(sv(r)){let n=VB(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(mo),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var KQ_=ce(zE());function lQM(e){return Hgc.includes(e)}var MGo=class extends LB{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(lQM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Hgc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new KQ_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var DGo=class extends LB{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return Wgi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var JQ_=ce(zE());function fQM(e){return Ggc.includes(e)}var BGo=class extends LB{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(fQM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Ggc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new JQ_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var $Q_=ce(zE());function dQM(e){return Kgc.includes(e)}var IGo=class extends LB{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new $Q_.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(dQM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${Kgc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new O1i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var YQ_=ce(zE());var CGo=class extends LB{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,YQ_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var G$i=class extends OK{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=KLn(this.input);let t=VB(this.input,this.context.document);t?.enum!=null&&g1i(t)&&(this.maybeEnumConverterNode=new O1i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:Qs.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=VB(this.input,this.context.document);if(r!=null)return new YP({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var YP=class e extends OK{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new EPe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),g1i(this.input)&&WQ_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),sv(this.input)){let t=KLn(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new G$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new PGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(VQ_(this.input))this.typeShapeNode=new jGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(g1i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new EGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(Xgc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new JLn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(g1i(this.input)&&this.input.enum!=null)this.typeShapeNode=new O1i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":Xgc(this.input)&&(this.typeShapeNode=new JLn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":v1i(this.input)&&(this.typeShapeNode=new mGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":UQ_(this.input)&&(this.typeShapeNode=new SGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":LQ_(this.input)&&(this.typeShapeNode=new MGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":GQ_(this.input)&&(this.typeShapeNode=new BGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":HQ_(this.input)&&(this.typeShapeNode=new IGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":xQ_(this.input)&&(this.typeShapeNode=new DGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new XQ_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new JLn({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new CGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!sv(this.input)&&(!v1i(this.input)&&this.input==null||v1i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=km(t)?.map(i=>this.nullable?Wgi(i):i).filter(mo);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function A1i(e){if(e!=null)return HLn(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(mo))}var eGt=class extends LB{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;sv(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new EPe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new YP({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=FQ_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function ZQ_(e,t){return sv(e)?cU(e,t,void 0):e}var Zgc=ce(zE());function qGo(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[Qs.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var kQ_=ce(kjs(),1),$Ln=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,o){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=o}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=kQ_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function pQM(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var TGo=class extends $a{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new YP({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),pQM(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(sv(r)?n=Z9o(r.$ref,this.context.document):n=r,n!=null)return[t,new xLn({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(mo)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[Qs.api.latest.AuthSchemeId(t),i]}).filter(mo)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=km(r.convert());return n==null?[t,void 0]:[Qs.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>mo(r))):void 0}}};var RGo=class extends YP{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=VB(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${sv(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=VB(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var zGo=class extends $a{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=VB(this.input.schema,this.context.document);this.availability=new EPe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=sv(this.input.schema)?new G$i({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=$Ln.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new YP({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,o])=>{if(o!=null)return[a,new RGo({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(mo))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[Dz]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[Dz]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:km(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=HFt([this.method,this.path,this.contentType,"request"].join("_"));return qGo({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Qs.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new Zgc.UnreachableCaseError(n);return}}).filter(mo)}convert(){if(this.schema instanceof G$i)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:Qs.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:Qs.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=km(n.convert()),o=n.multipartType;return a?.map(c=>({type:o,key:Qs.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new Zgc.UnreachableCaseError(n.multipartType),[]}}).filter(mo).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var NGo=class extends $a{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=ZQ_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new zGo({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>km(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(mo)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>km(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(mo)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var eU_={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function tU_(e,t){if(sv(e)){let r=cU(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var FGo=ce(zE());var rU_="application/json";var iU_="application/octet-stream";function nU_(e,t){return e===t||t===Dz||e===Dz}var nSa=class extends $a{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,o,c,f){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=o,this.requests=c,this.shapes=f,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,o]of Object.entries(n?.examples??{}))for(let[c,f]of Object.entries(r))for(let s of f)nU_(c,a)&&(i.add(c),this.examples?.push(new k9t({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,y1i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[o,c]of r){if(a===i){let[f,s,u]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(l=>new k9t({input:{requestExample:u,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,y1i(s,o),{requestBody:f,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,o]=r[r.length-1]??[void 0,void 0],[c,f,s]=n??[void 0,void 0,void 0];this.examples?.push(...(o??[void 0]).map(u=>new k9t({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:f!=null&&f!==""?["examples",f]:"examples"},this.path,this.statusCode,y1i(f,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,o]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,f]of r.slice(t.length))this.examples?.push(...f.map(s=>new k9t({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,y1i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[Dz];if(a!=null)for(let o of a)this.examples?.push(new k9t({input:{requestExample:n,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,y1i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=$Ln.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=rU_,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new YP({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=iU_,this.contentSubtype=VB(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new YP({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=lGo(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[Dz]??=[],r[Dz]=[{value:this.input.example}]);let i=VB(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=lGo(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[Dz]??=[],r[Dz]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[Dz]??=[],r[Dz]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([f])=>!n.has(f)&&f!==Dz).map(([f,s])=>[c,f,s]));let o=Object.entries(r).filter(([c,f])=>!n.has(c)&&mo(f)&&c!==Dz);Object.keys(r).every(c=>c===Dz)||this.matchExamplesByIndex(a,o),!n.has(Dz)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return km(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new FGo.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return km(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=HFt([this.method,this.path,this.statusCode,"response"].join("_"));return qGo({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Qs.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new FGo.UnreachableCaseError(i);return}}).filter(mo)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new FGo.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var aSa=class extends $a{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,o){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=o,this.safeParse()}parse(t){this.description=this.input.description;let r=tU_(this.input,this.context.document);if(r==null){this.context.errors.error({message:sv(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new eGt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new nSa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new nSa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(mo)}};var QGo=class extends $a{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new aSa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new aSa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return wGo(A1i(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(o=>(o.examples??[]).map(c=>c.convert()).filter(mo))})))}).filter(mo)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=km(n?.convert());if(n!=null)return a?.map(o=>({statusCode:parseInt(t),shape:o,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??eU_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let f=c.convert();if(f!=null&&f.responseBody?.type==="json")return{name:f.name,description:f.description,responseBody:f.responseBody}}).filter(mo)})).filter(mo)})).filter(mo)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var m1i=class extends $a{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new k9t({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,y1i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new EPe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=h1i(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new OGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(sv(i)){let a=hGo(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new eGt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new eGt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new eGt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new AGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new NGo({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new QGo({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,o])=>{this.pushEmptyResponseExample(o,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new GLn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new iSa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new iSa({input:{[$9o]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new gGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>fGo({namespace:km(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(mo),this.xFernExamplesNode=new vGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(mo)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:Qs.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(u=>u.convert()).filter(mo),n=BQ_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:DQ_(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:Qs.WebhookId(u),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[l]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(p=>p.value.toString())??[],queryParameters:A1i(this.queryParameters)?.flat(),headers:A1i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(mo)}}).filter(mo);let a=this.servers?.map(u=>u.convert()).filter(mo),o=this.convertPathToPathParts();if(o==null)return;let c,f=this.auth?.convert();f!=null&&(c=Object.keys(f));let s=t?.flatMap(u=>u.headers).filter(mo);return this.endpointIds.map((u,l)=>({id:Qs.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(p=>Qs.api.v1.SubpackageId(p)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(p=>Qs.api.latest.AuthSchemeId(p)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:A1i(this.pathParameters)?.flat(),queryParameters:A1i(this.queryParameters)?.flat(),requestHeaders:A1i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(p=>p.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var YLn=class extends $a{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=h1i(t,this.input.servers,this.context,this.accessPath),o=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new m1i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:o,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new m1i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:o,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new m1i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:o,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new m1i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:o,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new m1i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:o,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(mo)}};function UGo(e){return"payloads"in e}var LGo=class extends $a{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new YLn({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:h1i(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(mo)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{UGo(a)?r[Qs.WebhookId(a.id)]=a:t[Qs.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var VGo=class extends $a{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[$F_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||hGo(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new eGt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return HLn(this.globalHeaders,this.requiredProperties)?.flat()}};function aU_(e,t){if(sv(e)){let r=cU(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var WGo=class extends $a{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let o=aU_(a,this.context.document);if(o!=null)return new YLn({input:o,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(mo)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{UGo(i)&&(t[Qs.WebhookId(i.id)]=i)}),t),{})}};var xGo=class extends $a{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=h1i(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new GLn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new _Go({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new LGo({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new WGo({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new TGo({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new VGo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=the(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=GF_({endpoints:i,webhookEndpoints:n}),{types:o,auths:c}=this.components?.convert()??{};return{id:Qs.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...o,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};async function kgc(e,t){if(e instanceof Q9t){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof Xw))return;let r=new zFt(e.absoluteFilePath),i=await bPe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let o of n){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new K9o,generatedTypes:{}},f=new xGo({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=hws(a,f.convert())}return a}var PG_=ce(rOc(),1),jG_=ce(C7o(),1),rKo=require("fs/promises"),wG_=ce(require("http"),1),EG_=ce(require("path"),1);var cV_=require("events"),N7o=ce(require("fs"),1),tYi=ce(require("path"),1);var G8_=ce(require("os"),1),H8_=300,D1i=20,MSa=1e7,K8_=G8_.default.platform();var R5M=K8_==="darwin",mAc=K8_==="win32",B1i=R5M||mAc,J8_=3e3,$8_=2e4,PAc=1250;var nGt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(nGt||(nGt={}));var eYi;(function(e){e.CHANGE="change",e.RENAME="rename"})(eYi||(eYi={}));var DSa;(function(e){e.CHANGE="change",e.ERROR="error"})(DSa||(DSa={}));var Il;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(Il||(Il={}));var Qx;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(Qx||(Qx={}));var z5M=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,f=0,s=0,u=()=>{let g=Date.now(),m=g-f,j=g-s,S=m>=t||j>=a;return[g,S]},l=g=>{if(s=g,!o)return;let m=o;o=void 0,e.apply(void 0,m)},p=()=>{O(0)},_=()=>{c&&(p(),l(Date.now()))},h=g=>{if(s=g,i)return l(g)},y=g=>{if(n&&o)return l(g);o=void 0},b=()=>{c=void 0;let[g,m]=u();return m?y(g):v(g)},v=g=>{let m=g-f,j=g-s,S=t-m,E=a-j,D=Math.min(S,E);return O(D)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},A=(...g)=>{let[m,j]=u(),S=!!c;if(o=g,f=m,(j||!c)&&O(t),j)return S?l(m):h(m)};return A.cancel=p,A.flush=_,A},q7o=z5M;var SAc=ce(require("fs"),1),R7o=ce(require("path"),1);var bO=ce(require("fs"),1),lU=require("util");var Ggi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},aGt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var jAc=ce(require("process"),1),Y8_=jAc.default.getuid?!jAc.default.getuid():!1,X8_=1e4,jK=()=>{};var BSa={isChangeErrorOk:e=>{if(!BSa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!Y8_&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!BSa.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!BSa.isNodeError(e))throw e;if(!BSa.isChangeErrorOk(e))throw e}},WB=BSa;var wAc=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=X8_,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},Z8_=new wAc;var Hgi=(e,t)=>function(i){return function n(...a){return Z8_.schedule().then(o=>{let c=s=>(o(),s),f=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,f)})}},Kgi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var N5M={attempt:{chmod:Ggi((0,lU.promisify)(bO.default.chmod),WB.onChangeError),chown:Ggi((0,lU.promisify)(bO.default.chown),WB.onChangeError),close:Ggi((0,lU.promisify)(bO.default.close),jK),fsync:Ggi((0,lU.promisify)(bO.default.fsync),jK),mkdir:Ggi((0,lU.promisify)(bO.default.mkdir),jK),realpath:Ggi((0,lU.promisify)(bO.default.realpath),jK),stat:Ggi((0,lU.promisify)(bO.default.stat),jK),unlink:Ggi((0,lU.promisify)(bO.default.unlink),jK),chmodSync:aGt(bO.default.chmodSync,WB.onChangeError),chownSync:aGt(bO.default.chownSync,WB.onChangeError),closeSync:aGt(bO.default.closeSync,jK),existsSync:aGt(bO.default.existsSync,jK),fsyncSync:aGt(bO.default.fsync,jK),mkdirSync:aGt(bO.default.mkdirSync,jK),realpathSync:aGt(bO.default.realpathSync,jK),statSync:aGt(bO.default.statSync,jK),unlinkSync:aGt(bO.default.unlinkSync,jK)},retry:{close:Hgi((0,lU.promisify)(bO.default.close),WB.isRetriableError),fsync:Hgi((0,lU.promisify)(bO.default.fsync),WB.isRetriableError),open:Hgi((0,lU.promisify)(bO.default.open),WB.isRetriableError),readFile:Hgi((0,lU.promisify)(bO.default.readFile),WB.isRetriableError),rename:Hgi((0,lU.promisify)(bO.default.rename),WB.isRetriableError),stat:Hgi((0,lU.promisify)(bO.default.stat),WB.isRetriableError),write:Hgi((0,lU.promisify)(bO.default.write),WB.isRetriableError),writeFile:Hgi((0,lU.promisify)(bO.default.writeFile),WB.isRetriableError),closeSync:Kgi(bO.default.closeSync,WB.isRetriableError),fsyncSync:Kgi(bO.default.fsyncSync,WB.isRetriableError),openSync:Kgi(bO.default.openSync,WB.isRetriableError),readFileSync:Kgi(bO.default.readFileSync,WB.isRetriableError),renameSync:Kgi(bO.default.renameSync,WB.isRetriableError),statSync:Kgi(bO.default.statSync,WB.isRetriableError),writeSync:Kgi(bO.default.writeSync,WB.isRetriableError),writeFileSync:Kgi(bO.default.writeFileSync,WB.isRetriableError)}},k8_=N5M;var T7o=ce(require("fs"),1),ISa=ce(require("path"),1);var EAc=()=>{};var F5M=()=>{let e=EAc,t=EAc,r=!1,i=!1;return{promise:new Promise((f,s)=>{e=u=>(r=!0,f(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},eV_=F5M;var Q5M=()=>{let{promise:e,resolve:t,isPending:r}=eV_(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},tV_=Q5M;var rV_={then:e=>{e()}};var iV_=e=>Array.isArray(e)?e:[e],nV_=e=>typeof e=="function";var U5M=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=iV_(a).map(V=>nV_(V)?V:U=>V.test(U)),c=V=>o.some(U=>U(V)),f=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],l=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,O={},A={},g=new Set,m={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:l,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:A},{promise:S,increment:E,decrement:D}=tV_(),B=0,F=(V,U,Se,ue)=>{g.has(U)||B>=n||(B+=1,V.directories.push(U),V.directoriesNames.add(Se),u.push(U),l.add(Se),p.propertyIsEnumerable(Se)||(p[Se]=[]),p[Se].push(U),g.add(U),!(ue>=i)&&(B>=n||J(U,ue+1)))},N=(V,U,Se)=>{g.has(U)||B>=n||(B+=1,V.files.push(U),V.filesNames.add(Se),_.push(U),h.add(Se),y.propertyIsEnumerable(Se)||(y[Se]=[]),y[Se].push(U),g.add(U))},R=(V,U,Se,ue)=>{g.has(U)||B>=n||(B+=1,V.symlinks.push(U),V.symlinksNames.add(Se),b.push(U),v.add(Se),O.propertyIsEnumerable(Se)||(O[Se]=[]),O[Se].push(U),g.add(U),r&&(ue>=i||B>=n||fe(U,ue+1)))},z=(V,U,Se,ue,we)=>{f.aborted||c(U)||(ue.isDirectory()?F(V,U,Se,we):ue.isFile()?N(V,U,Se):ue.isSymbolicLink()&&R(V,U,Se,we))},L=(V,U,Se,ue)=>{if(f.aborted)return;let we=U===ISa.default.sep?"":ISa.default.sep,Le=Se.name,se=`${U}${we}${Le}`;c(se)||(Se.isDirectory()?F(V,se,Le,ue):Se.isFile()?N(V,se,Le):Se.isSymbolicLink()&&R(V,se,Le,ue))},H=(V,U,Se,ue)=>{for(let we=0,Le=Se.length;we<Le;we++)L(V,U,Se[we],ue)},J=(V,U)=>{f.aborted||U>i||B>=n||(E(),T7o.default.readdir(V,{withFileTypes:!0},(Se,ue)=>{if(Se||f.aborted||!ue.length)return D();(s(ue)||rV_).then(()=>{let Le=A[V]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};H(Le,V,ue,U),D()})}))},fe=(V,U)=>{E(),T7o.default.realpath(V,(Se,ue)=>{if(Se||f.aborted)return D();T7o.default.stat(ue,(we,Le)=>{if(we||f.aborted)return D();let se=ISa.default.basename(ue),ne=A[V]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(ne,ue,se,Le,U),D()})})};return(async(V,U=1)=>(V=ISa.default.normalize(V),g.add(V),J(V,U),await S,f.aborted?m:j))(e)},aV_=U5M;var oGt={lang:{debounce:q7o,attempt:e=>{try{return e()}catch(t){return oGt.lang.castError(t)}},castArray:e=>oGt.lang.isArray(e)?e:[e],castError:e=>oGt.lang.isError(e)?e:oGt.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(oGt.lang.isNaN(e))return oGt.lang.isNaN(t);if(oGt.lang.isPrimitive(e)||oGt.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(R7o.default.sep).length-1),getRealPath:(e,t)=>{try{return t?SAc.default.realpathSync.native(e):SAc.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===R7o.default.sep&&t.length-e.length>R7o.default.sep.length,poll:(e,t=$8_)=>k8_.retry.stat(t)(e,{bigint:!0}).catch(oGt.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await aV_(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},cp=oGt;var z7o=ce(require("path"),1);var MAc=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||cp.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=H8_){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,f)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...f]),l=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(l)},o=cp.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,f="",s=!1)=>{s?await this.eventsPopulate([f],i,!0):n.add(f),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===Il.CHANGE&&c===Il.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===Il.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Il.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??D1i:Math.min(1,this.options.depth??D1i),o=this.options.limit??MSa,[c,f]=await cp.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...f];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())cp.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Il.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!B1i&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(Il.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Il.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(z7o.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Il.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(z7o.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(Il.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Il.ADD?this.onTargetAdd(i):r===Il.ADD_DIR?this.onTargetAddDir(i):r===Il.CHANGE?this.onTargetChange(i):r===Il.UNLINK?this.onTargetUnlink(i):r===Il.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=eYi.CHANGE,r){if(this.watcher.isClosed())return;let i=z7o.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){mAc&&t.code==="EPERM"?this.onWatcherChange(eYi.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(DSa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(DSa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(eYi.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&B1i&&this.options.native!==!1?this.options.depth??D1i:Math.min(1,this.options.depth??D1i),i=this.options.limit??MSa,[n,a]=await cp.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(eYi.CHANGE,c,t)}))}}},oV_=MAc;var Ux={interval:100,intervalId:void 0,fns:new Map,init:()=>{Ux.intervalId||(Ux.intervalId=setInterval(Ux.resolve,Ux.interval))},reset:()=>{Ux.intervalId&&(clearInterval(Ux.intervalId),delete Ux.intervalId)},add:(e,t)=>{Ux.fns.set(e,Date.now()+t),Ux.init()},remove:e=>{Ux.fns.delete(e)},resolve:()=>{if(!Ux.fns.size)return Ux.reset();let e=Date.now();for(let[t,r]of Ux.fns)r>=e||(Ux.remove(t),t())}},CSa=Ux;var qSa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=PAc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let l=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(l&&l!==n){if(cp.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return c();let f=()=>{o.add.delete(i),CSa.remove(s)},s=()=>{f(),c()};CSa.add(s,r);let u=()=>{let l=o.unlink.get(i);if(!l)return;f();let p=l();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=PAc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let f=()=>{o.unlink.delete(i),CSa.remove(s)},s=()=>{f(),c()};CSa.add(s,r);let u=()=>(f(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,Il.ADD,nGt.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,Il.ADD_DIR,nGt.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,Il.UNLINK,nGt.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,Il.UNLINK_DIR,nGt.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};qSa.DIR_EVENTS={add:Il.ADD_DIR,rename:Il.RENAME_DIR,unlink:Il.UNLINK_DIR};qSa.FILE_EVENTS={add:Il.ADD,change:Il.CHANGE,rename:Il.RENAME,unlink:Il.UNLINK};var uV_=qSa;var DAc=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(cp.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(cp.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(cp.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(cp.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return cp.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);cp.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},BAc=DAc;var IAc=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},sV_=IAc;var CAc=class{constructor(){this.inos={},this.paths=new BAc,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await cp.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new sV_(i)}reset(){this.inos={},this.paths=new BAc,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,Il.ADD,n),[Il.ADD];if(n.isDirectory())return this.updateIno(t,Il.ADD_DIR,n),[Il.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Il.UNLINK,i),[Il.UNLINK];if(i.isDirectory())return this.updateIno(t,Il.UNLINK_DIR,i),[Il.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Il.CHANGE,n),[Il.CHANGE]);if(n.isDirectory())return this.updateIno(t,Il.UNLINK,i),this.updateIno(t,Il.ADD_DIR,n),[Il.UNLINK,Il.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Il.UNLINK_DIR,i),this.updateIno(t,Il.ADD,n),[Il.UNLINK_DIR,Il.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Il.UNLINK_DIR,i),this.updateIno(t,Il.ADD_DIR,n),[Il.UNLINK_DIR,Il.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?nGt.FILE:nGt.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},qAc=CAc;var TAc=class e extends cV_.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(Qx.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(Qx.CLOSE,n)),this._readyWait=new Promise(n=>this.on(Qx.READY,n)),this._locker=new uV_(this),this._roots=new Set,this._poller=new qAc,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(cp.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(Qx.CLOSE))}error(t){if(this.isClosed())return!1;let r=cp.lang.castError(t);return this.emit(Qx.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(Qx.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(Qx.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&cp.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&cp.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)cp.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new oV_(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=cp.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=tYi.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??D1i))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&B1i&&u.options.native!==!1)))return!0;if(!B1i)break;let s=tYi.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=cp.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let f=!r.recursive||B1i&&r.native!==!1?r:{...r,recursive:!1},u={watcher:N7o.default.watch(c,f),handler:i,options:r,folderPath:c,filePath:n},l=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=tYi.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,l)}}catch(f){this.error(f)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||B1i&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??D1i,c=r.limit??MSa,[f]=await cp.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(f.length){let u=cp.fs.getDepth(t);for(let l of f){let p=cp.fs.getDepth(l),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([l],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(f(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(Qx.CLOSE,f),o.watchFile(t,r,a)},f=()=>{this._subwatchers.delete(n),this.removeListener(Qx.CLOSE,f),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=tYi.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new qAc,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return cp.lang.noop;if(this.pollerExists(t,r))return cp.lang.noop;let n={...r,interval:r.pollingInterval??J8_},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(Qx.CLOSE,c),N7o.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(Qx.CLOSE,c),N7o.default.unwatchFile(t,i)};return cp.lang.attempt(o),()=>cp.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=cp.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,f)=>f===o||!cp.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=tYi.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await cp.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=tYi.default.dirname(t);return(await cp.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=cp.lang.noop){if(cp.lang.isFunction(t))return this.watch([],{},t);if(cp.lang.isUndefined(t))return this.watch([],r,i);if(cp.lang.isFunction(r))return this.watch(t,{},r);if(cp.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=cp.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==cp.lang.noop&&this.on(Qx.ALL,i),r.readdirMap=void 0,this.ready())}},F7o=TAc;TMo();var d3n=require("fs/promises"),lV_=require("os"),fV_=ce(require("path"),1),L5M=".fern",V5M="logs";function W5M(){return"cli@3.26.2"}var TSa=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Bt(Br.of((0,lV_.homedir)()),Ye.of(L5M)),r=Bt(t,Ye.of(V5M));await ji(r)||await(0,d3n.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Bt(r,Ye.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${fV_.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
1787
1787
  `);await(0,d3n.writeFile)(this.logFilePath,a,"utf-8"),this.initialized=!0}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
1788
1788
  `;try{await(0,d3n.appendFile)(this.logFilePath,r,"utf-8")}catch{}}async logFrontendMetrics(t){let r={timestamp:t.timestamp,source:t.source,level:t.level,eventType:this.getEventType(t.payload,t.isAggregate),isAggregate:t.isAggregate,data:t.payload};await this.writeEntry(r)}async logCliMetric(t,r="info"){let i={timestamp:t.timestamp,source:W5M(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(i)}async logCliMemory(){let t=process.memoryUsage(),r={type:"cli_memory",timestamp:new Date().toISOString(),metadata:{heapUsed:t.heapUsed,heapTotal:t.heapTotal,external:t.external,rss:t.rss,heapUsedMB:Math.round(t.heapUsed/1024/1024*100)/100,heapTotalMB:Math.round(t.heapTotal/1024/1024*100)/100,rssMB:Math.round(t.rss/1024/1024*100)/100}};await this.logCliMetric(r)}async logCliReloadStart(){let t={type:"cli_reload_start",timestamp:new Date().toISOString()};await this.logCliMetric(t)}async logCliReloadFinish(t,r){let i={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliDocsGeneration(t,r){let i={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliValidation(t,r){let i={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(i)}getEventType(t,r){return r?"aggregate_summary":"type"in t&&typeof t.type=="string"?t.type:"unknown"}static isMetricsMessage(t){if(typeof t!="object"||t===null)return!1;let r=t;return r.type==="metrics"&&typeof r.timestamp=="string"&&typeof r.source=="string"}};var u0c=ce(WAc(),1),rG_=ce(DHo(),1),wK=require("fs/promises"),iG_=require("os"),nG_=ce(qW(),1),aG_=ce(tG_(),1),HHo=process.platform==="win32",o0c=Ut.cyan("[docs]:"),cGM="etag",lGM="preview",fGM="app-preview",dGM="bundle",pGM=".next",_GM="standalone",hGM=".fern",yGM="packages/fern-docs/bundle/.next/server/instrumentation.js",bGM=".npmrc",vGM=".pnpmfile.cjs",gGM="pnpm-workspace.yaml",OGM='Cannot find matching keyid: {"signatures":';function AGM(){return Bt(Br.of((0,iG_.homedir)()),Ye.of(hGM))}function D3n({app:e=!1}){return Bt(AGM(),Ye.of(e?fGM:lGM))}function Q1i({app:e=!1}){return Bt(D3n({app:e}),Ye.of(e?pGM:dGM))}function nMa({app:e=!1}){return Bt(Q1i({app:e}),Ye.of(_GM))}function mGM({app:e=!1}){return Bt(nMa({app:e}),Ye.of(yGM))}function PGM({app:e=!1}){return Bt(nMa({app:e}),Ye.of(gGM))}function jGM({app:e=!1}){return Bt(nMa({app:e}),Ye.of(vGM))}function wGM({app:e=!1}){return Bt(nMa({app:e}),Ye.of(bGM))}function sYi(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function EGM({app:e=!1}){return Bt(D3n({app:e}),Ye.of(cGM))}var SGM=`module.exports = {
1789
1789
  hooks: {