fern-api 0.101.0 → 0.101.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +3 -3
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -2163,7 +2163,7 @@ ${M1y.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&x0f(th
|
|
|
2163
2163
|
`+pla.default.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?pla.default.cyan(Q1y(t,this.opt.mask)):pla.default.italic(pla.default.dim("[hidden]")):this.opt.mask?Q1y(t,this.opt.mask):pla.default.italic(pla.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 hCs=Gi(lse(),1);var QEy=Gi(gmf(),1),pCs=require("child_process"),Qeo=require("fs"),dCs=Gi(require("path"),1),LEy=Gi(require("os"),1),UEy=require("crypto"),nOf=Gi(xEy(),1);var cCs=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var N$o=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var lCs=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var fCs=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function _Cs(e="",t,r){let n=new iOf(e,r);n.runAsync((i,a)=>{if(i)setImmediate(t,i,void 0);else try{n.cleanup(),setImmediate(t,void 0,a)}catch(o){setImmediate(t,o,void 0)}})}function zEy(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function zdC(e){let t=[],r="";for(let n=0;n<e.length;n++){let i=e.charAt(n);n>0&&i===" "&&e[n-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${i}`}return r.length>0&&t.push(r),t}var iOf=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=zdC(t).map(i=>i.replace("\\ "," ")),n=r.shift();this.editor={args:r,bin:n}}createTemporaryFile(){try{let t=this.fileOptions.dir??LEy.default.tmpdir(),r=(0,UEy.randomUUID)(),n=zEy(this.fileOptions.prefix),i=zEy(this.fileOptions.postfix),a=`${n}${r}${i}`,o=dCs.default.resolve(t,a),c=dCs.default.resolve(t)+dCs.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,Qeo.writeFileSync)(this.tempFile,this.text,f)}catch(t){throw new cCs(t)}}readTemporaryFile(){try{let t=(0,Qeo.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,QEy.detect)(t)??"utf8";nOf.default.encodingExists(r)||(r="utf8"),this.text=nOf.default.decode(t,r)}}catch(t){throw new lCs(t)}}removeTemporaryFile(){try{(0,Qeo.unlinkSync)(this.tempFile)}catch(t){throw new fCs(t)}}launchEditor(){try{let t=(0,pCs.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new N$o(t)}}launchEditorAsync(t){try{(0,pCs.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",n=>{this.lastExitStatus=n,setImmediate(t)})}catch(r){throw new N$o(r)}}};var VEy=Gi(_it(),1);var F$o=class extends fse{_run(t){this.done=t,this.editorResult=new VEy.Subject;let r=Fbe(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let n=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,i=this.handleSubmitEvents(this.editorResult);return i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,n?this.render():this.startExternalEditor(),this}render(t){let r="",n=this.getQuestion();n+=this.status==="answered"?hCs.default.dim("Received"):hCs.default.dim("Press <enter> to launch your preferred editor."),t&&(r=hCs.default.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),_Cs(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 KEy=require("stream");var GEy=Gi(require("readline"),1),JEy=Gi(HEy(),1),vla=class{constructor(t){this.rl||=GEy.default.createInterface(LdC(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 LdC(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let i=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw i.isTtyError=!0,i}let r=new JEy.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var x$o=class extends vla{constructor(t={}){super(t),this.log=new KEy.Writable({write:(r,n,i)=>{this.writeLog(r),i()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return O$o(this.rl,this.bottomBar.split(`
|
|
2164
2164
|
`).length),this}updateBottomBar(t){return O$o(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+`
|
|
2165
2165
|
`}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&&FDs(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var i6=Gi(_it(),1),XEy=Gi(UKo(),1);var yCs=Gi(_it(),1),$Ey=Gi(UKo(),1),vCs=function(e,t,r){return typeof e[t]!="function"?(0,yCs.of)(e):(0,yCs.from)((0,$Ey.default)(e[t])(r).then(n=>(e[t]=n,e)))};var YEy={set:(e,t="",r)=>{let n=e;t.split(".").forEach((i,a,o)=>{i==="__proto__"||i==="constructor"||(a===o.length-1?n[i]=r:(!(i in n)||typeof n[i]!="object")&&(n[i]={}),n=n[i])})},get:(e,t="",r)=>{let n=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((o,c)=>o!=null?o[c]:o,e),i=n(/[,[\]]+?/)||n(/[,.[\]]+?/);return i===void 0||i===e?r:i}},Leo=class extends vla{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let n;return Array.isArray(t)?n=(0,i6.from)(t):(0,i6.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,i6.from)(Object.entries(t).map(([i,a])=>({name:i,...a}))):n=(0,i6.from)([t]),this.process=n.pipe((0,i6.concatMap)(this.processQuestion.bind(this)),(0,i6.publish)()),this.process.connect(),this.process.pipe((0,i6.reduce)((i,a)=>(YEy.set(i,a.name,a.answer),i),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,i6.defer)(()=>(0,i6.of)(t).pipe((0,i6.concatMap)(this.setDefaultType.bind(this)),(0,i6.concatMap)(this.filterIfRunnable.bind(this)),(0,i6.concatMap)(()=>vCs(t,"message",this.answers)),(0,i6.concatMap)(()=>vCs(t,"default",this.answers)),(0,i6.concatMap)(()=>vCs(t,"choices",this.answers)),(0,i6.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,i6.defer)(()=>(0,i6.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,i6.defer)(()=>(0,i6.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&YEy.get(this.answers,t.name)!==void 0)return i6.EMPTY;if(t.when===!1)return i6.EMPTY;if(typeof t.when!="function")return(0,i6.of)(t);let{answers:r}=this;return(0,i6.defer)(()=>(0,i6.from)((0,XEy.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,i6.filter)(n=>n!=null)))}};function ZEy(e){let t=function(r,n){let i;try{i=new Leo(t.prompts,e)}catch(o){return Promise.reject(o)}let a=i.run(r,n);return a.ui=i,a};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",P$o),this.registerPrompt("input",dla),this.registerPrompt("number",w$o),this.registerPrompt("confirm",j$o),this.registerPrompt("rawlist",E$o),this.registerPrompt("expand",S$o),this.registerPrompt("checkbox",D$o),this.registerPrompt("password",C$o),this.registerPrompt("editor",F$o)},t.restoreDefaultPrompts(),t}var oOf=ZEy();function VdC(e,t){oOf.registerPrompt(e,t)}function WdC(){oOf.restoreDefaultPrompts()}var HdC={prompt:oOf,ui:{BottomBar:x$o,Prompt:Leo},createPromptModule:ZEy,registerPrompt:VdC,restoreDefaultPrompts:WdC,Separator:v3e},bCs=HdC;var eto=require("path"),MDy=require("fs"),BDy=require("readline"),rDy="posthog-node";function bhC(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"]}={}){return a=>{if(!(i==="*"||i.includes(a.level)))return a;a.tags||(a.tags={});let c=a.tags[xCs.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(A=>({...A,stacktrace:A.stacktrace?{...A.stacktrace,type:"raw",frames:(A.stacktrace.frames||[]).map(P=>({...P,platform:"node:javascript"}))}:void 0})),m={$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&&(m.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),e.capture({event:"$exception",distinctId:c,properties:m}),a}}var xCs=class{constructor(t,r,n,i){this.name=rDy,this.name=rDy,this.setupOnce=function(a,o){let c=o()?.getClient()?.getDsn()?.projectId;a(bhC(t,{organization:r,projectId:c,prefix:n,severityAllowList:i}))}}};xCs.POSTHOG_ID_TAG="posthog_distinct_id";var TCs="0123456789abcdef",zCs=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,n,i){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(i)||t<0||r<0||n<0||i<0||t>0xffffffffffff||r>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|n>>>24,a[9]=n>>>16,a[10]=n>>>8,a[11]=n,a[12]=i>>>24,a[13]=i>>>16,a[14]=i>>>8,a[15]=i,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break}if(r){let n=new Uint8Array(16);for(let i=0;i<16;i+=4){let a=parseInt(r.substring(2*i,2*i+8),16);n[i+0]=a>>>24,n[i+1]=a>>>16,n[i+2]=a>>>8,n[i+3]=a}return new e(n)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=TCs.charAt(this.bytes[r]>>>4),t+=TCs.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+=TCs.charAt(this.bytes[r]>>>4),t+=TCs.charAt(this.bytes[r]&15);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let n=this.bytes[r]-t.bytes[r];if(n!==0)return Math.sign(n)}return 0}},WOf=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??ghC()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let n=this.generateOrAbortCore(t,r);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(t,r)),n}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else if(t+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return zCs.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,zCs.ofInner(t)}},ghC=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),nDy,HOf=()=>mhC().toString(),mhC=()=>(nDy||(nDy=new WOf)).generate();function OhC(e,t){let r=!1;return Object.assign(n=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t())},{_posthogErrorHandler:!0})}function AhC(e,t){global.process.on("uncaughtException",OhC(e,t))}function PhC(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var qCs,iDy,RCs;function whC(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return RCs&&r.length===iDy||(iDy=r.length,RCs=r.reduce((n,i)=>{qCs||(qCs={});let a=qCs[i];if(a)n[a[0]]=a[1];else{let o=e(i);for(let c=o.length-1;c>=0;c--){let s=o[c]?.filename,u=t[i];if(s&&u){n[s]=u,qCs[i]=[s,u];break}}}return n},{})),RCs}function jhC(e){return typeof Event<"u"&&TDy(e,Event)}function EhC(e){return qDy(e,"Object")}function kOf(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return TDy(e,Error)}}function TDy(e,t){try{return e instanceof t}catch{return!1}}function ShC(e){return qDy(e,"ErrorEvent")}function qDy(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function DhC(e,t,r,n){let a=n&&n.mechanism||{handled:!0,type:"generic"},o=RDy(a,r,n);return{$exception_list:await Promise.all(o.map(async s=>{let u=await RhC(e,t,s);return u.value=u.value||"",u.type=u.type||"Error",u.mechanism=a,u}))}}function RDy(e,t,r){let n=ChC(e,t,r);return n.cause?[n,...RDy(e,n.cause,r)]:[n]}function ChC(e,t,r){if(kOf(t))return t;if(e.synthetic=!0,EhC(t)){let i=IhC(t);if(i)return i;let a=MhC(t),o=r?.syntheticException||new Error(a);return o.message=a,o}let n=r?.syntheticException||new Error(t);return n.message=`${t}`,n}function IhC(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(kOf(r))return r}}function MhC(e){if("name"in e&&typeof e.name=="string"){let n=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(n+=` with message '${e.message}'`),n}else if("message"in e&&typeof e.message=="string")return e.message;let t=ThC(e);if(ShC(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=BhC(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function BhC(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function ThC(e,t=40){let r=Object.keys(qhC(e));r.sort();let n=r[0];if(!n)return"[object has no keys]";if(n.length>=t)return aDy(n,t);for(let i=r.length;i>0;i--){let a=r.slice(0,i).join(", ");if(!(a.length>t))return i===r.length?a:aDy(a,t)}return""}function aDy(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function qhC(e){return kOf(e)?{message:e.message,name:e.name,stack:e.stack,...oDy(e)}:jhC(e)?{type:e.type,target:uDy(e.target),currentTarget:uDy(e.currentTarget),...oDy(e)}:e}function oDy(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 uDy(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function RhC(e,t,r){let n={type:r.name||r.constructor.name,value:r.message},i=NhC(e,r);for(let a of t)i=await a(i);return i.length&&(n.stacktrace={frames:i,type:"raw"}),n}function NhC(e,t){return FhC(e(t.stack||"",1),e)}function FhC(e,t){let r=whC(t);return e.forEach(n=>{n.filename&&(n.chunk_id=r[n.filename])}),e}var xhC=2e3,Xeo=class e{static async captureException(t,r,n,i,a){let o={...a};i||(o.$process_person_profile=!1);let c=await DhC(this.stackParser,this.frameModifiers,r,n);t.capture({event:"$exception",distinctId:i||HOf(),properties:{...c,...o}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(AhC(this.onException.bind(this),this.onFatalError.bind(this)),PhC(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(xhC)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function zhC(e=process.argv[1]?(0,eto.dirname)(process.argv[1]):process.cwd(),t=eto.sep==="\\"){let r=t?sDy(e):e;return n=>{if(!n)return;let i=t?sDy(n):n,{dir:a,base:o,ext:c}=eto.posix.parse(i);(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 sDy(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var QCs=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)}}},FCs=new QCs(25),NDy=new QCs(20),eAf=7,QhC=1e3,LhC=1e4;async function UhC(e){let t={};for(let i=e.length-1;i>=0;i--){let a=e[i],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||GhC(o)||JhC(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(NDy.get(i))continue;let a=t[i];if(!a)continue;a.sort((f,s)=>f-s);let o=$hC(a);if(o.every(f=>KhC(i,f)))continue;let c=YhC(FCs,i,{});n.push(VhC(i,o,c))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&WhC(e,FCs),FCs.reduce(),e}function VhC(e,t,r){return new Promise(n=>{let i=(0,MDy.createReadStream)(e),a=(0,BDy.createInterface)({input:i});function o(){i.destroy(),n()}let c=0,f=0,s=t[f];if(s===void 0){o();return}let u=s[0],l=s[1];function m(){NDy.set(e,1),a.close(),a.removeAllListeners(),o()}i.on("error",m),a.on("error",m),a.on("close",o),a.on("line",A=>{if(c++,!(c<u)&&(r[c]=XhC(A,0),c>=l)){if(f===t.length-1){a.close(),a.removeAllListeners();return}f++;let P=t[f];if(P===void 0){a.close(),a.removeAllListeners();return}u=P[0],l=P[1]}})})}function WhC(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;HhC(r.lineno,r,n)}}function HhC(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=FDy(e);i<e;i++){let a=r[i];if(a===void 0){cDy(t);return}t.pre_context.push(a)}if(r[e]===void 0){cDy(t);return}t.context_line=r[e];let n=xDy(e);t.post_context=[];for(let i=e+1;i<=n;i++){let a=r[i];if(a===void 0)break;t.post_context.push(a)}}function cDy(e){delete e.pre_context,delete e.context_line,delete e.post_context}function GhC(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function JhC(e){return e.lineno!==void 0&&e.lineno>LhC||e.colno!==void 0&&e.colno>QhC}function KhC(e,t){let r=FCs.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function $hC(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=lDy(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let a=e[t+1];if(typeof a!="number")break;a<=n[1]?n[1]=a+eAf:(i.push(n),n=lDy(a)),t++}return i}function lDy(e){return[FDy(e),xDy(e)]}function FDy(e){return Math.max(1,e-eAf)}function xDy(e){return e+eAf}function YhC(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function XhC(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let a=Math.min(i+140,n);return a>n-5&&(a=n),a===n&&(i=Math.max(a-140,0)),r=r.slice(i,a),i>0&&(r=`...${r}`),a<n&&(r+="..."),r}var ZhC="4.18.0",A3e;(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"})(A3e||(A3e={}));var fDy;(function(e){e.Left="left",e.Right="right",e.Center="center"})(fDy||(fDy={}));var dDy;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(dDy||(dDy={}));var pDy;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(pDy||(pDy={}));var _Dy;(function(e){e.Html="html",e.Text="text"})(_Dy||(_Dy={}));var hDy;(function(e){e.Number="number",e.Emoji="emoji"})(hDy||(hDy={}));var yDy;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(yDy||(yDy={}));var vDy;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(vDy||(vDy={}));var bDy;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(bDy||(bDy={}));var gDy;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(gDy||(gDy={}));var khC=e=>{if("flags"in e){let t=tyC(e.flags),r=ryC(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,a])=>[i,zDy(a)])),n=Object.fromEntries(Object.entries(t).map(([i,a])=>[i,eyC(i,a,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function eyC(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 tyC=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,tAf(r)]).filter(([,t])=>t!==void 0)),ryC=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let n=t[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=t[r].metadata?.payload;return[r,n?zDy(n):void 0]}))},tAf=e=>e===void 0?void 0:e.variant??e.enabled,zDy=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},nyC=1,iyC=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"]),ayC="utf8";function oyC(e,t){if(!e||typeof e!="string"||uyC(e))throw new Error(t)}function uyC(e){return e.trim().length===0}function syC(e){return e?.replace(/\/+$/,"")}async function cyC(e,t){let r=null;for(let n=0;n<t.retryCount+1;n++){n>0&&await new Promise(i=>setTimeout(i,t.retryDelay));try{return await e()}catch(i){if(r=i,!t.retryCheck(i))throw i}}throw r}function mDy(){return new Date().getTime()}function UOf(){return new Date().toISOString()}function LCs(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function lyC(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function fyC(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 dyC(e,t=0,r){let n=fyC(e);return r?.has(n)?!1:parseInt(n,16)/4294967295<t}function ODy(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var K$o=String.fromCharCode,ADy="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",NCs={};function pyC(e,t){if(!NCs[e]){NCs[e]={};for(let r=0;r<e.length;r++)NCs[e][e.charAt(r)]=r}return NCs[e][t]}var $eo={compressToBase64:function(e){if(e==null)return"";let t=$eo._compress(e,6,function(r){return ADy.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:$eo._decompress(e.length,32,function(t){return pyC(ADy,e.charAt(t))})},compress:function(e){return $eo._compress(e,16,function(t){return K$o(t)})},_compress:function(e,t,r){if(e==null)return"";let n={},i={},a=[],o,c,f="",s="",u="",l=2,m=3,A=2,P=0,C=0,M;for(M=0;M<e.length;M+=1)if(f=e.charAt(M),Object.prototype.hasOwnProperty.call(n,f)||(n[f]=m++,i[f]=!0),s=u+f,Object.prototype.hasOwnProperty.call(n,s))u=s;else{if(Object.prototype.hasOwnProperty.call(i,u)){if(u.charCodeAt(0)<256){for(o=0;o<A;o++)P=P<<1,C==t-1?(C=0,a.push(r(P)),P=0):C++;for(c=u.charCodeAt(0),o=0;o<8;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1}else{for(c=1,o=0;o<A;o++)P=P<<1|c,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=0;for(c=u.charCodeAt(0),o=0;o<16;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1}l--,l==0&&(l=Math.pow(2,A),A++),delete i[u]}else for(c=n[u],o=0;o<A;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1;l--,l==0&&(l=Math.pow(2,A),A++),n[s]=m++,u=String(f)}if(u!==""){if(Object.prototype.hasOwnProperty.call(i,u)){if(u.charCodeAt(0)<256){for(o=0;o<A;o++)P=P<<1,C==t-1?(C=0,a.push(r(P)),P=0):C++;for(c=u.charCodeAt(0),o=0;o<8;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1}else{for(c=1,o=0;o<A;o++)P=P<<1|c,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=0;for(c=u.charCodeAt(0),o=0;o<16;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1}l--,l==0&&(l=Math.pow(2,A),A++),delete i[u]}else for(c=n[u],o=0;o<A;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1;l--,l==0&&(l=Math.pow(2,A),A++)}for(c=2,o=0;o<A;o++)P=P<<1|c&1,C==t-1?(C=0,a.push(r(P)),P=0):C++,c=c>>1;for(;;)if(P=P<<1,C==t-1){a.push(r(P));break}else C++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:$eo._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let n=[],i=[],a={val:r(0),position:t,index:1},o=4,c=4,f=3,s="",u,l,m,A,P,C,M;for(u=0;u<3;u+=1)n[u]=u;for(m=0,P=Math.pow(2,2),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;switch(m){case 0:for(m=0,P=Math.pow(2,8),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;M=K$o(m);break;case 1:for(m=0,P=Math.pow(2,16),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;M=K$o(m);break;case 2:return""}for(n[3]=M,l=M,i.push(M);;){if(a.index>e)return"";for(m=0,P=Math.pow(2,f),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;switch(M=m){case 0:for(m=0,P=Math.pow(2,8),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;n[c++]=K$o(m),M=c-1,o--;break;case 1:for(m=0,P=Math.pow(2,16),C=1;C!=P;)A=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),m|=(A>0?1:0)*C,C<<=1;n[c++]=K$o(m),M=c-1,o--;break;case 2:return i.join("")}if(o==0&&(o=Math.pow(2,f),f++),n[M])s=n[M];else if(M===c)s=l+l.charAt(0);else return null;i.push(s),n[c++]=l+s.charAt(0),o--,l=s,o==0&&(o=Math.pow(2,f),f++)}}},GOf=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(n=>n!==r)}}emit(t,r){for(let n of this.events[t]||[])n(r);for(let n of this.events["*"]||[])n(t,r)}},Zeo=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()}},$$o=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function PDy(e){if(e instanceof Zeo){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 VOf(e){return typeof e=="object"&&(e instanceof Zeo||e instanceof $$o)}function wDy(e){return typeof e=="object"&&e instanceof Zeo&&e.status===413}var JOf;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(JOf||(JOf={}));var KOf=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new GOf,this._isInitialized=!1,oyC(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=syC(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:VOf},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(A3e.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(A3e.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(A3e.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>console.log("PostHog Debug",n,i));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=HOf();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",a,i)})}async captureStatelessImmediate(t,r,n,i){let a=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",a,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",a,i)})}async aliasStatelessImmediate(t,r,n,i){let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",a,i)}groupIdentifyStateless(t,r,n,i,a,o){this.wrap(()=>{let c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...o||{}}});this.enqueue("capture",c,i)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(i=>i.json()).catch(i=>{this.logMsgIfDebug(()=>console.error("Remote config could not be loaded",i)),this._events.emit("error",i)})}async getDecide(t,r={},n={},i={},a={}){await this._initPromise;let c=dyC(this.apiKey,nyC,iyC)?`${this.host}/flags/?v=2`:`${this.host}/decide/?v=4`,f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...a})};return this.logMsgIfDebug(()=>console.log("PostHog Debug","Decide URL",c)),this.fetchWithRetry(c,f,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(s=>s.json()).then(s=>khC(s)).catch(s=>{this._events.emit("error",s)})}async getFeatureFlagStateless(t,r,n={},i={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,n,i,a,o);if(c===void 0)return{response:void 0,requestId:void 0};let f=tAf(c.response);return f===void 0&&(f=!1),{response:f,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,n,i,a,o,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId}}async getFeatureFlagPayloadStateless(t,r,n={},i={},a={},o){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,n,i,a,o,[t]);if(!c)return;let f=c[t];return f===void 0?null:f}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},a,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a,o)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},a,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,a,o)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},a,o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(t,r,n,i,a,o);return c?{flags:c.featureFlags,payloads:c.featureFlagPayloads,requestId:c.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},a,o){await this._initPromise;let c={};(a??this.disableGeoip)&&(c.geoip_disable=!0),o&&(c.flag_keys_to_evaluate=o);let f=await this.getDecide(t,r,n,i,c);if(f!==void 0)return f.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),f.quotaLimited?.includes(JOf.FeatureFlags)?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:f?.requestId}):f}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this.logMsgIfDebug(()=>console.log("PostHog Debug","Loading surveys is disabled.")),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(t,r).then(a=>{if(a.status!==200||!a.json){let o=`Surveys API could not be loaded: ${a.status}`,c=new Error(o);this.logMsgIfDebug(()=>console.error(c)),this._events.emit("error",new Error(o));return}return a.json()}).catch(a=>{this.logMsgIfDebug(()=>console.error("Surveys API could not be loaded",a)),this._events.emit("error",a)}))?.surveys;return i&&this.logMsgIfDebug(()=>console.log("PostHog Debug","Surveys fetched from API: ",JSON.stringify(i))),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(A3e.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(A3e.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(A3e.Props,this.props)})}enqueue(t,r,n){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let i=this.prepareMessage(t,r,n),a=this.getPersistedProperty(A3e.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),a.push({message:i}),this.setPersistedProperty(A3e.Queue,a),this._events.emit(t,i),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=LCs(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized||await this._initPromise,this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let i={api_key:this.apiKey,batch:[this.prepareMessage(t,r,n)],sent_at:UOf()};this.historicalMigration&&(i.historical_migration=!0);let a=JSON.stringify(i),o=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${mDy()}&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($eo.compressToBase64(a))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:a};try{await this.fetchWithRetry(o,c)}catch(f){this._events.emit("error",f)}}prepareMessage(t,r,n){let i={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:UOf(),uuid:n?.uuid?n.uuid:HOf()};return(n?.disableGeoip??this.disableGeoip)&&(i.properties||(i.properties={}),i.properties.$geoip_disable=!0),i.distinctId&&(i.distinct_id=i.distinctId,delete i.distinctId),i}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await PDy(t)})}async flush(){let t=ODy([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),ODy([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(A3e.Queue)||[];if(!t.length)return;let r=[],n=t.length;for(;t.length>0&&r.length<n;){let i=t.slice(0,this.maxBatchSize),a=i.map(m=>m.message),o=()=>{let A=(this.getPersistedProperty(A3e.Queue)||[]).slice(i.length);this.setPersistedProperty(A3e.Queue,A),t=A},c={api_key:this.apiKey,batch:a,sent_at:UOf()};this.historicalMigration&&(c.historical_migration=!0);let f=JSON.stringify(c),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${mDy()}&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($eo.compressToBase64(f))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:f},l={retryCheck:m=>wDy(m)?!1:VOf(m)};try{await this.fetchWithRetry(s,u,l)}catch(m){if(wDy(m)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this.logMsgIfDebug(()=>console.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`));continue}throw m instanceof $$o||o(),this._events.emit("error",m),m}o(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,n,i){var a;(a=AbortSignal).timeout??(a.timeout=function(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,ayC)}catch{c=new TextEncoder().encode(o).length}return await cyC(async()=>{let f=null;try{f=await this.fetch(t,{signal:AbortSignal.timeout(i??this.requestTimeout),...r})}catch(u){throw new $$o(u)}if(!(r.mode==="no-cors")&&(f.status<200||f.status>=400))throw new Zeo(f,c);return f},{...this._retryOptions,...n})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let n=async()=>{try{for(await Promise.all(Object.values(this.pendingPromises));!((this.getPersistedProperty(A3e.Queue)||[]).length===0||(await this.flush(),r)););}catch(i){if(!VOf(i))throw i;await PDy(i)}};return Promise.race([new Promise((i,a)=>{LCs(()=>{this.logMsgIfDebug(()=>console.error("Timed out while shutting down PostHog")),r=!0,a("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),n()])}async shutdown(t=3e4){return this.shutdownPromise?this.logMsgIfDebug(()=>console.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup")):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}},$Of=lyC();if(!$Of){let e=tDy();$Of=async(t,r)=>{let n=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:n.status,text:async()=>n.data,json:async()=>n.data}}}var QDy=$Of,UCs=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()}},LDy=new UCs(async()=>{try{return await import("crypto")}catch{return}});async function _yC(){return await LDy.getValue()}var hyC=new UCs(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await LDy.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function yyC(){return await hyC.getValue()}async function vyC(e){let t=await _yC();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await yyC();if(r){let n=await r.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}throw new Error("No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API")}var byC=60*1e3,gyC=1152921504606847e3,myC=["is_not"],Yeo=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},dse=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},YOf=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:a,customHeaders:o,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=a,this.poller=void 0,this.fetch=c.fetch||QDy,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,n={},i={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;for(let f of this.featureFlags)if(t===f.key){c=f;break}if(c!==void 0)try{o=await this.computeFlagLocally(c,r,n,i,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(f){f instanceof dse?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${f}`)):f instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${f}`))}return o}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let n;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),n==null)return null;try{return JSON.parse(n)}catch{return n}}}async getAllFlagsAndPayloads(t,r={},n={},i={}){await this.loadFeatureFlags();let a={},o={},c=this.featureFlags.length==0;return await Promise.all(this.featureFlags.map(async f=>{try{let s=await this.computeFlagLocally(f,t,r,n,i);a[f.key]=s;let u=await this.computeFeatureFlagPayloadLocally(f.key,s);u&&(o[f.key]=u)}catch(s){s instanceof dse||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,n={},i={},a={}){if(t.ensure_experience_continuity)throw new dse("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 dse("Flag has unknown group type index");if(!(f in n))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[f];return await this.matchFeatureFlagProperties(t,n[f],s)}else return await this.matchFeatureFlagProperties(t,r,i)}async matchFeatureFlagProperties(t,r,n){let i=t.filters||{},a=i.groups||[],o=!1,c,f=[...a].sort((s,u)=>{let l=!!s.variant,m=!!u.variant;return l&&m?0:l?-1:m?1:0});for(let s of f)try{if(await this.isConditionMatch(t,r,s,n)){let u=s.variant,l=i.multivariate?.variants||[];u&&l.some(m=>m.key===u)?c=u:c=await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof dse)o=!0;else throw u}if(c!==void 0)return c;if(o)throw new dse("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i){let a=n.rollout_percentage,o=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let f=c.type,s=!1;if(f==="cohort"?s=VDy(c,i,this.cohorts,this.debugMode):s=UDy(c,i,o),!s)return!1}if(a==null)return!0}return!(a!=null&&await jDy(t.key,r)>a/100)}async getMatchingVariant(t,r){let n=await jDy(t.key,r,"variant"),i=this.variantLookupTable(t).find(a=>n>=a.valueMin&&n<a.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{i=n+c.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:c.key}),n=i}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(byC,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 Yeo(`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 Yeo(`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 Yeo(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r)){this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));return}this.featureFlags=r.flags??[],this.featureFlagsByKey=this.featureFlags.reduce((n,i)=>(n[i.key]=i,n),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||{},this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof Yeo&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET"){return{method:t,headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions(),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=LCs(()=>{i.abort()},this.timeout),r.signal=i.signal}try{return await this.fetch(t,r)}finally{clearTimeout(n)}}stopPoller(){clearTimeout(this.poller)}_requestRemoteConfigPayload(t){let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config/`,n=this.getPersonalApiKeyRequestOptions(),i=null;if(this.timeout&&typeof this.timeout=="number"){let a=new AbortController;i=LCs(()=>{a.abort()},this.timeout),n.signal=a.signal}try{return this.fetch(r,n)}finally{clearTimeout(i)}}};async function jDy(e,t,r=""){let n=await vyC(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/gyC}function UDy(e,t,r){let n=e.key,i=e.value,a=e.operator||"exact";if(n in t){if(a==="is_not_set")throw new dse("Operator is_not_set is not supported")}else throw new dse(`Property ${n} not found in propertyValues`);let o=t[n];if(o==null&&!myC.includes(a))return r&&r(`Property ${n} 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(i,o);case"is_not":return!c(i,o);case"is_set":return n in t;case"icontains":return String(o).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(i).toLowerCase());case"regex":return EDy(String(i))&&String(o).match(String(i))!==null;case"not_regex":return EDy(String(i))&&String(o).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof i=="number"?i:null;if(typeof i=="string")try{s=parseFloat(i)}catch{}return s!=null&&o!=null?typeof o=="string"?f(o,String(i),a):f(o,s,a):f(String(o),String(i),a)}case"is_date_after":case"is_date_before":{let s=OyC(String(i));if(s==null&&(s=SDy(i)),s==null)throw new dse(`Invalid date: ${i}`);let u=SDy(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new dse(`Unknown operator: ${a}`)}}function VDy(e,t,r,n=!1){let i=String(e.value);if(!(i in r))throw new dse("can't match cohort without a given cohort property value");let a=r[i];return WDy(a,t,r,n)}function WDy(e,t,r,n=!1){if(!e)return!0;let i=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let f=WDy(c,t,r,n);if(i==="AND"){if(!f)return!1}else if(f)return!0}catch(f){if(f instanceof dse)n&&console.debug(`Failed to compute property ${c} locally: ${f}`),o=!0;else throw f}if(o)throw new dse("Can't match cohort without a given cohort property value");return i==="AND"}else{for(let c of a)try{let f;c.type==="cohort"?f=VDy(c,t,r,n):f=UDy(c,t);let s=c.negation||!1;if(i==="AND"){if(!f&&!s||f&&s)return!1}else if(f&&!s||!f&&s)return!0}catch(f){if(f instanceof dse)n&&console.debug(`Failed to compute property ${c} locally: ${f}`),o=!0;else throw f}if(o)throw new dse("can't match cohort without a given cohort property value");return i==="AND"}}function EDy(e){try{return new RegExp(e),!0}catch{return!1}}function SDy(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 dse(`${e} is in an invalid date format`)}else throw new dse(`The date provided ${e} must be a string, number, or date object`)}function OyC(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let a=r.groups.interval;if(a=="h")n.setUTCHours(n.getUTCHours()-i);else if(a=="d")n.setUTCDate(n.getUTCDate()-i);else if(a=="w")n.setUTCDate(n.getUTCDate()-i*7);else if(a=="m")n.setUTCMonth(n.getUTCMonth()-i);else if(a=="y")n.setUTCFullYear(n.getUTCFullYear()-i);else return null;return n}else return null}var XOf=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},AyC=100,DDy=30*1e3,PyC=50*1e3,ZOf=class extends KOf{constructor(t,r={}){if(super(t,r),this._memoryStorage=new XOf,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,AyC):DDy,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 YOf({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders()})}this.errorTracking=new Xeo(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||PyC}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):QDy(t,r)}getLibraryVersion(){return ZhC}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:n,properties:i,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:f,uuid:s}=t,u=A=>{super.captureStateless(r,n,A,{timestamp:c,disableGeoip:f,uuid:s})},l=async(A,P,C)=>(await super.getFeatureFlagsStateless(A,P,void 0,void 0,C)).flags,m=Promise.resolve().then(async()=>{if(o)return await l(r,a,f);if(n==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let A={};for(let[P,C]of Object.entries(a||{}))A[P]=String(C);return await this.getAllFlags(r,{groups:A,disableGeoip:f,onlyEvaluateLocally:!0})}return{}}).then(A=>{let P={};if(A)for(let[M,T]of Object.entries(A))P[`$feature/${M}`]=T;let C=Object.keys(A||{}).filter(M=>A?.[M]!==!1).sort();return C.length>0&&(P.$active_feature_flags=C),P}).catch(()=>({})).then(A=>{u({...A,...i,$groups:a})});this.addPendingPromise(m)}async captureImmediate(t){typeof t=="string"&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:n,properties:i,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:f,uuid:s}=t,u=A=>super.captureStatelessImmediate(r,n,A,{timestamp:c,disableGeoip:f,uuid:s}),l=async(A,P,C)=>(await super.getFeatureFlagsStateless(A,P,void 0,void 0,C)).flags;await Promise.resolve().then(async()=>{if(o)return await l(r,a,f);if(n==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let A={};for(let[P,C]of Object.entries(a||{}))A[P]=String(C);return await this.getAllFlags(r,{groups:A,disableGeoip:f,onlyEvaluateLocally:!0})}return{}}).then(A=>{let P={};if(A)for(let[M,T]of Object.entries(A))P[`$feature/${M}`]=T;let C=Object.keys(A||{}).filter(M=>A?.[M]!==!1).sort();return C.length>0&&(P.$active_feature_flags=C),P}).catch(()=>({})).then(A=>{u({...A,...i,$groups:a})})}identify({distinctId:t,properties:r,disableGeoip:n}){let i=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;super.identifyStateless(t,{$set:a,$set_once:i},{disableGeoip:n})}async identifyImmediate({distinctId:t,properties:r,disableGeoip:n}){let i=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;await super.identifyStatelessImmediate(t,{$set:a,$set_once:i},{disableGeoip:n})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=DDy){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(n),i(),r(a>0)})})}async getFeatureFlag(t,r,n){let{groups:i,disableGeoip:a}=n||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:f,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,i,f,s);f=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,i,f,s),m=l!==void 0,A,P;if(!m&&!o){let M=await super.getFeatureFlagDetailStateless(t,r,i,f,s,a);if(M===void 0)return;P=M.response,l=tAf(P),A=M?.requestId}let C=`${t}_${l}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(C))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(C):this.distinctIdHasSentFlagCalls[r]=[C],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,$feature_flag_id:P?.metadata?.id,$feature_flag_version:P?.metadata?.version,$feature_flag_reason:P?.reason?.description??P?.reason?.code,locally_evaluated:m,[`$feature/${t}`]:l,$feature_flag_request_id:A},groups:i,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,n,i){let{groups:a,disableGeoip:o}=i||{},{onlyEvaluateLocally:c,sendFeatureFlagEvents:f,personProperties:s,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,a,s,u);s=l.allPersonProperties,u=l.allGroupProperties;let m;return this.featureFlagsPoller!==void 0&&(n||(n=await this.getFeatureFlag(t,r,{...i,onlyEvaluateLocally:!0,sendFeatureFlagEvents:!1})),n&&(m=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,n))),c==null&&(c=!1),f==null&&(f=!0),c==null&&(c=!1),!(m!==void 0)&&!c&&(m=await super.getFeatureFlagPayloadStateless(t,r,a,s,u,o)),m}async getRemoteConfigPayload(t){return(await this.featureFlagsPoller?._requestRemoteConfigPayload(t))?.json()}async isFeatureEnabled(t,r,n){let i=await this.getFeatureFlag(t,r,n);if(i!==void 0)return!!i||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:n,disableGeoip:i}=r||{},{onlyEvaluateLocally:a,personProperties:o,groupProperties:c}=r||{},f=this.addLocalPersonAndGroupProperties(t,n,o,c);o=f.allPersonProperties,c=f.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,n,o,c),u={},l={},m=!0;if(s&&(u=s.response,l=s.payloads,m=s.fallbackToDecide),m&&!a){let A=await super.getFeatureFlagsAndPayloadsStateless(t,n,o,c,i);u={...u,...A.flags||{}},l={...l,...A.payloads||{}}}return{featureFlags:u,featureFlagPayloads:l}}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:a}){super.groupIdentifyStateless(t,r,n,{disableGeoip:a},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(),super._shutdown(t)}addLocalPersonAndGroupProperties(t,r,n,i){let a={distinct_id:t,...n||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...i?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,n){let i=new Error("PostHog syntheticException");Xeo.captureException(this,t,{syntheticException:i},r,n)}},CDy=/\(error: (.*)\)/,HDy=50,GDy="?";function wyC(e){let t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return n=>{let i=n.match(r);if(i){let a,o,c,f,s;if(i[1]){c=i[1];let m=c.lastIndexOf(".");if(c[m-1]==="."&&m--,m>0){a=c.slice(0,m),o=c.slice(m+1);let A=a.indexOf(".Module");A>0&&(c=c.slice(A+1),a=a.slice(0,A))}f=void 0}o&&(f=a,s=o),o==="<anonymous>"&&(s=void 0,c=void 0),c===void 0&&(s=s||GDy,c=f?`${f}.${s}`:s);let u=i[2]?.startsWith("file://")?i[2].slice(7):i[2],l=i[5]==="native";return u?.match(/\/[A-Z]:/)&&(u=u.slice(1)),!u&&i[5]&&!l&&(u=i[5]),{filename:u?decodeURI(u):void 0,module:e?e(u):void 0,function:c,lineno:IDy(i[3]),colno:IDy(i[4]),in_app:jyC(u||"",l),platform:"node:javascript"}}if(n.match(t))return{filename:n,platform:"node:javascript"}}}function jyC(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 IDy(e){return parseInt(e||"",10)||void 0}function EyC(e){return[90,wyC(e)]}function SyC(e){let r=[EyC(e)].sort((n,i)=>n[0]-i[0]).map(n=>n[1]);return(n,i=0)=>{let a=[],o=n.split(`
|
|
2166
|
-
`);for(let c=i;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let s=CDy.test(f)?f.replace(CDy,"$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>=HDy)break}}return DyC(a)}}function DyC(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,HDy).map(r=>({...r,filename:r.filename||CyC(t).filename,function:r.function||GDy}))}function CyC(e){return e[e.length-1]||{}}Xeo.stackParser=SyC(zhC());Xeo.frameModifiers=[UhC];var keo=class extends ZOf{getLibraryId(){return"posthog-node"}};var VCs=class{posthog;constructor({posthogApiKey:t}){this.posthog=new keo(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.101.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var Y$o=class{async sendEvent(){}async identify(){}async flush(){}};var tto=require("fs/promises"),YDy=require("os"),XDy=require("path");var JDy=Gi(require("crypto")),HCs=new Uint8Array(256),WCs=HCs.length;function rAf(){return WCs>HCs.length-16&&(JDy.default.randomFillSync(HCs),WCs=0),HCs.slice(WCs,WCs+=16)}var zbe=[];for(let e=0;e<256;++e)zbe.push((e+256).toString(16).slice(1));function KDy(e,t=0){return zbe[e[t+0]]+zbe[e[t+1]]+zbe[e[t+2]]+zbe[e[t+3]]+"-"+zbe[e[t+4]]+zbe[e[t+5]]+"-"+zbe[e[t+6]]+zbe[e[t+7]]+"-"+zbe[e[t+8]]+zbe[e[t+9]]+"-"+zbe[e[t+10]]+zbe[e[t+11]]+zbe[e[t+12]]+zbe[e[t+13]]+zbe[e[t+14]]+zbe[e[t+15]]}var $Dy=Gi(require("crypto")),nAf={randomUUID:$Dy.default.randomUUID};function IyC(e,t,r){if(nAf.randomUUID&&!t&&!e)return nAf.randomUUID();e=e||{};let n=e.random||(e.rng||rAf)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(let i=0;i<16;++i)t[r+i]=n[i];return t}return KDy(n)}var yit=IyC;var MyC="id",ByC=".fern",X$o=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new keo(r),this.userId=t==null?void 0:Ohf(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.101.0",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=kl(L_.of((0,YDy.homedir)()),ds.of(ByC),ds.of(MyC));await Qv(t)||(await(0,tto.mkdir)((0,XDy.dirname)(t),{recursive:!0}),await(0,tto.writeFile)(t,yit())),this.persistedDistinctId=(await(0,tto.readFile)(t)).toString()}return this.persistedDistinctId}};var iAf;async function rto(){return iAf==null&&(iAf=await TyC()),iAf}async function TyC(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new Y$o;let r=await nws();return r!=null?new X$o({token:r,posthogApiKey:e}):await rka()!=null?new VCs({posthogApiKey:e}):new X$o({token:void 0,posthogApiKey:e})}catch{return new Y$o}}function Z$o(e,t){return function(){return e.apply(t,arguments)}}var{toString:qyC}=Object.prototype,{getPrototypeOf:oAf}=Object,{iterator:JCs,toStringTag:kDy}=Symbol,KCs=(e=>t=>{let r=qyC.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),oRr=e=>(e=e.toLowerCase(),t=>KCs(t)===e),$Cs=e=>t=>typeof t===e,{isArray:ito}=Array,nto=$Cs("undefined");function k$o(e){return e!==null&&!nto(e)&&e.constructor!==null&&!nto(e.constructor)&&P3e(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var eCy=oRr("ArrayBuffer");function RyC(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&eCy(e.buffer),t}var NyC=$Cs("string"),P3e=$Cs("function"),tCy=$Cs("number"),eYo=e=>e!==null&&typeof e=="object",FyC=e=>e===!0||e===!1,GCs=e=>{if(KCs(e)!=="object")return!1;let t=oAf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(kDy in e)&&!(JCs in e)},xyC=e=>{if(!eYo(e)||k$o(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},zyC=oRr("Date"),QyC=oRr("File"),LyC=oRr("Blob"),UyC=oRr("FileList"),VyC=e=>eYo(e)&&P3e(e.pipe),WyC=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||P3e(e.append)&&((t=KCs(e))==="formdata"||t==="object"&&P3e(e.toString)&&e.toString()==="[object FormData]"))},HyC=oRr("URLSearchParams"),[GyC,JyC,KyC,$yC]=["ReadableStream","Request","Response","Headers"].map(oRr),YyC=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function tYo(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),ito(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(k$o(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(n=0;n<o;n++)c=a[n],t.call(null,e[c],c,e)}}function rCy(e,t){if(k$o(e))return null;t=t.toLowerCase();let r=Object.keys(e),n=r.length,i;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}var Pla=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,nCy=e=>!nto(e)&&e!==Pla;function aAf(){let{caseless:e,skipUndefined:t}=nCy(this)&&this||{},r={},n=(i,a)=>{let o=e&&rCy(r,a)||a;GCs(r[o])&&GCs(i)?r[o]=aAf(r[o],i):GCs(i)?r[o]=aAf({},i):ito(i)?r[o]=i.slice():(!t||!nto(i))&&(r[o]=i)};for(let i=0,a=arguments.length;i<a;i++)arguments[i]&&tYo(arguments[i],n);return r}var XyC=(e,t,r,{allOwnKeys:n}={})=>(tYo(t,(i,a)=>{r&&P3e(i)?e[a]=Z$o(i,r):e[a]=i},{allOwnKeys:n}),e),ZyC=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),kyC=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},evC=(e,t,r,n)=>{let i,a,o,c={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),a=i.length;a-- >0;)o=i[a],(!n||n(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&oAf(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},tvC=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let n=e.indexOf(t,r);return n!==-1&&n===r},rvC=e=>{if(!e)return null;if(ito(e))return e;let t=e.length;if(!tCy(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},nvC=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&oAf(Uint8Array)),ivC=(e,t)=>{let n=(e&&e[JCs]).call(e),i;for(;(i=n.next())&&!i.done;){let a=i.value;t.call(e,a[0],a[1])}},avC=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},ovC=oRr("HTMLFormElement"),uvC=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),ZDy=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),svC=oRr("RegExp"),iCy=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};tYo(r,(i,a)=>{let o;(o=t(i,a,e))!==!1&&(n[a]=o||i)}),Object.defineProperties(e,n)},cvC=e=>{iCy(e,(t,r)=>{if(P3e(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(P3e(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},lvC=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return ito(e)?n(e):n(String(e).split(t)),r},fvC=()=>{},dvC=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function pvC(e){return!!(e&&P3e(e.append)&&e[kDy]==="FormData"&&e[JCs])}var _vC=e=>{let t=new Array(10),r=(n,i)=>{if(eYo(n)){if(t.indexOf(n)>=0)return;if(k$o(n))return n;if(!("toJSON"in n)){t[i]=n;let a=ito(n)?[]:{};return tYo(n,(o,c)=>{let f=r(o,i+1);!nto(f)&&(a[c]=f)}),t[i]=void 0,a}}return n};return r(e,0)},hvC=oRr("AsyncFunction"),yvC=e=>e&&(eYo(e)||P3e(e))&&P3e(e.then)&&P3e(e.catch),aCy=((e,t)=>e?setImmediate:t?((r,n)=>(Pla.addEventListener("message",({source:i,data:a})=>{i===Pla&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),Pla.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",P3e(Pla.postMessage)),vvC=typeof queueMicrotask<"u"?queueMicrotask.bind(Pla):typeof process<"u"&&process.nextTick||aCy,bvC=e=>e!=null&&P3e(e[JCs]),Zf={isArray:ito,isArrayBuffer:eCy,isBuffer:k$o,isFormData:WyC,isArrayBufferView:RyC,isString:NyC,isNumber:tCy,isBoolean:FyC,isObject:eYo,isPlainObject:GCs,isEmptyObject:xyC,isReadableStream:GyC,isRequest:JyC,isResponse:KyC,isHeaders:$yC,isUndefined:nto,isDate:zyC,isFile:QyC,isBlob:LyC,isRegExp:svC,isFunction:P3e,isStream:VyC,isURLSearchParams:HyC,isTypedArray:nvC,isFileList:UyC,forEach:tYo,merge:aAf,extend:XyC,trim:YyC,stripBOM:ZyC,inherits:kyC,toFlatObject:evC,kindOf:KCs,kindOfTest:oRr,endsWith:tvC,toArray:rvC,forEachEntry:ivC,matchAll:avC,isHTMLForm:ovC,hasOwnProperty:ZDy,hasOwnProp:ZDy,reduceDescriptors:iCy,freezeMethods:cvC,toObjectSet:lvC,toCamelCase:uvC,noop:fvC,toFiniteNumber:dvC,findKey:rCy,global:Pla,isContextDefined:nCy,isSpecCompliantForm:pvC,toJSONObject:_vC,isAsyncFn:hvC,isThenable:yvC,setImmediate:aCy,asap:vvC,isIterable:bvC};function ato(e,t,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Zf.inherits(ato,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:Zf.toJSONObject(this.config),code:this.code,status:this.status}}});var oCy=ato.prototype,uCy={};["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=>{uCy[e]={value:e}});Object.defineProperties(ato,uCy);Object.defineProperty(oCy,"isAxiosError",{value:!0});ato.from=(e,t,r,n,i,a)=>{let o=Object.create(oCy);Zf.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 ato.call(o,c,f,r,n,i),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var xm=ato;var sCy=Gi(oca(),1),YCs=sCy.default;function uAf(e){return Zf.isPlainObject(e)||Zf.isArray(e)}function lCy(e){return Zf.endsWith(e,"[]")?e.slice(0,-2):e}function cCy(e,t,r){return e?e.concat(t).map(function(i,a){return i=lCy(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function gvC(e){return Zf.isArray(e)&&!e.some(uAf)}var mvC=Zf.toFlatObject(Zf,{},null,function(t){return/^is[A-Z]/.test(t)});function OvC(e,t,r){if(!Zf.isObject(e))throw new TypeError("target must be an object");t=t||new(YCs||FormData),r=Zf.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(C,M){return!Zf.isUndefined(M[C])});let n=r.metaTokens,i=r.visitor||u,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&Zf.isSpecCompliantForm(t);if(!Zf.isFunction(i))throw new TypeError("visitor must be a function");function s(P){if(P===null)return"";if(Zf.isDate(P))return P.toISOString();if(Zf.isBoolean(P))return P.toString();if(!f&&Zf.isBlob(P))throw new xm("Blob is not supported. Use a Buffer instead.");return Zf.isArrayBuffer(P)||Zf.isTypedArray(P)?f&&typeof Blob=="function"?new Blob([P]):Buffer.from(P):P}function u(P,C,M){let T=P;if(P&&!M&&typeof P=="object"){if(Zf.endsWith(C,"{}"))C=n?C:C.slice(0,-2),P=JSON.stringify(P);else if(Zf.isArray(P)&&gvC(P)||(Zf.isFileList(P)||Zf.endsWith(C,"[]"))&&(T=Zf.toArray(P)))return C=lCy(C),T.forEach(function(U,q){!(Zf.isUndefined(U)||U===null)&&t.append(o===!0?cCy([C],q,a):o===null?C:C+"[]",s(U))}),!1}return uAf(P)?!0:(t.append(cCy(M,C,a),s(P)),!1)}let l=[],m=Object.assign(mvC,{defaultVisitor:u,convertValue:s,isVisitable:uAf});function A(P,C){if(!Zf.isUndefined(P)){if(l.indexOf(P)!==-1)throw Error("Circular reference detected in "+C.join("."));l.push(P),Zf.forEach(P,function(T,z){(!(Zf.isUndefined(T)||T===null)&&i.call(t,T,Zf.isString(z)?z.trim():z,C,m))===!0&&A(T,C?C.concat(z):[z])}),l.pop()}}if(!Zf.isObject(e))throw new TypeError("data must be an object");return A(e),t}var X7i=OvC;function fCy(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function dCy(e,t){this._pairs=[],e&&X7i(e,this,t)}var pCy=dCy.prototype;pCy.append=function(t,r){this._pairs.push([t,r])};pCy.toString=function(t){let r=t?function(n){return t.call(this,n,fCy)}:fCy;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var _Cy=dCy;function AvC(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function wla(e,t,r){if(!t)return e;let n=r&&r.encode||AvC;Zf.isFunction(r)&&(r={serialize:r});let i=r&&r.serialize,a;if(i?a=i(t,r):a=Zf.isURLSearchParams(t)?t.toString():new _Cy(t,r).toString(n),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var sAf=class{constructor(){this.handlers=[]}use(t,r,n){return this.handlers.push({fulfilled:t,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){Zf.forEach(this.handlers,function(n){n!==null&&t(n)})}},cAf=sAf;var oto={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var bCy=Gi(require("crypto"),1);var hCy=Gi(require("url"),1),yCy=hCy.default.URLSearchParams;var lAf="abcdefghijklmnopqrstuvwxyz",vCy="0123456789",gCy={DIGIT:vCy,ALPHA:lAf,ALPHA_DIGIT:lAf+lAf.toUpperCase()+vCy},PvC=(e=16,t=gCy.ALPHA_DIGIT)=>{let r="",{length:n}=t,i=new Uint32Array(e);bCy.default.randomFillSync(i);for(let a=0;a<e;a++)r+=t[i[a]%n];return r},mCy={isNode:!0,classes:{URLSearchParams:yCy,FormData:YCs,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:gCy,generateString:PvC,protocols:["http","https","file","data"]};var pAf={};yf(pAf,{hasBrowserEnv:()=>dAf,hasStandardBrowserEnv:()=>wvC,hasStandardBrowserWebWorkerEnv:()=>jvC,navigator:()=>fAf,origin:()=>EvC});var dAf=typeof window<"u"&&typeof document<"u",fAf=typeof navigator=="object"&&navigator||void 0,wvC=dAf&&(!fAf||["ReactNative","NativeScript","NS"].indexOf(fAf.product)<0),jvC=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",EvC=dAf&&window.location.href||"http://localhost";var n8={...pAf,...mCy};function _Af(e,t){return X7i(e,new n8.classes.URLSearchParams,{visitor:function(r,n,i,a){return n8.isNode&&Zf.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function SvC(e){return Zf.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function DvC(e){let t={},r=Object.keys(e),n,i=r.length,a;for(n=0;n<i;n++)a=r[n],t[a]=e[a];return t}function CvC(e){function t(r,n,i,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),f=a>=r.length;return o=!o&&Zf.isArray(i)?i.length:o,f?(Zf.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!c):((!i[o]||!Zf.isObject(i[o]))&&(i[o]=[]),t(r,n,i[o],a)&&Zf.isArray(i[o])&&(i[o]=DvC(i[o])),!c)}if(Zf.isFormData(e)&&Zf.isFunction(e.entries)){let r={};return Zf.forEachEntry(e,(n,i)=>{t(SvC(n),i,r,0)}),r}return null}var XCs=CvC;function IvC(e,t,r){if(Zf.isString(e))try{return(t||JSON.parse)(e),Zf.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var hAf={transitional:oto,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,a=Zf.isObject(t);if(a&&Zf.isHTMLForm(t)&&(t=new FormData(t)),Zf.isFormData(t))return i?JSON.stringify(XCs(t)):t;if(Zf.isArrayBuffer(t)||Zf.isBuffer(t)||Zf.isStream(t)||Zf.isFile(t)||Zf.isBlob(t)||Zf.isReadableStream(t))return t;if(Zf.isArrayBufferView(t))return t.buffer;if(Zf.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(n.indexOf("application/x-www-form-urlencoded")>-1)return _Af(t,this.formSerializer).toString();if((c=Zf.isFileList(t))||n.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return X7i(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),IvC(t)):t}],transformResponse:[function(t){let r=this.transitional||hAf.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(Zf.isResponse(t)||Zf.isReadableStream(t))return t;if(t&&Zf.isString(t)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?xm.from(c,xm.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:n8.classes.FormData,Blob:n8.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Zf.forEach(["delete","get","head","post","put","patch"],e=>{hAf.headers[e]={}});var uto=hAf;var MvC=Zf.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"]),OCy=e=>{let t={},r,n,i;return e&&e.split(`
|
|
2166
|
+
`);for(let c=i;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let s=CDy.test(f)?f.replace(CDy,"$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>=HDy)break}}return DyC(a)}}function DyC(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,HDy).map(r=>({...r,filename:r.filename||CyC(t).filename,function:r.function||GDy}))}function CyC(e){return e[e.length-1]||{}}Xeo.stackParser=SyC(zhC());Xeo.frameModifiers=[UhC];var keo=class extends ZOf{getLibraryId(){return"posthog-node"}};var VCs=class{posthog;constructor({posthogApiKey:t}){this.posthog=new keo(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.101.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var Y$o=class{async sendEvent(){}async identify(){}async flush(){}};var tto=require("fs/promises"),YDy=require("os"),XDy=require("path");var JDy=Gi(require("crypto")),HCs=new Uint8Array(256),WCs=HCs.length;function rAf(){return WCs>HCs.length-16&&(JDy.default.randomFillSync(HCs),WCs=0),HCs.slice(WCs,WCs+=16)}var zbe=[];for(let e=0;e<256;++e)zbe.push((e+256).toString(16).slice(1));function KDy(e,t=0){return zbe[e[t+0]]+zbe[e[t+1]]+zbe[e[t+2]]+zbe[e[t+3]]+"-"+zbe[e[t+4]]+zbe[e[t+5]]+"-"+zbe[e[t+6]]+zbe[e[t+7]]+"-"+zbe[e[t+8]]+zbe[e[t+9]]+"-"+zbe[e[t+10]]+zbe[e[t+11]]+zbe[e[t+12]]+zbe[e[t+13]]+zbe[e[t+14]]+zbe[e[t+15]]}var $Dy=Gi(require("crypto")),nAf={randomUUID:$Dy.default.randomUUID};function IyC(e,t,r){if(nAf.randomUUID&&!t&&!e)return nAf.randomUUID();e=e||{};let n=e.random||(e.rng||rAf)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(let i=0;i<16;++i)t[r+i]=n[i];return t}return KDy(n)}var yit=IyC;var MyC="id",ByC=".fern",X$o=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new keo(r),this.userId=t==null?void 0:Ohf(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.101.1",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=kl(L_.of((0,YDy.homedir)()),ds.of(ByC),ds.of(MyC));await Qv(t)||(await(0,tto.mkdir)((0,XDy.dirname)(t),{recursive:!0}),await(0,tto.writeFile)(t,yit())),this.persistedDistinctId=(await(0,tto.readFile)(t)).toString()}return this.persistedDistinctId}};var iAf;async function rto(){return iAf==null&&(iAf=await TyC()),iAf}async function TyC(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new Y$o;let r=await nws();return r!=null?new X$o({token:r,posthogApiKey:e}):await rka()!=null?new VCs({posthogApiKey:e}):new X$o({token:void 0,posthogApiKey:e})}catch{return new Y$o}}function Z$o(e,t){return function(){return e.apply(t,arguments)}}var{toString:qyC}=Object.prototype,{getPrototypeOf:oAf}=Object,{iterator:JCs,toStringTag:kDy}=Symbol,KCs=(e=>t=>{let r=qyC.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),oRr=e=>(e=e.toLowerCase(),t=>KCs(t)===e),$Cs=e=>t=>typeof t===e,{isArray:ito}=Array,nto=$Cs("undefined");function k$o(e){return e!==null&&!nto(e)&&e.constructor!==null&&!nto(e.constructor)&&P3e(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var eCy=oRr("ArrayBuffer");function RyC(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&eCy(e.buffer),t}var NyC=$Cs("string"),P3e=$Cs("function"),tCy=$Cs("number"),eYo=e=>e!==null&&typeof e=="object",FyC=e=>e===!0||e===!1,GCs=e=>{if(KCs(e)!=="object")return!1;let t=oAf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(kDy in e)&&!(JCs in e)},xyC=e=>{if(!eYo(e)||k$o(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},zyC=oRr("Date"),QyC=oRr("File"),LyC=oRr("Blob"),UyC=oRr("FileList"),VyC=e=>eYo(e)&&P3e(e.pipe),WyC=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||P3e(e.append)&&((t=KCs(e))==="formdata"||t==="object"&&P3e(e.toString)&&e.toString()==="[object FormData]"))},HyC=oRr("URLSearchParams"),[GyC,JyC,KyC,$yC]=["ReadableStream","Request","Response","Headers"].map(oRr),YyC=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function tYo(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,i;if(typeof e!="object"&&(e=[e]),ito(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(k$o(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(n=0;n<o;n++)c=a[n],t.call(null,e[c],c,e)}}function rCy(e,t){if(k$o(e))return null;t=t.toLowerCase();let r=Object.keys(e),n=r.length,i;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}var Pla=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,nCy=e=>!nto(e)&&e!==Pla;function aAf(){let{caseless:e,skipUndefined:t}=nCy(this)&&this||{},r={},n=(i,a)=>{let o=e&&rCy(r,a)||a;GCs(r[o])&&GCs(i)?r[o]=aAf(r[o],i):GCs(i)?r[o]=aAf({},i):ito(i)?r[o]=i.slice():(!t||!nto(i))&&(r[o]=i)};for(let i=0,a=arguments.length;i<a;i++)arguments[i]&&tYo(arguments[i],n);return r}var XyC=(e,t,r,{allOwnKeys:n}={})=>(tYo(t,(i,a)=>{r&&P3e(i)?e[a]=Z$o(i,r):e[a]=i},{allOwnKeys:n}),e),ZyC=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),kyC=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},evC=(e,t,r,n)=>{let i,a,o,c={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),a=i.length;a-- >0;)o=i[a],(!n||n(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&oAf(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},tvC=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let n=e.indexOf(t,r);return n!==-1&&n===r},rvC=e=>{if(!e)return null;if(ito(e))return e;let t=e.length;if(!tCy(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},nvC=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&oAf(Uint8Array)),ivC=(e,t)=>{let n=(e&&e[JCs]).call(e),i;for(;(i=n.next())&&!i.done;){let a=i.value;t.call(e,a[0],a[1])}},avC=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},ovC=oRr("HTMLFormElement"),uvC=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),ZDy=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),svC=oRr("RegExp"),iCy=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};tYo(r,(i,a)=>{let o;(o=t(i,a,e))!==!1&&(n[a]=o||i)}),Object.defineProperties(e,n)},cvC=e=>{iCy(e,(t,r)=>{if(P3e(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=e[r];if(P3e(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},lvC=(e,t)=>{let r={},n=i=>{i.forEach(a=>{r[a]=!0})};return ito(e)?n(e):n(String(e).split(t)),r},fvC=()=>{},dvC=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function pvC(e){return!!(e&&P3e(e.append)&&e[kDy]==="FormData"&&e[JCs])}var _vC=e=>{let t=new Array(10),r=(n,i)=>{if(eYo(n)){if(t.indexOf(n)>=0)return;if(k$o(n))return n;if(!("toJSON"in n)){t[i]=n;let a=ito(n)?[]:{};return tYo(n,(o,c)=>{let f=r(o,i+1);!nto(f)&&(a[c]=f)}),t[i]=void 0,a}}return n};return r(e,0)},hvC=oRr("AsyncFunction"),yvC=e=>e&&(eYo(e)||P3e(e))&&P3e(e.then)&&P3e(e.catch),aCy=((e,t)=>e?setImmediate:t?((r,n)=>(Pla.addEventListener("message",({source:i,data:a})=>{i===Pla&&a===r&&n.length&&n.shift()()},!1),i=>{n.push(i),Pla.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",P3e(Pla.postMessage)),vvC=typeof queueMicrotask<"u"?queueMicrotask.bind(Pla):typeof process<"u"&&process.nextTick||aCy,bvC=e=>e!=null&&P3e(e[JCs]),Zf={isArray:ito,isArrayBuffer:eCy,isBuffer:k$o,isFormData:WyC,isArrayBufferView:RyC,isString:NyC,isNumber:tCy,isBoolean:FyC,isObject:eYo,isPlainObject:GCs,isEmptyObject:xyC,isReadableStream:GyC,isRequest:JyC,isResponse:KyC,isHeaders:$yC,isUndefined:nto,isDate:zyC,isFile:QyC,isBlob:LyC,isRegExp:svC,isFunction:P3e,isStream:VyC,isURLSearchParams:HyC,isTypedArray:nvC,isFileList:UyC,forEach:tYo,merge:aAf,extend:XyC,trim:YyC,stripBOM:ZyC,inherits:kyC,toFlatObject:evC,kindOf:KCs,kindOfTest:oRr,endsWith:tvC,toArray:rvC,forEachEntry:ivC,matchAll:avC,isHTMLForm:ovC,hasOwnProperty:ZDy,hasOwnProp:ZDy,reduceDescriptors:iCy,freezeMethods:cvC,toObjectSet:lvC,toCamelCase:uvC,noop:fvC,toFiniteNumber:dvC,findKey:rCy,global:Pla,isContextDefined:nCy,isSpecCompliantForm:pvC,toJSONObject:_vC,isAsyncFn:hvC,isThenable:yvC,setImmediate:aCy,asap:vvC,isIterable:bvC};function ato(e,t,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Zf.inherits(ato,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:Zf.toJSONObject(this.config),code:this.code,status:this.status}}});var oCy=ato.prototype,uCy={};["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=>{uCy[e]={value:e}});Object.defineProperties(ato,uCy);Object.defineProperty(oCy,"isAxiosError",{value:!0});ato.from=(e,t,r,n,i,a)=>{let o=Object.create(oCy);Zf.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 ato.call(o,c,f,r,n,i),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var xm=ato;var sCy=Gi(oca(),1),YCs=sCy.default;function uAf(e){return Zf.isPlainObject(e)||Zf.isArray(e)}function lCy(e){return Zf.endsWith(e,"[]")?e.slice(0,-2):e}function cCy(e,t,r){return e?e.concat(t).map(function(i,a){return i=lCy(i),!r&&a?"["+i+"]":i}).join(r?".":""):t}function gvC(e){return Zf.isArray(e)&&!e.some(uAf)}var mvC=Zf.toFlatObject(Zf,{},null,function(t){return/^is[A-Z]/.test(t)});function OvC(e,t,r){if(!Zf.isObject(e))throw new TypeError("target must be an object");t=t||new(YCs||FormData),r=Zf.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(C,M){return!Zf.isUndefined(M[C])});let n=r.metaTokens,i=r.visitor||u,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&Zf.isSpecCompliantForm(t);if(!Zf.isFunction(i))throw new TypeError("visitor must be a function");function s(P){if(P===null)return"";if(Zf.isDate(P))return P.toISOString();if(Zf.isBoolean(P))return P.toString();if(!f&&Zf.isBlob(P))throw new xm("Blob is not supported. Use a Buffer instead.");return Zf.isArrayBuffer(P)||Zf.isTypedArray(P)?f&&typeof Blob=="function"?new Blob([P]):Buffer.from(P):P}function u(P,C,M){let T=P;if(P&&!M&&typeof P=="object"){if(Zf.endsWith(C,"{}"))C=n?C:C.slice(0,-2),P=JSON.stringify(P);else if(Zf.isArray(P)&&gvC(P)||(Zf.isFileList(P)||Zf.endsWith(C,"[]"))&&(T=Zf.toArray(P)))return C=lCy(C),T.forEach(function(U,q){!(Zf.isUndefined(U)||U===null)&&t.append(o===!0?cCy([C],q,a):o===null?C:C+"[]",s(U))}),!1}return uAf(P)?!0:(t.append(cCy(M,C,a),s(P)),!1)}let l=[],m=Object.assign(mvC,{defaultVisitor:u,convertValue:s,isVisitable:uAf});function A(P,C){if(!Zf.isUndefined(P)){if(l.indexOf(P)!==-1)throw Error("Circular reference detected in "+C.join("."));l.push(P),Zf.forEach(P,function(T,z){(!(Zf.isUndefined(T)||T===null)&&i.call(t,T,Zf.isString(z)?z.trim():z,C,m))===!0&&A(T,C?C.concat(z):[z])}),l.pop()}}if(!Zf.isObject(e))throw new TypeError("data must be an object");return A(e),t}var X7i=OvC;function fCy(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function dCy(e,t){this._pairs=[],e&&X7i(e,this,t)}var pCy=dCy.prototype;pCy.append=function(t,r){this._pairs.push([t,r])};pCy.toString=function(t){let r=t?function(n){return t.call(this,n,fCy)}:fCy;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var _Cy=dCy;function AvC(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function wla(e,t,r){if(!t)return e;let n=r&&r.encode||AvC;Zf.isFunction(r)&&(r={serialize:r});let i=r&&r.serialize,a;if(i?a=i(t,r):a=Zf.isURLSearchParams(t)?t.toString():new _Cy(t,r).toString(n),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var sAf=class{constructor(){this.handlers=[]}use(t,r,n){return this.handlers.push({fulfilled:t,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){Zf.forEach(this.handlers,function(n){n!==null&&t(n)})}},cAf=sAf;var oto={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var bCy=Gi(require("crypto"),1);var hCy=Gi(require("url"),1),yCy=hCy.default.URLSearchParams;var lAf="abcdefghijklmnopqrstuvwxyz",vCy="0123456789",gCy={DIGIT:vCy,ALPHA:lAf,ALPHA_DIGIT:lAf+lAf.toUpperCase()+vCy},PvC=(e=16,t=gCy.ALPHA_DIGIT)=>{let r="",{length:n}=t,i=new Uint32Array(e);bCy.default.randomFillSync(i);for(let a=0;a<e;a++)r+=t[i[a]%n];return r},mCy={isNode:!0,classes:{URLSearchParams:yCy,FormData:YCs,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:gCy,generateString:PvC,protocols:["http","https","file","data"]};var pAf={};yf(pAf,{hasBrowserEnv:()=>dAf,hasStandardBrowserEnv:()=>wvC,hasStandardBrowserWebWorkerEnv:()=>jvC,navigator:()=>fAf,origin:()=>EvC});var dAf=typeof window<"u"&&typeof document<"u",fAf=typeof navigator=="object"&&navigator||void 0,wvC=dAf&&(!fAf||["ReactNative","NativeScript","NS"].indexOf(fAf.product)<0),jvC=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",EvC=dAf&&window.location.href||"http://localhost";var n8={...pAf,...mCy};function _Af(e,t){return X7i(e,new n8.classes.URLSearchParams,{visitor:function(r,n,i,a){return n8.isNode&&Zf.isBuffer(r)?(this.append(n,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function SvC(e){return Zf.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function DvC(e){let t={},r=Object.keys(e),n,i=r.length,a;for(n=0;n<i;n++)a=r[n],t[a]=e[a];return t}function CvC(e){function t(r,n,i,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),f=a>=r.length;return o=!o&&Zf.isArray(i)?i.length:o,f?(Zf.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!c):((!i[o]||!Zf.isObject(i[o]))&&(i[o]=[]),t(r,n,i[o],a)&&Zf.isArray(i[o])&&(i[o]=DvC(i[o])),!c)}if(Zf.isFormData(e)&&Zf.isFunction(e.entries)){let r={};return Zf.forEachEntry(e,(n,i)=>{t(SvC(n),i,r,0)}),r}return null}var XCs=CvC;function IvC(e,t,r){if(Zf.isString(e))try{return(t||JSON.parse)(e),Zf.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var hAf={transitional:oto,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,a=Zf.isObject(t);if(a&&Zf.isHTMLForm(t)&&(t=new FormData(t)),Zf.isFormData(t))return i?JSON.stringify(XCs(t)):t;if(Zf.isArrayBuffer(t)||Zf.isBuffer(t)||Zf.isStream(t)||Zf.isFile(t)||Zf.isBlob(t)||Zf.isReadableStream(t))return t;if(Zf.isArrayBufferView(t))return t.buffer;if(Zf.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(n.indexOf("application/x-www-form-urlencoded")>-1)return _Af(t,this.formSerializer).toString();if((c=Zf.isFileList(t))||n.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return X7i(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||i?(r.setContentType("application/json",!1),IvC(t)):t}],transformResponse:[function(t){let r=this.transitional||hAf.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(Zf.isResponse(t)||Zf.isReadableStream(t))return t;if(t&&Zf.isString(t)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?xm.from(c,xm.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:n8.classes.FormData,Blob:n8.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Zf.forEach(["delete","get","head","post","put","patch"],e=>{hAf.headers[e]={}});var uto=hAf;var MvC=Zf.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"]),OCy=e=>{let t={},r,n,i;return e&&e.split(`
|
|
2167
2167
|
`).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||t[r]&&MvC[r])&&(r==="set-cookie"?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t};var ACy=Symbol("internals");function rYo(e){return e&&String(e).trim().toLowerCase()}function ZCs(e){return e===!1||e==null?e:Zf.isArray(e)?e.map(ZCs):String(e)}function BvC(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}var TvC=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function yAf(e,t,r,n,i){if(Zf.isFunction(n))return n.call(this,t,r);if(i&&(t=r),!!Zf.isString(t)){if(Zf.isString(n))return t.indexOf(n)!==-1;if(Zf.isRegExp(n))return n.test(t)}}function qvC(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function RvC(e,t){let r=Zf.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(i,a,o){return this[n].call(this,t,i,a,o)},configurable:!0})})}var sto=class{constructor(t){t&&this.set(t)}set(t,r,n){let i=this;function a(c,f,s){let u=rYo(f);if(!u)throw new Error("header name must be a non-empty string");let l=Zf.findKey(i,u);(!l||i[l]===void 0||s===!0||s===void 0&&i[l]!==!1)&&(i[l||f]=ZCs(c))}let o=(c,f)=>Zf.forEach(c,(s,u)=>a(s,u,f));if(Zf.isPlainObject(t)||t instanceof this.constructor)o(t,r);else if(Zf.isString(t)&&(t=t.trim())&&!TvC(t))o(OCy(t),r);else if(Zf.isObject(t)&&Zf.isIterable(t)){let c={},f,s;for(let u of t){if(!Zf.isArray(u))throw TypeError("Object iterator must return a key-value pair");c[s=u[0]]=(f=c[s])?Zf.isArray(f)?[...f,u[1]]:[f,u[1]]:u[1]}o(c,r)}else t!=null&&a(r,t,n);return this}get(t,r){if(t=rYo(t),t){let n=Zf.findKey(this,t);if(n){let i=this[n];if(!r)return i;if(r===!0)return BvC(i);if(Zf.isFunction(r))return r.call(this,i,n);if(Zf.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=rYo(t),t){let n=Zf.findKey(this,t);return!!(n&&this[n]!==void 0&&(!r||yAf(this,this[n],n,r)))}return!1}delete(t,r){let n=this,i=!1;function a(o){if(o=rYo(o),o){let c=Zf.findKey(n,o);c&&(!r||yAf(n,n[c],c,r))&&(delete n[c],i=!0)}}return Zf.isArray(t)?t.forEach(a):a(t),i}clear(t){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let a=r[n];(!t||yAf(this,this[a],a,t,!0))&&(delete this[a],i=!0)}return i}normalize(t){let r=this,n={};return Zf.forEach(this,(i,a)=>{let o=Zf.findKey(n,a);if(o){r[o]=ZCs(i),delete r[a];return}let c=t?qvC(a):String(a).trim();c!==a&&delete r[a],r[c]=ZCs(i),n[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return Zf.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=t&&Zf.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
|
|
2168
2168
|
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let n=new this(t);return r.forEach(i=>n.set(i)),n}static accessor(t){let n=(this[ACy]=this[ACy]={accessors:{}}).accessors,i=this.prototype;function a(o){let c=rYo(o);n[c]||(RvC(i,o),n[c]=!0)}return Zf.isArray(t)?t.forEach(a):a(t),this}};sto.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Zf.reduceDescriptors(sto.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}});Zf.freezeMethods(sto);var J$=sto;function nYo(e,t){let r=this||uto,n=t||r,i=J$.from(n.headers),a=n.data;return Zf.forEach(e,function(c){a=c.call(r,a,i.normalize(),t?t.status:void 0)}),i.normalize(),a}function iYo(e){return!!(e&&e.__CANCEL__)}function PCy(e,t,r){xm.call(this,e??"canceled",xm.ERR_CANCELED,t,r),this.name="CanceledError"}Zf.inherits(PCy,xm,{__CANCEL__:!0});var vit=PCy;function NVr(e,t,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new xm("Request failed with status code "+r.status,[xm.ERR_BAD_REQUEST,xm.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function vAf(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function bAf(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function jla(e,t,r){let n=!vAf(t);return e&&(n||r==!1)?bAf(e,t):t}var zCy=Gi(gCs(),1),QCy=Gi(require("http"),1),LCy=Gi(require("https"),1),UCy=Gi(require("util"),1),VCy=Gi(gOf(),1),TPi=Gi(require("zlib"),1);var Ela="1.12.2";function aYo(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var NvC=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function gAf(e,t,r){let n=r&&r.Blob||n8.classes.Blob,i=aYo(e);if(t===void 0&&n&&(t=!0),i==="data"){e=i.length?e.slice(i.length+1):e;let a=NvC.exec(e);if(!a)throw new xm("Invalid URL",xm.ERR_INVALID_URL);let o=a[1],c=a[2],f=a[3],s=Buffer.from(decodeURIComponent(f),c?"base64":"utf8");if(t){if(!n)throw new xm("Blob is not supported",xm.ERR_NOT_SUPPORT);return new n([s],{type:o})}return s}throw new xm("Unsupported protocol "+i,xm.ERR_NOT_SUPPORT)}var Dla=Gi(require("stream"),1);var wCy=Gi(require("stream"),1);var mAf=Symbol("internals"),OAf=class extends wCy.default.Transform{constructor(t){t=Zf.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(n,i)=>!Zf.isUndefined(i[n])),super({readableHighWaterMark:t.chunkSize});let r=this[mAf]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",n=>{n==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[mAf];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,n){let i=this[mAf],a=i.maxRate,o=this.readableHighWaterMark,c=i.timeWindow,f=1e3/c,s=a/f,u=i.minChunkSize!==!1?Math.max(i.minChunkSize,s*.01):0,l=(A,P)=>{let C=Buffer.byteLength(A);i.bytesSeen+=C,i.bytes+=C,i.isCaptured&&this.emit("progress",i.bytesSeen),this.push(A)?process.nextTick(P):i.onReadCallback=()=>{i.onReadCallback=null,process.nextTick(P)}},m=(A,P)=>{let C=Buffer.byteLength(A),M=null,T=o,z,U=0;if(a){let q=Date.now();(!i.ts||(U=q-i.ts)>=c)&&(i.ts=q,z=s-i.bytes,i.bytes=z<0?-z:0,U=0),z=s-i.bytes}if(a){if(z<=0)return setTimeout(()=>{P(null,A)},c-U);z<T&&(T=z)}T&&C>T&&C-T>u&&(M=A.subarray(T),A=A.subarray(0,T)),l(A,M?()=>{process.nextTick(P,null,M)}:P)};m(t,function A(P,C){if(P)return n(P);C?m(C,A):n(null)})}},AAf=OAf;var WCy=require("events");var ECy=Gi(require("util"),1),SCy=require("stream");var{asyncIterator:jCy}=Symbol,FvC=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[jCy]?yield*e[jCy]():yield e},kCs=FvC;var xvC=n8.ALPHABET.ALPHA_DIGIT+"-_",oYo=typeof TextEncoder=="function"?new TextEncoder:new ECy.default.TextEncoder,Sla=`\r
|
|
2169
2169
|
`,zvC=oYo.encode(Sla),QvC=2,PAf=class{constructor(t,r){let{escapeName:n}=this.constructor,i=Zf.isString(r),a=`Content-Disposition: form-data; name="${n(t)}"${!i&&r.name?`; filename="${n(r.name)}"`:""}${Sla}`;i?r=oYo.encode(String(r).replace(/\r?\n|\r\n?/g,Sla)):a+=`Content-Type: ${r.type||"application/octet-stream"}${Sla}`,this.headers=oYo.encode(a+Sla),this.contentLength=i?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+QvC,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;Zf.isTypedArray(t)?yield t:yield*kCs(t),yield zvC}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},LvC=(e,t,r)=>{let{tag:n="form-data-boundary",size:i=25,boundary:a=n+"-"+n8.generateString(i,xvC)}=r||{};if(!Zf.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=oYo.encode("--"+a+Sla),c=oYo.encode("--"+a+"--"+Sla),f=c.byteLength,s=Array.from(e.entries()).map(([l,m])=>{let A=new PAf(l,m);return f+=A.size,A});f+=o.byteLength*s.length,f=Zf.toFiniteNumber(f);let u={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(f)&&(u["Content-Length"]=f),t&&t(u),SCy.Readable.from((async function*(){for(let l of s)yield o,yield*l.encode();yield c})())},DCy=LvC;var CCy=Gi(require("stream"),1),wAf=class extends CCy.default.Transform{__transform(t,r,n){this.push(t),n()}_transform(t,r,n){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let i=Buffer.alloc(2);i[0]=120,i[1]=156,this.push(i,r)}this.__transform(t,r,n)}},ICy=wAf;var UvC=(e,t)=>Zf.isAsyncFn(e)?function(...r){let n=r.pop();e.apply(this,r).then(i=>{try{t?n(null,...t(i)):n(null,i)}catch(a){n(a)}},n)}:e,MCy=UvC;function VvC(e,t){e=e||10;let r=new Array(e),n=new Array(e),i=0,a=0,o;return t=t!==void 0?t:1e3,function(f){let s=Date.now(),u=n[a];o||(o=s),r[i]=f,n[i]=s;let l=a,m=0;for(;l!==i;)m+=r[l++],l=l%e;if(i=(i+1)%e,i===a&&(a=(a+1)%e),s-o<t)return;let A=u&&s-u;return A?Math.round(m*1e3/A):void 0}}var BCy=VvC;function WvC(e,t){let r=0,n=1e3/t,i,a,o=(s,u=Date.now())=>{r=u,i=null,a&&(clearTimeout(a),a=null),e(...s)};return[(...s)=>{let u=Date.now(),l=u-r;l>=n?o(s,u):(i=s,a||(a=setTimeout(()=>{a=null,o(i)},n-l)))},()=>i&&o(i)]}var TCy=WvC;var BPi=(e,t,r=3)=>{let n=0,i=BCy(50,250);return TCy(a=>{let o=a.loaded,c=a.lengthComputable?a.total:void 0,f=o-n,s=i(f),u=o<=c;n=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)},cto=(e,t)=>{let r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},lto=e=>(...t)=>Zf.asap(()=>e(...t));function jAf(e){if(!e||typeof e!="string"||!e.startsWith("data:"))return 0;let t=e.indexOf(",");if(t<0)return 0;let r=e.slice(5,t),n=e.slice(t+1);if(/;base64/i.test(r)){let a=n.length,o=n.length;for(let m=0;m<o;m++)if(n.charCodeAt(m)===37&&m+2<o){let A=n.charCodeAt(m+1),P=n.charCodeAt(m+2);(A>=48&&A<=57||A>=65&&A<=70||A>=97&&A<=102)&&(P>=48&&P<=57||P>=65&&P<=70||P>=97&&P<=102)&&(a-=2,m+=2)}let c=0,f=o-1,s=m=>m>=2&&n.charCodeAt(m-2)===37&&n.charCodeAt(m-1)===51&&(n.charCodeAt(m)===68||n.charCodeAt(m)===100);f>=0&&(n.charCodeAt(f)===61?(c++,f--):s(f)&&(c++,f-=3)),c===1&&f>=0&&(n.charCodeAt(f)===61||s(f))&&c++;let l=Math.floor(a/4)*3-(c||0);return l>0?l:0}return Buffer.byteLength(n,"utf8")}var qCy={flush:TPi.default.constants.Z_SYNC_FLUSH,finishFlush:TPi.default.constants.Z_SYNC_FLUSH},HvC={flush:TPi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:TPi.default.constants.BROTLI_OPERATION_FLUSH},RCy=Zf.isFunction(TPi.default.createBrotliDecompress),{http:GvC,https:JvC}=VCy.default,KvC=/https:?/,NCy=n8.protocols.map(e=>e+":"),FCy=(e,[t,r])=>(e.on("end",r).on("error",r),t);function $vC(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function HCy(e,t,r){let n=t;if(!n&&n!==!1){let i=zCy.default.getProxyForUrl(r);i&&(n=new URL(i))}if(n){if(n.username&&(n.auth=(n.username||"")+":"+(n.password||"")),n.auth){(n.auth.username||n.auth.password)&&(n.auth=(n.auth.username||"")+":"+(n.auth.password||""));let a=Buffer.from(n.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let i=n.hostname||n.host;e.hostname=i,e.host=i,e.port=n.port,e.path=r,n.protocol&&(e.protocol=n.protocol.includes(":")?n.protocol:`${n.protocol}:`)}e.beforeRedirects.proxy=function(a){HCy(a,t,a.href)}}var YvC=typeof process<"u"&&Zf.kindOf(process)==="process",XvC=e=>new Promise((t,r)=>{let n,i,a=(f,s)=>{i||(i=!0,n&&n(f,s))},o=f=>{a(f),t(f)},c=f=>{a(f,!0),r(f)};e(o,c,f=>n=f).catch(c)}),ZvC=({address:e,family:t})=>{if(!Zf.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},xCy=(e,t)=>ZvC(Zf.isObject(e)?e:{address:e,family:t}),GCy=YvC&&function(t){return XvC(async function(n,i,a){let{data:o,lookup:c,family:f}=t,{responseType:s,responseEncoding:u}=t,l=t.method.toUpperCase(),m,A=!1,P;if(c){let Se=MCy(c,jt=>Zf.isArray(jt)?jt:[jt]);c=(jt,bt,ze)=>{Se(jt,bt,(Me,$t,rt)=>{if(Me)return ze(Me);let nr=Zf.isArray($t)?$t.map(Ft=>xCy(Ft)):[xCy($t,rt)];bt.all?ze(Me,nr):ze(Me,nr[0].address,nr[0].family)})}}let C=new WCy.EventEmitter,M=()=>{t.cancelToken&&t.cancelToken.unsubscribe(T),t.signal&&t.signal.removeEventListener("abort",T),C.removeAllListeners()};a((Se,jt)=>{m=!0,jt&&(A=!0,M())});function T(Se){C.emit("abort",!Se||Se.type?new vit(null,t,P):Se)}C.once("abort",i),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(T),t.signal&&(t.signal.aborted?T():t.signal.addEventListener("abort",T)));let z=jla(t.baseURL,t.url,t.allowAbsoluteUrls),U=new URL(z,n8.hasBrowserEnv?n8.origin:void 0),q=U.protocol||NCy[0];if(q==="data:"){if(t.maxContentLength>-1){let jt=String(t.url||z||"");if(jAf(jt)>t.maxContentLength)return i(new xm("maxContentLength size of "+t.maxContentLength+" exceeded",xm.ERR_BAD_RESPONSE,t))}let Se;if(l!=="GET")return NVr(n,i,{status:405,statusText:"method not allowed",headers:{},config:t});try{Se=gAf(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(jt){throw xm.from(jt,xm.ERR_BAD_REQUEST,t)}return s==="text"?(Se=Se.toString(u),(!u||u==="utf8")&&(Se=Zf.stripBOM(Se))):s==="stream"&&(Se=Dla.default.Readable.from(Se)),NVr(n,i,{data:Se,status:200,statusText:"OK",headers:new J$,config:t})}if(NCy.indexOf(q)===-1)return i(new xm("Unsupported protocol "+q,xm.ERR_BAD_REQUEST,t));let V=J$.from(t.headers).normalize();V.set("User-Agent","axios/"+Ela,!1);let{onUploadProgress:$,onDownloadProgress:re}=t,X=t.maxRate,k,ne;if(Zf.isSpecCompliantForm(o)){let Se=V.getContentType(/boundary=([-_\w\d]{10,70})/i);o=DCy(o,jt=>{V.set(jt)},{tag:`axios-${Ela}-boundary`,boundary:Se&&Se[1]||void 0})}else if(Zf.isFormData(o)&&Zf.isFunction(o.getHeaders)){if(V.set(o.getHeaders()),!V.hasContentLength())try{let Se=await UCy.default.promisify(o.getLength).call(o);Number.isFinite(Se)&&Se>=0&&V.setContentLength(Se)}catch{}}else if(Zf.isBlob(o)||Zf.isFile(o))o.size&&V.setContentType(o.type||"application/octet-stream"),V.setContentLength(o.size||0),o=Dla.default.Readable.from(kCs(o));else if(o&&!Zf.isStream(o)){if(!Buffer.isBuffer(o))if(Zf.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else if(Zf.isString(o))o=Buffer.from(o,"utf-8");else return i(new xm("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",xm.ERR_BAD_REQUEST,t));if(V.setContentLength(o.length,!1),t.maxBodyLength>-1&&o.length>t.maxBodyLength)return i(new xm("Request body larger than maxBodyLength limit",xm.ERR_BAD_REQUEST,t))}let Oe=Zf.toFiniteNumber(V.getContentLength());Zf.isArray(X)?(k=X[0],ne=X[1]):k=ne=X,o&&($||k)&&(Zf.isStream(o)||(o=Dla.default.Readable.from(o,{objectMode:!1})),o=Dla.default.pipeline([o,new AAf({maxRate:Zf.toFiniteNumber(k)})],Zf.noop),$&&o.on("progress",FCy(o,cto(Oe,BPi(lto($),!1,3)))));let ve;if(t.auth){let Se=t.auth.username||"",jt=t.auth.password||"";ve=Se+":"+jt}if(!ve&&U.username){let Se=U.username,jt=U.password;ve=Se+":"+jt}ve&&V.delete("authorization");let me;try{me=wla(U.pathname+U.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(Se){let jt=new Error(Se.message);return jt.config=t,jt.url=t.url,jt.exists=!0,i(jt)}V.set("Accept-Encoding","gzip, compress, deflate"+(RCy?", br":""),!1);let be={path:me,method:l,headers:V.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:ve,protocol:q,family:f,beforeRedirect:$vC,beforeRedirects:{}};!Zf.isUndefined(c)&&(be.lookup=c),t.socketPath?be.socketPath=t.socketPath:(be.hostname=U.hostname.startsWith("[")?U.hostname.slice(1,-1):U.hostname,be.port=U.port,HCy(be,t.proxy,q+"//"+U.hostname+(U.port?":"+U.port:"")+be.path));let Ie,Be=KvC.test(be.protocol);if(be.agent=Be?t.httpsAgent:t.httpAgent,t.transport?Ie=t.transport:t.maxRedirects===0?Ie=Be?LCy.default:QCy.default:(t.maxRedirects&&(be.maxRedirects=t.maxRedirects),t.beforeRedirect&&(be.beforeRedirects.config=t.beforeRedirect),Ie=Be?JvC:GvC),t.maxBodyLength>-1?be.maxBodyLength=t.maxBodyLength:be.maxBodyLength=1/0,t.insecureHTTPParser&&(be.insecureHTTPParser=t.insecureHTTPParser),P=Ie.request(be,function(jt){if(P.destroyed)return;let bt=[jt],ze=+jt.headers["content-length"];if(re||ne){let Ft=new AAf({maxRate:Zf.toFiniteNumber(ne)});re&&Ft.on("progress",FCy(Ft,cto(ze,BPi(lto(re),!0,3)))),bt.push(Ft)}let Me=jt,$t=jt.req||P;if(t.decompress!==!1&&jt.headers["content-encoding"])switch((l==="HEAD"||jt.statusCode===204)&&delete jt.headers["content-encoding"],(jt.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":bt.push(TPi.default.createUnzip(qCy)),delete jt.headers["content-encoding"];break;case"deflate":bt.push(new ICy),bt.push(TPi.default.createUnzip(qCy)),delete jt.headers["content-encoding"];break;case"br":RCy&&(bt.push(TPi.default.createBrotliDecompress(HvC)),delete jt.headers["content-encoding"])}Me=bt.length>1?Dla.default.pipeline(bt,Zf.noop):bt[0];let rt=Dla.default.finished(Me,()=>{rt(),M()}),nr={status:jt.statusCode,statusText:jt.statusMessage,headers:new J$(jt.headers),config:t,request:$t};if(s==="stream")nr.data=Me,NVr(n,i,nr);else{let Ft=[],Xe=0;Me.on("data",function(ur){Ft.push(ur),Xe+=ur.length,t.maxContentLength>-1&&Xe>t.maxContentLength&&(A=!0,Me.destroy(),i(new xm("maxContentLength size of "+t.maxContentLength+" exceeded",xm.ERR_BAD_RESPONSE,t,$t)))}),Me.on("aborted",function(){if(A)return;let ur=new xm("stream has been aborted",xm.ERR_BAD_RESPONSE,t,$t);Me.destroy(ur),i(ur)}),Me.on("error",function(ur){P.destroyed||i(xm.from(ur,null,t,$t))}),Me.on("end",function(){try{let ur=Ft.length===1?Ft[0]:Buffer.concat(Ft);s!=="arraybuffer"&&(ur=ur.toString(u),(!u||u==="utf8")&&(ur=Zf.stripBOM(ur))),nr.data=ur}catch(ur){return i(xm.from(ur,null,t,nr.request,nr))}NVr(n,i,nr)})}C.once("abort",Ft=>{Me.destroyed||(Me.emit("error",Ft),Me.destroy())})}),C.once("abort",Se=>{i(Se),P.destroy(Se)}),P.on("error",function(jt){i(xm.from(jt,null,t,P))}),P.on("socket",function(jt){jt.setKeepAlive(!0,1e3*60)}),t.timeout){let Se=parseInt(t.timeout,10);if(Number.isNaN(Se)){i(new xm("error trying to parse `config.timeout` to int",xm.ERR_BAD_OPTION_VALUE,t,P));return}P.setTimeout(Se,function(){if(m)return;let bt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",ze=t.transitional||oto;t.timeoutErrorMessage&&(bt=t.timeoutErrorMessage),i(new xm(bt,ze.clarifyTimeoutError?xm.ETIMEDOUT:xm.ECONNABORTED,t,P)),T()})}if(Zf.isStream(o)){let Se=!1,jt=!1;o.on("end",()=>{Se=!0}),o.once("error",bt=>{jt=!0,P.destroy(bt)}),o.on("close",()=>{!Se&&!jt&&T(new vit("Request stream has been aborted",t,P))}),o.pipe(P)}else P.end(o)})};var JCy=n8.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,n8.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(n8.origin),n8.navigator&&/(msie|trident)/i.test(n8.navigator.userAgent)):()=>!0;var KCy=n8.hasStandardBrowserEnv?{write(e,t,r,n,i,a){let o=[e+"="+encodeURIComponent(t)];Zf.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),Zf.isString(n)&&o.push("path="+n),Zf.isString(i)&&o.push("domain="+i),a===!0&&o.push("secure"),document.cookie=o.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var $Cy=e=>e instanceof J$?{...e}:e;function uRr(e,t){t=t||{};let r={};function n(s,u,l,m){return Zf.isPlainObject(s)&&Zf.isPlainObject(u)?Zf.merge.call({caseless:m},s,u):Zf.isPlainObject(u)?Zf.merge({},u):Zf.isArray(u)?u.slice():u}function i(s,u,l,m){if(Zf.isUndefined(u)){if(!Zf.isUndefined(s))return n(void 0,s,l,m)}else return n(s,u,l,m)}function a(s,u){if(!Zf.isUndefined(u))return n(void 0,u)}function o(s,u){if(Zf.isUndefined(u)){if(!Zf.isUndefined(s))return n(void 0,s)}else return n(void 0,u)}function c(s,u,l){if(l in t)return n(s,u);if(l in e)return n(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)=>i($Cy(s),$Cy(u),l,!0)};return Zf.forEach(Object.keys({...e,...t}),function(u){let l=f[u]||i,m=l(e[u],t[u],u);Zf.isUndefined(m)&&l!==c||(r[u]=m)}),r}var eIs=e=>{let t=uRr({},e),{data:r,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=J$.from(o),t.url=wla(jla(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),Zf.isFormData(r)){if(n8.hasStandardBrowserEnv||n8.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(Zf.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(n8.hasStandardBrowserEnv&&(n&&Zf.isFunction(n)&&(n=n(t)),n||n!==!1&&JCy(t.url))){let f=i&&a&&KCy.read(a);f&&o.set(i,f)}return t};var kvC=typeof XMLHttpRequest<"u",YCy=kvC&&function(e){return new Promise(function(r,n){let i=eIs(e),a=i.data,o=J$.from(i.headers).normalize(),{responseType:c,onUploadProgress:f,onDownloadProgress:s}=i,u,l,m,A,P;function C(){A&&A(),P&&P(),i.cancelToken&&i.cancelToken.unsubscribe(u),i.signal&&i.signal.removeEventListener("abort",u)}let M=new XMLHttpRequest;M.open(i.method.toUpperCase(),i.url,!0),M.timeout=i.timeout;function T(){if(!M)return;let U=J$.from("getAllResponseHeaders"in M&&M.getAllResponseHeaders()),V={data:!c||c==="text"||c==="json"?M.responseText:M.response,status:M.status,statusText:M.statusText,headers:U,config:e,request:M};NVr(function(re){r(re),C()},function(re){n(re),C()},V),M=null}"onloadend"in M?M.onloadend=T:M.onreadystatechange=function(){!M||M.readyState!==4||M.status===0&&!(M.responseURL&&M.responseURL.indexOf("file:")===0)||setTimeout(T)},M.onabort=function(){M&&(n(new xm("Request aborted",xm.ECONNABORTED,e,M)),M=null)},M.onerror=function(q){let V=q&&q.message?q.message:"Network Error",$=new xm(V,xm.ERR_NETWORK,e,M);$.event=q||null,n($),M=null},M.ontimeout=function(){let q=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",V=i.transitional||oto;i.timeoutErrorMessage&&(q=i.timeoutErrorMessage),n(new xm(q,V.clarifyTimeoutError?xm.ETIMEDOUT:xm.ECONNABORTED,e,M)),M=null},a===void 0&&o.setContentType(null),"setRequestHeader"in M&&Zf.forEach(o.toJSON(),function(q,V){M.setRequestHeader(V,q)}),Zf.isUndefined(i.withCredentials)||(M.withCredentials=!!i.withCredentials),c&&c!=="json"&&(M.responseType=i.responseType),s&&([m,P]=BPi(s,!0),M.addEventListener("progress",m)),f&&M.upload&&([l,A]=BPi(f),M.upload.addEventListener("progress",l),M.upload.addEventListener("loadend",A)),(i.cancelToken||i.signal)&&(u=U=>{M&&(n(!U||U.type?new vit(null,e,M):U),M.abort(),M=null)},i.cancelToken&&i.cancelToken.subscribe(u),i.signal&&(i.signal.aborted?u():i.signal.addEventListener("abort",u)));let z=aYo(i.url);if(z&&n8.protocols.indexOf(z)===-1){n(new xm("Unsupported protocol "+z+":",xm.ERR_BAD_REQUEST,e));return}M.send(a||null)})};var ebC=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let n=new AbortController,i,a=function(s){if(!i){i=!0,c();let u=s instanceof Error?s:this.reason;n.abort(u instanceof xm?u:new vit(u instanceof Error?u.message:u))}},o=t&&setTimeout(()=>{o=null,a(new xm(`timeout ${t} of ms exceeded`,xm.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}=n;return f.unsubscribe=()=>Zf.asap(c),f}},XCy=ebC;var tbC=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let n=0,i;for(;n<r;)i=n+t,yield e.slice(n,i),n=i},rbC=async function*(e,t){for await(let r of nbC(e))yield*tbC(r,t)},nbC=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;yield n}}finally{await t.cancel()}},EAf=(e,t,r,n)=>{let i=rbC(e,t),a=0,o,c=f=>{o||(o=!0,n&&n(f))};return new ReadableStream({async pull(f){try{let{done:s,value:u}=await i.next();if(s){c(),f.close();return}let l=u.byteLength;if(r){let m=a+=l;r(m)}f.enqueue(new Uint8Array(u))}catch(s){throw c(s),s}},cancel(f){return c(f),i.return()}},{highWaterMark:2})};var ZCy=64*1024,{isFunction:tIs}=Zf,ibC=(({Request:e,Response:t})=>({Request:e,Response:t}))(Zf.global),{ReadableStream:kCy,TextEncoder:eIy}=Zf.global,tIy=(e,...t)=>{try{return!!e(...t)}catch{return!1}},abC=e=>{e=Zf.merge.call({skipUndefined:!0},ibC,e);let{fetch:t,Request:r,Response:n}=e,i=t?tIs(t):typeof fetch=="function",a=tIs(r),o=tIs(n);if(!i)return!1;let c=i&&tIs(kCy),f=i&&(typeof eIy=="function"?(P=>C=>P.encode(C))(new eIy):async P=>new Uint8Array(await new r(P).arrayBuffer())),s=a&&c&&tIy(()=>{let P=!1,C=new r(n8.origin,{body:new kCy,method:"POST",get duplex(){return P=!0,"half"}}).headers.has("Content-Type");return P&&!C}),u=o&&c&&tIy(()=>Zf.isReadableStream(new n("").body)),l={stream:u&&(P=>P.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(P=>{!l[P]&&(l[P]=(C,M)=>{let T=C&&C[P];if(T)return T.call(C);throw new xm(`Response type '${P}' is not supported`,xm.ERR_NOT_SUPPORT,M)})});let m=async P=>{if(P==null)return 0;if(Zf.isBlob(P))return P.size;if(Zf.isSpecCompliantForm(P))return(await new r(n8.origin,{method:"POST",body:P}).arrayBuffer()).byteLength;if(Zf.isArrayBufferView(P)||Zf.isArrayBuffer(P))return P.byteLength;if(Zf.isURLSearchParams(P)&&(P=P+""),Zf.isString(P))return(await f(P)).byteLength},A=async(P,C)=>{let M=Zf.toFiniteNumber(P.getContentLength());return M??m(C)};return async P=>{let{url:C,method:M,data:T,signal:z,cancelToken:U,timeout:q,onDownloadProgress:V,onUploadProgress:$,responseType:re,headers:X,withCredentials:k="same-origin",fetchOptions:ne}=eIs(P),Oe=t||fetch;re=re?(re+"").toLowerCase():"text";let ve=XCy([z,U&&U.toAbortSignal()],q),me=null,be=ve&&ve.unsubscribe&&(()=>{ve.unsubscribe()}),Ie;try{if($&&s&&M!=="get"&&M!=="head"&&(Ie=await A(X,T))!==0){let Me=new r(C,{method:"POST",body:T,duplex:"half"}),$t;if(Zf.isFormData(T)&&($t=Me.headers.get("content-type"))&&X.setContentType($t),Me.body){let[rt,nr]=cto(Ie,BPi(lto($)));T=EAf(Me.body,ZCy,rt,nr)}}Zf.isString(k)||(k=k?"include":"omit");let Be=a&&"credentials"in r.prototype,Se={...ne,signal:ve,method:M.toUpperCase(),headers:X.normalize().toJSON(),body:T,duplex:"half",credentials:Be?k:void 0};me=a&&new r(C,Se);let jt=await(a?Oe(me,ne):Oe(C,Se)),bt=u&&(re==="stream"||re==="response");if(u&&(V||bt&&be)){let Me={};["status","statusText","headers"].forEach(Ft=>{Me[Ft]=jt[Ft]});let $t=Zf.toFiniteNumber(jt.headers.get("content-length")),[rt,nr]=V&&cto($t,BPi(lto(V),!0))||[];jt=new n(EAf(jt.body,ZCy,rt,()=>{nr&&nr(),be&&be()}),Me)}re=re||"text";let ze=await l[Zf.findKey(l,re)||"text"](jt,P);return!bt&&be&&be(),await new Promise((Me,$t)=>{NVr(Me,$t,{data:ze,headers:J$.from(jt.headers),status:jt.status,statusText:jt.statusText,config:P,request:me})})}catch(Be){throw be&&be(),Be&&Be.name==="TypeError"&&/Load failed|fetch/i.test(Be.message)?Object.assign(new xm("Network Error",xm.ERR_NETWORK,P,me),{cause:Be.cause||Be}):xm.from(Be,Be&&Be.code,P,me)}}},obC=new Map,SAf=e=>{let t=e?e.env:{},{fetch:r,Request:n,Response:i}=t,a=[n,i,r],o=a.length,c=o,f,s,u=obC;for(;c--;)f=a[c],s=u.get(f),s===void 0&&u.set(f,s=c?new Map:abC(t)),u=s;return s},uKU=SAf();var DAf={http:GCy,xhr:YCy,fetch:{get:SAf}};Zf.forEach(DAf,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var rIy=e=>`- ${e}`,sbC=e=>Zf.isFunction(e)||e===null||e===!1,rIs={getAdapter:(e,t)=>{e=Zf.isArray(e)?e:[e];let{length:r}=e,n,i,a={};for(let o=0;o<r;o++){n=e[o];let c;if(i=n,!sbC(n)&&(i=DAf[(c=String(n)).toLowerCase()],i===void 0))throw new xm(`Unknown adapter '${c}'`);if(i&&(Zf.isFunction(i)||(i=i.get(t))))break;a[c||"#"+o]=i}if(!i){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 :
|
|
@@ -2404,7 +2404,7 @@ ${q}${z}${V}${kio}`});function m3s({message:e,error:t,logger:r,logLevel:n=iE.Err
|
|
|
2404
2404
|
Run ${Kf.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
|
|
2405
2405
|
Run ${Kf.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),dto(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function RNf({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!YYy(e))return;let i=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let o=a.sort((c,f)=>c.generatorName.localeCompare(f.generatorName)||c.currentVersion.localeCompare(f.currentVersion));for(let c of o)i+=`
|
|
2406
2406
|
${await $YC(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Kf.dim(c.currentVersion)+Kf.reset(" \u2192 ")+Kf.green(c.latestVersion);return i+=`
|
|
2407
|
-
`,n?dto(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function $YC(e){let r=await new $Yy.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 YYC({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await ZYy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let m=N4i(u.name,l),A=await Dqr({generatorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:a,context:l});A!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),c}let o={type:"multiApi",versions:{}};return await ZYy({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=N4i(s.name,u),m=await Dqr({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:i,includeMajor:a,context:u});m!=null&&(o.versions[c][f][s.name]={previousVersion:s.version,latestVersion:m})},generatorFilter:r,groupFilter:n}),o}async function ZYy({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await xqr({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(!(c==null||c.groups==null)){for(let f of c.groups)if(!(i!=null&&f.groupName!==i))for(let s of f.generators)n!=null&&s.name!==n||await r(a.workspaceName,f.groupName,s,o)}})}))}function kYy(e,t,r){let n=[];for(let[i,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${i} has an upgrade available...`);let f=Q3e(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),n.push({generatorName:o,generatorGroup:i,apiName:t,isUpgradeAvailable:f,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return n}async function w3s({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let o=[];if(e!=null){let c=await YYC({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a});if(c.type==="multiApi")for(let[f,s]of Object.entries(c.versions))o.push(...kYy(s,f,t.logger));else o.push(...kYy(c.versions,void 0,t.logger))}return o}var Jko=class extends Error{response;request;options;constructor(t,r,n){let i=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${i} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=n}};var nao=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var NNf=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",n=typeof globalThis.Request=="function";if(r&&n)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(i){if(i instanceof Error&&i.message==="unsupported BodyInit type")return!1;throw i}return e&&!t})(),eXy=typeof globalThis.AbortController=="function",tXy=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",rXy=typeof globalThis.ReadableStream=="function",nXy=typeof globalThis.FormData=="function",j3s=["get","post","put","patch","head","delete"],XYC=()=>{};XYC();var iXy={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},E3s=2147483647,aXy=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,S3s=Symbol("stop"),oXy={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},uXy={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 ZYC=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,n]of e)t+=aXy,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof n=="string"?new TextEncoder().encode(n).length:n.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},sXy=(e,t,r)=>{let n,i=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),n){i+=n.byteLength;let c=t===0?0:i/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,i),transferredBytes:i},n)}n=a},flush(){n&&(i+=n.byteLength,r?.({percent:1,totalBytes:Math.max(t,i),transferredBytes:i},n))}}))},cXy=(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(sXy(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},lXy=(e,t,r)=>{if(!e.body)return e;let n=ZYC(r??e.body);return new Request(e,{duplex:"half",body:sXy(e.body,n,t)})};var iao=e=>e!==null&&typeof e=="object";var Kko=(...e)=>{for(let t of e)if((!iao(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return zNf({},...e)},FNf=(e={},t={})=>{let r=new globalThis.Headers(e),n=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[a,o]of i.entries())n&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function D3s(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:zNf(e[r]??[],t[r]??[])}var xNf=(e={},t={})=>({beforeRequest:D3s(e,t,"beforeRequest"),beforeRetry:D3s(e,t,"beforeRetry"),afterResponse:D3s(e,t,"afterResponse"),beforeError:D3s(e,t,"beforeError")}),zNf=(...e)=>{let t={},r={},n={};for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(iao(i)){for(let[a,o]of Object.entries(i))iao(o)&&a in t&&(o=zNf(t[a],o)),t={...t,[a]:o};iao(i.hooks)&&(n=xNf(n,i.hooks),t.hooks=n),iao(i.headers)&&(r=FNf(r,i.headers),t.headers=r)}return t};var dXy=e=>j3s.includes(e)?e.toUpperCase():e,kYC=["get","put","head","delete","options","trace"],eXC=[408,413,429,500,502,503,504],tXC=[413,429,503],fXy={limit:2,methods:kYC,statusCodes:eXC,afterStatusCodes:tXC,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},pXy=(e={})=>{if(typeof e=="number")return{...fXy,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{...fXy,...e}};async function QNf(e,t,r,n){return new Promise((i,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new nao(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(o)})})}async function LNf(e,{signal:t}){return new Promise((r,n)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",i,{once:!0}));function i(){clearTimeout(a),n(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e)})}var _Xy=(e,t)=>{let r={};for(let n in t)!(n in uXy)&&!(n in oXy)&&!(n in e)&&(r[n]=t[n]);return r},hXy=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 $ko=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>E3s)throw new RangeError(`The \`timeout\` option cannot be greater than ${E3s}`);await Promise.resolve();let c=await n._fetch();for(let f of n._options.hooks.afterResponse){let s=await f(n.request,n._options,n._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(n._decorateResponse(c),!c.ok&&n._options.throwHttpErrors){let f=new Jko(c,n.request,n._options);for(let s of n._options.hooks.beforeError)f=await s(f);throw f}if(n._options.onDownloadProgress){if(typeof n._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!rXy)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return cXy(c.clone(),n._options.onDownloadProgress)}return c},o=(n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(i):i()).finally(async()=>{let c=n._originalRequest,f=[];c&&!c.bodyUsed&&f.push(c.body?.cancel()),n.request.bodyUsed||f.push(n.request.body?.cancel()),await Promise.all(f)});for(let[c,f]of Object.entries(iXy))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{n.request.headers.set("accept",n.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:FNf(this._input.headers,r.headers),hooks:xNf({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:dXy(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:pXy(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(eXy&&tXy){let n=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=n?AbortSignal.any([n,this.abortController.signal]):this.abortController.signal}if(NNf&&(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),hXy(this._options.searchParams)){let i="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,i);(nXy&&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(!NNf)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=lXy(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof nao)throw t;if(t instanceof Jko){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let n=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(n&&this._options.retry.afterStatusCodes.includes(t.response.status)){let i=Number(n)*1e3;Number.isNaN(i)?i=Date.parse(n)-Date.now():i>=Date.parse("2024-01-01")&&(i-=Date.now());let a=this._options.retry.maxRetryAfter??i;return i<a?i:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let n=Math.min(this._calculateRetryDelay(r),E3s);if(this._retryCount<1)throw r;await LNf(n,{signal:this._options.signal});for(let i of this._options.hooks.beforeRetry)if(await i({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===S3s)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let n=await r(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=_Xy(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):QNf(this._originalRequest,t,this.abortController,this._options)}};var UNf=e=>{let t=(r,n)=>$ko.create(r,Kko(e,n));for(let r of j3s)t[r]=(n,i)=>$ko.create(n,Kko(e,i,{method:r}));return t.create=r=>UNf(Kko(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),UNf(Kko(e,r))),t.stop=S3s,t},rXC=UNf(),yXy=rXC;var zXy=Gi(xXy(),1);function JNf(e){let t=(0,zXy.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var TZy=Gi(BZy(),1),qZy=Gi(JTr(),1),oFf=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},uFf=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function sFf(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??JNf(i),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,TZy.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 yXy(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new oFf(e):l}if(t.allVersions)return s;let u=new uFf(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(n&&!l)for(let[A,P]of Object.entries(s.versions))P.deprecated&&delete s.versions[A];if(!l){let A=Object.keys(s.versions);if(r=qZy.default.maxSatisfying(A,r),!r)throw u}let{time:m}=s;if(s=s.versions[r],s.time=m,!s)throw u}return s}async function teu(e,t){let{version:r}=await sFf(e.toLowerCase(),t);return r}async function A2i({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:teu(e.packageName,{version:t?"prerelease":"latest"})}var RZy=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Q3s=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=iE.Info;isLocal;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new P3s(t,r),this.isLocal=n??!1;let i=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(i==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.101.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Kf.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new oie}failWithoutThrowing(t,r){this.didSucceed=!1,m3s({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await rto()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await XYy({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
2407
|
+
`,n?dto(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function $YC(e){let r=await new $Yy.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 YYC({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await ZYy({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let m=N4i(u.name,l),A=await Dqr({generatorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:a,context:l});A!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),c}let o={type:"multiApi",versions:{}};return await ZYy({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=N4i(s.name,u),m=await Dqr({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:i,includeMajor:a,context:u});m!=null&&(o.versions[c][f][s.name]={previousVersion:s.version,latestVersion:m})},generatorFilter:r,groupFilter:n}),o}async function ZYy({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await xqr({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(!(c==null||c.groups==null)){for(let f of c.groups)if(!(i!=null&&f.groupName!==i))for(let s of f.generators)n!=null&&s.name!==n||await r(a.workspaceName,f.groupName,s,o)}})}))}function kYy(e,t,r){let n=[];for(let[i,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${i} has an upgrade available...`);let f=Q3e(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),n.push({generatorName:o,generatorGroup:i,apiName:t,isUpgradeAvailable:f,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return n}async function w3s({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a}){let o=[];if(e!=null){let c=await YYC({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:a});if(c.type==="multiApi")for(let[f,s]of Object.entries(c.versions))o.push(...kYy(s,f,t.logger));else o.push(...kYy(c.versions,void 0,t.logger))}return o}var Jko=class extends Error{response;request;options;constructor(t,r,n){let i=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${i} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=n}};var nao=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var NNf=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",n=typeof globalThis.Request=="function";if(r&&n)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(i){if(i instanceof Error&&i.message==="unsupported BodyInit type")return!1;throw i}return e&&!t})(),eXy=typeof globalThis.AbortController=="function",tXy=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",rXy=typeof globalThis.ReadableStream=="function",nXy=typeof globalThis.FormData=="function",j3s=["get","post","put","patch","head","delete"],XYC=()=>{};XYC();var iXy={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},E3s=2147483647,aXy=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,S3s=Symbol("stop"),oXy={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},uXy={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 ZYC=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,n]of e)t+=aXy,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof n=="string"?new TextEncoder().encode(n).length:n.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},sXy=(e,t,r)=>{let n,i=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),n){i+=n.byteLength;let c=t===0?0:i/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,i),transferredBytes:i},n)}n=a},flush(){n&&(i+=n.byteLength,r?.({percent:1,totalBytes:Math.max(t,i),transferredBytes:i},n))}}))},cXy=(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(sXy(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},lXy=(e,t,r)=>{if(!e.body)return e;let n=ZYC(r??e.body);return new Request(e,{duplex:"half",body:sXy(e.body,n,t)})};var iao=e=>e!==null&&typeof e=="object";var Kko=(...e)=>{for(let t of e)if((!iao(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return zNf({},...e)},FNf=(e={},t={})=>{let r=new globalThis.Headers(e),n=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[a,o]of i.entries())n&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function D3s(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:zNf(e[r]??[],t[r]??[])}var xNf=(e={},t={})=>({beforeRequest:D3s(e,t,"beforeRequest"),beforeRetry:D3s(e,t,"beforeRetry"),afterResponse:D3s(e,t,"afterResponse"),beforeError:D3s(e,t,"beforeError")}),zNf=(...e)=>{let t={},r={},n={};for(let i of e)if(Array.isArray(i))Array.isArray(t)||(t=[]),t=[...t,...i];else if(iao(i)){for(let[a,o]of Object.entries(i))iao(o)&&a in t&&(o=zNf(t[a],o)),t={...t,[a]:o};iao(i.hooks)&&(n=xNf(n,i.hooks),t.hooks=n),iao(i.headers)&&(r=FNf(r,i.headers),t.headers=r)}return t};var dXy=e=>j3s.includes(e)?e.toUpperCase():e,kYC=["get","put","head","delete","options","trace"],eXC=[408,413,429,500,502,503,504],tXC=[413,429,503],fXy={limit:2,methods:kYC,statusCodes:eXC,afterStatusCodes:tXC,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},pXy=(e={})=>{if(typeof e=="number")return{...fXy,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{...fXy,...e}};async function QNf(e,t,r,n){return new Promise((i,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new nao(e))},n.timeout);n.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(o)})})}async function LNf(e,{signal:t}){return new Promise((r,n)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",i,{once:!0}));function i(){clearTimeout(a),n(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e)})}var _Xy=(e,t)=>{let r={};for(let n in t)!(n in uXy)&&!(n in oXy)&&!(n in e)&&(r[n]=t[n]);return r},hXy=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 $ko=class e{static create(t,r){let n=new e(t,r),i=async()=>{if(typeof n._options.timeout=="number"&&n._options.timeout>E3s)throw new RangeError(`The \`timeout\` option cannot be greater than ${E3s}`);await Promise.resolve();let c=await n._fetch();for(let f of n._options.hooks.afterResponse){let s=await f(n.request,n._options,n._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(n._decorateResponse(c),!c.ok&&n._options.throwHttpErrors){let f=new Jko(c,n.request,n._options);for(let s of n._options.hooks.beforeError)f=await s(f);throw f}if(n._options.onDownloadProgress){if(typeof n._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!rXy)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return cXy(c.clone(),n._options.onDownloadProgress)}return c},o=(n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(i):i()).finally(async()=>{let c=n._originalRequest,f=[];c&&!c.bodyUsed&&f.push(c.body?.cancel()),n.request.bodyUsed||f.push(n.request.body?.cancel()),await Promise.all(f)});for(let[c,f]of Object.entries(iXy))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{n.request.headers.set("accept",n.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:FNf(this._input.headers,r.headers),hooks:xNf({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:dXy(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:pXy(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(eXy&&tXy){let n=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=n?AbortSignal.any([n,this.abortController.signal]):this.abortController.signal}if(NNf&&(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),hXy(this._options.searchParams)){let i="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,i);(nXy&&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(!NNf)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=lXy(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof nao)throw t;if(t instanceof Jko){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let n=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(n&&this._options.retry.afterStatusCodes.includes(t.response.status)){let i=Number(n)*1e3;Number.isNaN(i)?i=Date.parse(n)-Date.now():i>=Date.parse("2024-01-01")&&(i-=Date.now());let a=this._options.retry.maxRetryAfter??i;return i<a?i:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let n=Math.min(this._calculateRetryDelay(r),E3s);if(this._retryCount<1)throw r;await LNf(n,{signal:this._options.signal});for(let i of this._options.hooks.beforeRetry)if(await i({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===S3s)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let n=await r(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=_Xy(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):QNf(this._originalRequest,t,this.abortController,this._options)}};var UNf=e=>{let t=(r,n)=>$ko.create(r,Kko(e,n));for(let r of j3s)t[r]=(n,i)=>$ko.create(n,Kko(e,i,{method:r}));return t.create=r=>UNf(Kko(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),UNf(Kko(e,r))),t.stop=S3s,t},rXC=UNf(),yXy=rXC;var zXy=Gi(xXy(),1);function JNf(e){let t=(0,zXy.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var TZy=Gi(BZy(),1),qZy=Gi(JTr(),1),oFf=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},uFf=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function sFf(e,t={}){let{version:r="latest"}=t,{omitDeprecated:n=!0}=t,i=e.split("/")[0],a=t.registryUrl??JNf(i),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,TZy.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 yXy(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new oFf(e):l}if(t.allVersions)return s;let u=new uFf(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(n&&!l)for(let[A,P]of Object.entries(s.versions))P.deprecated&&delete s.versions[A];if(!l){let A=Object.keys(s.versions);if(r=qZy.default.maxSatisfying(A,r),!r)throw u}let{time:m}=s;if(s=s.versions[r],s.time=m,!s)throw u}return s}async function teu(e,t){let{version:r}=await sFf(e.toLowerCase(),t);return r}async function A2i({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:teu(e.packageName,{version:t?"prerelease":"latest"})}var RZy=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Q3s=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=iE.Info;isLocal;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new P3s(t,r),this.isLocal=n??!1;let i=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(i==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.101.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Kf.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new oie}failWithoutThrowing(t,r){this.didSucceed=!1,m3s({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await rto()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await XYy({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
2408
2408
|
`)||(r+=`
|
|
2409
2409
|
`),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=Wkl(t.map(n=>n.type==="docs"?"docs":n.workspaceName??"api"),n=>n.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new Lko(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let n=this.addTaskWithInit(t).start(),i;try{i=await r(n)}catch(a){throw a.message.includes("globalThis")?(n.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),n.failWithoutThrowing()):n.failWithoutThrowing(void 0,a),new oie}finally{n.finish()}return i}async instrumentPostHogEvent(t){this.isLocal||(await rto()).sendEvent(t)}logger=W5r((t,...r)=>this.log(t,...r));stderr=W5r((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=NZy(t.type==="docs"?"docs":t.workspaceName??"api"),n=1+(this.longestWorkspaceName!=null?NZy(this.longestWorkspaceName):r).length,i=r.padEnd(n),a=RZy[this.numTasks++%RZy.length],o=Kf.hex(a)(i);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===LV.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let n=t.filter(i=>$zi.indexOf(i.level)>=$zi.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===iE.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 A2i({cliEnvironment:this.environment,includePreReleases:t}),n=Q3e(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},a=await w3s({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await wNf({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Kf.yellow("?"),style:{answer:i=>Kf.cyan(i),message:i=>Kf.bold(i),highlight:i=>Kf.cyan(i)}}})}catch(n){throw n?.name==="ExitPromptError"?(this.logger.info(`
|
|
2410
2410
|
Cancelled by user.`),new oie):n}}async getInput(t){return await mNf({message:t.message,default:t.default})}};function NZy(e){return`[${e}]:`}var MRr=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:n,absoluteFilePath:i,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=n,this.absoluteFilePath=i,this.changelog=a}};var Wit=class extends MRr{definition;sources;type="fern";constructor({definition:t,sources:r,...n}){super(n),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var ovt={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!1,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1,wrapReferencesToNullableInOptional:!0,coerceOptionalSchemasToNullable:!0,groupEnvironmentsByHost:!1};function reu({options:e,overrides:t}){return{enableUniqueErrorsPerEndpoint:t?.enableUniqueErrorsPerEndpoint??e?.enableUniqueErrorsPerEndpoint??ovt.enableUniqueErrorsPerEndpoint,detectGlobalHeaders:t?.detectGlobalHeaders??e?.detectGlobalHeaders??ovt.detectGlobalHeaders,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??ovt.objectQueryParameters,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??ovt.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??ovt.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??ovt.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??ovt.inlinePathParameters,useBytesForBinaryResponse:t?.useBytesForBinaryResponse??e?.useBytesForBinaryResponse??ovt.useBytesForBinaryResponse,respectForwardCompatibleEnums:t?.respectForwardCompatibleEnums??e?.respectForwardCompatibleEnums??ovt.respectForwardCompatibleEnums,wrapReferencesToNullableInOptional:t?.wrapReferencesToNullableInOptional??e?.wrapReferencesToNullableInOptional??ovt.wrapReferencesToNullableInOptional,coerceOptionalSchemasToNullable:t?.coerceOptionalSchemasToNullable??e?.coerceOptionalSchemasToNullable??ovt.coerceOptionalSchemasToNullable,groupEnvironmentsByHost:t?.groupEnvironmentsByHost??e?.groupEnvironmentsByHost??ovt.groupEnvironmentsByHost}}var hwe={openapi:e=>({...e,type:"openapi",_visit:function(t){return hwe._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return hwe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"openapi":return t.openapi(e);case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var fao={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return fao._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var Vde={basic:e=>({...e,type:"basic",_visit:function(t){return Vde._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return Vde._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return Vde._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return Vde._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return Vde._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"query":return t.query(e);case"oauth":return t.oauth(e);default:return t._other(e)}}};var qS={primitive:e=>({value:e,type:"primitive",_visit:function(t){return qS._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return qS._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return qS._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return qS._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return qS._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return qS._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return qS._visit(this,t)}}),null:e=>({...e,type:"null",_visit:function(t){return qS._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return qS._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.value);case"object":return t.object(e);case"array":return t.array(e.value);case"map":return t.map(e.value);case"enum":return t.enum(e.value);case"literal":return t.literal(e.value);case"oneOf":return t.oneOf(e.value);case"null":return t.null(e);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var FO={int:e=>({value:e,type:"int",_visit:function(t){return FO._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return FO._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return FO._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return FO._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return FO._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return FO._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return FO._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return FO._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return FO._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return FO._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return FO._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e.value);case"int64":return t.int64(e.value);case"uint":return t.uint(e.value);case"uint64":return t.uint64(e.value);case"float":return t.float(e.value);case"double":return t.double(e.value);case"string":return t.string(e.value);case"datetime":return t.datetime(e.value);case"date":return t.date(e.value);case"base64":return t.base64(e.value);case"boolean":return t.boolean(e.value);default:return t._other(e)}}};var P2i={boolean:e=>({value:e,type:"boolean",_visit:function(t){return P2i._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return P2i._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var w2i={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return w2i._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return w2i._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undiscriminated":return t.undiscriminated(e.value);default:return t._other(e)}}};var L3s={};yf(L3s,{Availability:()=>Wde,CustomCodeSample:()=>IWr,EndpointExample:()=>uvt,EndpointResponseExample:()=>svt,HttpMethod:()=>Gde,LiteralSchemaValue:()=>oW,MultipartRequestPropertyEncoding:()=>fFf,MultipartSchema:()=>MWr,OneOfSchema:()=>BWr,Pagination:()=>Hit,PrimitiveSchemaValue:()=>Gq,Request:()=>BRr,Response:()=>Wbe,RetriesConfiguration:()=>neu,Schema:()=>f1,SupportedSdkLanguage:()=>Hde,WebhookHttpMethod:()=>lFf,WebsocketMessageOrigin:()=>cFf});var cFf={Client:"client",Server:"server",_visit:(e,t)=>{switch(e){case cFf.Client:return t.client();case cFf.Server:return t.server();default:return t._other()}}};var lFf={Get:"GET",Post:"POST",_visit:(e,t)=>{switch(e){case lFf.Get:return t.get();case lFf.Post:return t.post();default:return t._other()}}};var Wde={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case Wde.GenerallyAvailable:return t.generallyAvailable();case Wde.Beta:return t.beta();case Wde.Deprecated:return t.deprecated();default:return t._other()}}};var neu={disabled:e=>({value:e,type:"disabled",_visit:function(t){return neu._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"disabled":return t.disabled(e.value);default:return t._other(e)}}};var Hit={cursor:e=>({...e,type:"cursor",_visit:function(t){return Hit._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return Hit._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return Hit._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);case"custom":return t.custom(e);default:return t._other(e)}}};var IWr={language:e=>({...e,type:"language",_visit:function(t){return IWr._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return IWr._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"language":return t.language(e);case"sdk":return t.sdk(e);default:return t._other(e)}}};var Hde={Curl:"curl",Python:"python",Javascript:"javascript",Typescript:"typescript",Go:"go",Ruby:"ruby",Csharp:"csharp",Java:"java",Js:"js",Node:"node",Ts:"ts",Nodets:"nodets",Golang:"golang",Dotnet:"dotnet",Jvm:"jvm",_visit:(e,t)=>{switch(e){case Hde.Curl:return t.curl();case Hde.Python:return t.python();case Hde.Javascript:return t.javascript();case Hde.Typescript:return t.typescript();case Hde.Go:return t.go();case Hde.Ruby:return t.ruby();case Hde.Csharp:return t.csharp();case Hde.Java:return t.java();case Hde.Js:return t.js();case Hde.Node:return t.node();case Hde.Ts:return t.ts();case Hde.Nodets:return t.nodets();case Hde.Golang:return t.golang();case Hde.Dotnet:return t.dotnet();case Hde.Jvm:return t.jvm();default:return t._other()}}};var uvt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return uvt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return uvt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"unknown":return t.unknown(e.value);case"full":return t.full(e);default:return t._other(e)}}};var svt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return svt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return svt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"withStreaming":return t.withStreaming(e);case"withoutStreaming":return t.withoutStreaming(e.value);default:return t._other(e)}}};var Gde={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case Gde.Get:return t.get();case Gde.Post:return t.post();case Gde.Put:return t.put();case Gde.Patch:return t.patch();case Gde.Delete:return t.delete();case Gde.Head:return t.head();case Gde.Options:return t.options();case Gde.Trace:return t.trace();default:return t._other()}}};var BRr={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return BRr._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return BRr._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return BRr._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return BRr._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var fFf={Json:"json",Form:"form",_visit:(e,t)=>{switch(e){case fFf.Json:return t.json();case fFf.Form:return t.form();default:return t._other()}}};var MWr={file:e=>({...e,type:"file",_visit:function(t){return MWr._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return MWr._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e.value);default:return t._other(e)}}};var Wbe={file:e=>({...e,type:"file",_visit:function(t){return Wbe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Wbe._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return Wbe._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return Wbe._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return Wbe._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return Wbe._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return Wbe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var f1={primitive:e=>({...e,type:"primitive",_visit:function(t){return f1._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return f1._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return f1._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return f1._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return f1._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return f1._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return f1._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return f1._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return f1._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return f1._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return f1._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var Gq={int:e=>({...e,type:"int",_visit:function(t){return Gq._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return Gq._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return Gq._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return Gq._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return Gq._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return Gq._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return Gq._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return Gq._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return Gq._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return Gq._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return Gq._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint();case"uint64":return t.uint64();case"float":return t.float();case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime();case"date":return t.date();case"base64":return t.base64();case"boolean":return t.boolean(e);default:return t._other(e)}}};var oW={boolean:e=>({value:e,type:"boolean",_visit:function(t){return oW._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return oW._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var BWr={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return BWr._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return BWr._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var mIe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return mIe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return mIe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return mIe._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return mIe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var h9={file:e=>({...e,type:"file",_visit:function(t){return h9._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return h9._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return h9._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return h9._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return h9._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return h9._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return h9._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Mh={primitive:e=>({...e,type:"primitive",_visit:function(t){return Mh._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Mh._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Mh._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Mh._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Mh._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Mh._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Mh._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Mh._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Mh._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Mh._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Mh._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var Git={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Git._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Git._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var Z0={int:e=>({...e,type:"int",_visit:function(t){return Z0._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return Z0._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return Z0._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return Z0._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return Z0._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return Z0._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return Z0._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return Z0._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return Z0._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return Z0._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return Z0._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime(e);case"date":return t.date(e);case"base64":return t.base64(e);case"boolean":return t.boolean(e);default:return t._other(e)}}};var Wj={};yf(Wj,{AllOfPropertyConflict:()=>Fao,ArraySchema:()=>i4s,ArraySchemaWithExample:()=>R4s,Availability:()=>X3s,Base64WithExample:()=>I4s,BasicSecurityScheme:()=>k3s,BearerSecurityScheme:()=>ezs,BooleanSchema:()=>Zzs,BooleanWithExample:()=>M4s,BytesResponse:()=>Sao,CasingOverrides:()=>nzs,CommonProperty:()=>d4s,CommonPropertyWithExample:()=>W4s,CursorPagination:()=>Rzs,CustomCodeSample:()=>Tzs,CustomCodeSampleLanguage:()=>Izs,CustomCodeSampleSdk:()=>Bzs,CustomPagination:()=>Fzs,DateWithExample:()=>C4s,DatetimeWithExample:()=>D4s,DiscriminatedOneOfSchema:()=>l4s,DiscriminatedOneOfSchemaWithExample:()=>U4s,DoubleSchema:()=>Yzs,DoubleWithExample:()=>E4s,Encoding:()=>Y3s,Endpoint:()=>xzs,EndpointExample:()=>Mao,EndpointResponseExample:()=>Czs,EndpointSdkName:()=>RWr,EndpointSecurity:()=>gao,EndpointWithExample:()=>dky,EnumSchema:()=>yao,EnumSchemaWithExample:()=>T4s,EnumValue:()=>S2i,ErrorExample:()=>wzs,FernExample:()=>Ezs,FileResponse:()=>jao,FileSchema:()=>yzs,FloatWithExample:()=>j4s,FormUrlEncodedRequest:()=>Ozs,FullEndpointExample:()=>qzs,FullExample:()=>GQ,FullObjectExample:()=>fzs,FullOneOfExample:()=>pzs,GlobalHeader:()=>e4s,Header:()=>C2i,HeaderExample:()=>Iao,HeaderSecurityScheme:()=>tzs,HeaderWithExample:()=>B2i,HttpEndpointServer:()=>Dao,HttpError:()=>jzs,HttpErrorWithExample:()=>m4s,HttpMethod:()=>mao,IdempotencyHeader:()=>t4s,Int64WithExample:()=>A4s,IntSchema:()=>Kzs,IntWithExample:()=>O4s,JsonRequest:()=>mzs,JsonRequestWithExample:()=>y4s,JsonResponse:()=>Eao,JsonResponseWithExample:()=>Qao,KeyValuePair:()=>dzs,LiteralExample:()=>czs,LiteralSchema:()=>Nao,LiteralSchemaValue:()=>r4s,LongSchema:()=>$zs,MapSchema:()=>a4s,MapSchemaWithExample:()=>N4s,MultipartRequest:()=>wao,MultipartRequestProperty:()=>gzs,MultipartRequestPropertyEncoding:()=>bzs,MultipartSchema:()=>vzs,NamedFullExample:()=>lvt,Namespace:()=>izs,NamespaceId:()=>szs,NullExample:()=>lzs,NullableSchema:()=>u4s,NullableSchemaWithExample:()=>x4s,OauthSecurityScheme:()=>ozs,ObjectProperty:()=>c4s,ObjectPropertyConflictInfo:()=>xao,ObjectPropertyWithExample:()=>L4s,ObjectSchema:()=>n4s,ObjectSchemaWithExample:()=>z4s,OctetStreamRequest:()=>Pao,OffsetPagination:()=>Nzs,OneOfSchema:()=>s4s,OneOfSchemaWithExample:()=>Q4s,OpenApiIntermediateRepresentation:()=>lky,OpenApiSource:()=>G3s,OptionalSchema:()=>o4s,OptionalSchemaWithExample:()=>F4s,Pagination:()=>Bao,ParseFormUrlEncodedRequest:()=>v4s,ParseMultipartRequest:()=>h4s,ParseOctetStreamRequest:()=>_4s,PathParameter:()=>Oao,PathParameterExample:()=>Szs,PathParameterWithExample:()=>p4s,PrimitiveExample:()=>bao,PrimitiveSchema:()=>M2i,PrimitiveSchemaValue:()=>kzs,PrimitiveSchemaValueWithExample:()=>B4s,PrimitiveSchemaWithExample:()=>Lao,PropertyKey:()=>vao,ProtobufEncoding:()=>$3s,ProtobufSource:()=>J3s,QueryParameter:()=>Aao,QueryParameterExample:()=>Cao,QueryParameterWithExample:()=>zao,QuerySecurityScheme:()=>rzs,ReferencedSchema:()=>NWr,Request:()=>Azs,RequestWithExample:()=>b4s,Response:()=>Pzs,ResponseWithExample:()=>g4s,RetriesConfiguration:()=>Tao,Schema:()=>$I,SchemaId:()=>OIe,SchemaWithExample:()=>o6,Schemas:()=>Jzs,SdkGroup:()=>azs,SdkGroupInfo:()=>_zs,SdkGroupName:()=>D2i,SecurityScheme:()=>uzs,SecuritySchemeId:()=>hao,Server:()=>ueu,Source:()=>K3s,StatusCode:()=>TWr,StreamingResponseExample:()=>Dzs,StringSchema:()=>Xzs,StringSchemaWithExample:()=>S4s,SupportedSdkLanguage:()=>Mzs,Tag:()=>Z3s,TagId:()=>AIe,Tags:()=>hzs,TextResponse:()=>I2i,Uint64WithExample:()=>w4s,UintWithExample:()=>P4s,UnDiscriminatedOneOfSchema:()=>f4s,UnDiscriminatedOneOfSchemaWithExample:()=>V4s,UnknownSchemaWithExample:()=>q4s,Webhook:()=>zzs,WebhookExampleCall:()=>Rao,WebhookHttpMethod:()=>qao,WebhookWithExample:()=>pky,WebsocketChannel:()=>Gzs,WebsocketHandshake:()=>Qzs,WebsocketHandshakeWithExample:()=>fky,WebsocketMessageExample:()=>Wzs,WebsocketMessageOrigin:()=>Lzs,WebsocketMessageSchema:()=>Uzs,WebsocketServer:()=>Vzs,WebsocketSessionExample:()=>Hzs,WithAvailability:()=>nw,WithDescription:()=>bv,WithEncoding:()=>U3e,WithInline:()=>a6,WithName:()=>jD,WithNamespace:()=>RS,WithSdkGroupName:()=>$M,WithSdkMethodName:()=>qWr,WithSource:()=>AP,WithStatusCode:()=>cvt,WithTitle:()=>KM,commons:()=>yFf,example:()=>vFf,finalIr:()=>bFf,parseIr:()=>gFf});var yFf={};yf(yFf,{BasicSecurityScheme:()=>k3s,BearerSecurityScheme:()=>ezs,Encoding:()=>Y3s,HeaderSecurityScheme:()=>tzs,Namespace:()=>izs,NamespaceId:()=>szs,OauthSecurityScheme:()=>ozs,OpenApiSource:()=>G3s,ProtobufEncoding:()=>$3s,ProtobufSource:()=>J3s,QuerySecurityScheme:()=>rzs,SchemaId:()=>OIe,SdkGroup:()=>azs,SdkGroupName:()=>D2i,SecurityScheme:()=>uzs,SecuritySchemeId:()=>hao,Server:()=>ueu,Source:()=>K3s,StatusCode:()=>TWr,Tag:()=>Z3s,TagId:()=>AIe,WithAvailability:()=>nw,WithDescription:()=>bv,WithEncoding:()=>U3e,WithInline:()=>a6,WithName:()=>jD,WithNamespace:()=>RS,WithSdkGroupName:()=>$M,WithSdkMethodName:()=>qWr,WithSource:()=>AP,WithStatusCode:()=>cvt,WithTitle:()=>KM});var Wr={};yf(Wr,{JsonError:()=>dao,ParseError:()=>pao,any:()=>XZy,bigint:()=>xZy,boolean:()=>ZZy,booleanLiteral:()=>YZy,date:()=>zZy,discriminant:()=>uky,enum_:()=>V3s,getObjectLikeUtils:()=>TRr,getObjectUtils:()=>Lda,getSchemaUtils:()=>HQ,isProperty:()=>E2i,lazy:()=>QZy,lazyObject:()=>JZy,list:()=>H3s,number:()=>kZy,object:()=>W3s,objectWithoutOptionalProperties:()=>GZy,optional:()=>dFf,property:()=>UZy,record:()=>nky,set:()=>iky,string:()=>eky,stringLiteral:()=>$Zy,transform:()=>pFf,undiscriminatedUnion:()=>oky,union:()=>cky,unknown:()=>tky,withParsedProperties:()=>hFf});var Jq={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",OPTIONAL:"optional"};function s8(e,t){return`Expected ${t}. Received ${sZC(e)}.`}function sZC(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function Jde(e){return{...e,json:FZy(e.json),parse:FZy(e.parse)}}function FZy(e){return(t,r)=>{let n=e(t,r),{skipValidation:i=!1}=r??{};return!n.ok&&i?(console.warn(["Failed to validate.",...n.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
|
|
@@ -3011,7 +3011,7 @@ ${e}`)}return e}getContent(){let e=this.stringifyImports();return e.length>0?e+`
|
|
|
3011
3011
|
`)},e.heapify=function(t,r){var n=new e(r);return n.heapArray=t,n.init(),n},e.heappop=function(t,r){var n=new e(r);return n.heapArray=t,n.pop()},e.heappush=function(t,r,n){var i=new e(n);i.heapArray=t,i.push(r)},e.heappushpop=function(t,r,n){var i=new e(n);return i.heapArray=t,i.pushpop(r)},e.heapreplace=function(t,r,n){var i=new e(n);return i.heapArray=t,i.replace(r)},e.heaptop=function(t,r,n){r===void 0&&(r=1);var i=new e(n);return i.heapArray=t,i.top(r)},e.heapbottom=function(t,r,n){r===void 0&&(r=1);var i=new e(n);return i.heapArray=t,i.bottom(r)},e.nlargest=function(t,r,n){var i=new e(n);return i.heapArray=xIe([],Uwe(r),!1),i.init(),i.top(t)},e.nsmallest=function(t,r,n){var i=new e(n);return i.heapArray=xIe([],Uwe(r),!1),i.init(),i.bottom(t)},e.prototype.add=function(t){return this._sortNodeUp(this.heapArray.push(t)-1),this._applyLimit(),!0},e.prototype.addAll=function(t){var r,n=this.length;(r=this.heapArray).push.apply(r,xIe([],Uwe(t),!1));for(var i=this.length;n<i;++n)this._sortNodeUp(n);return this._applyLimit(),!0},e.prototype.bottom=function(t){return t===void 0&&(t=1),this.heapArray.length===0||t<=0?[]:this.heapArray.length===1?[this.heapArray[0]]:t>=this.heapArray.length?xIe([],Uwe(this.heapArray),!1):this._bottomN_push(~~t)},e.prototype.check=function(){var t=this;return this.heapArray.find(function(r,n){return!!t.getChildrenOf(n).find(function(i){return t.compare(r,i)>0})})},e.prototype.clear=function(){this.heapArray=[]},e.prototype.clone=function(){var t=new e(this.comparator());return t.heapArray=this.toArray(),t._limit=this._limit,t},e.prototype.comparator=function(){return this.compare},e.prototype.contains=function(t,r){return r===void 0&&(r=e.defaultIsEqual),this.indexOf(t,r)!==-1},e.prototype.init=function(t){t&&(this.heapArray=xIe([],Uwe(t),!1));for(var r=e.getParentIndexOf(this.length-1);r>=0;--r)this._sortNodeDown(r);this._applyLimit()},e.prototype.isEmpty=function(){return this.length===0},e.prototype.indexOf=function(t,r){if(r===void 0&&(r=e.defaultIsEqual),this.heapArray.length===0)return-1;for(var n=[],i=0;i<this.heapArray.length;){var a=this.heapArray[i];if(r(a,t))return i;this.compare(a,t)<=0&&n.push.apply(n,xIe([],Uwe(e.getChildrenIndexOf(i)),!1)),i=n.shift()||this.heapArray.length}return-1},e.prototype.indexOfEvery=function(t,r){if(r===void 0&&(r=e.defaultIsEqual),this.heapArray.length===0)return[];for(var n=[],i=[],a=0;a<this.heapArray.length;){var o=this.heapArray[a];r(o,t)?(i.push(a),n.push.apply(n,xIe([],Uwe(e.getChildrenIndexOf(a)),!1))):this.compare(o,t)<=0&&n.push.apply(n,xIe([],Uwe(e.getChildrenIndexOf(a)),!1)),a=n.shift()||this.heapArray.length}return i},e.prototype.leafs=function(){if(this.heapArray.length===0)return[];var t=e.getParentIndexOf(this.heapArray.length-1);return this.heapArray.slice(t+1)},Object.defineProperty(e.prototype,"length",{get:function(){return this.heapArray.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"limit",{get:function(){return this._limit},set:function(t){t<0||isNaN(t)?this._limit=0:this._limit=~~t,this._applyLimit()},enumerable:!1,configurable:!0}),e.prototype.setLimit=function(t){return this.limit=t,t<0||isNaN(t)?NaN:this._limit},e.prototype.peek=function(){return this.heapArray[0]},e.prototype.pop=function(){var t=this.heapArray.pop();return this.length>0&&t!==void 0?this.replace(t):t},e.prototype.push=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return t.length<1?!1:t.length===1?this.add(t[0]):this.addAll(t)},e.prototype.pushpop=function(t){var r;return this.compare(this.heapArray[0],t)<0&&(r=Uwe([this.heapArray[0],t],2),t=r[0],this.heapArray[0]=r[1],this._sortNodeDown(0)),t},e.prototype.remove=function(t,r){var n=this;if(r===void 0&&(r=e.defaultIsEqual),!this.heapArray.length)return!1;if(t===void 0)return this.pop(),!0;for(var i=[0];i.length;){var a=i.shift();if(r(this.heapArray[a],t))return a===0?this.pop():a===this.heapArray.length-1?this.heapArray.pop():(this.heapArray.splice(a,1,this.heapArray.pop()),this._sortNodeUp(a),this._sortNodeDown(a)),!0;if(this.compare(this.heapArray[a],t)<=0){var o=e.getChildrenIndexOf(a).filter(function(c){return c<n.heapArray.length});i.push.apply(i,xIe([],Uwe(o),!1))}}return!1},e.prototype.replace=function(t){var r=this.heapArray[0];return this.heapArray[0]=t,this._sortNodeDown(0),r},e.prototype.size=function(){return this.length},e.prototype.top=function(t){return t===void 0&&(t=1),this.heapArray.length===0||t<=0?[]:this.heapArray.length===1||t===1?[this.heapArray[0]]:t>=this.heapArray.length?xIe([],Uwe(this.heapArray),!1):this._topN_push(~~t)},e.prototype.toArray=function(){return xIe([],Uwe(this.heapArray),!1)},e.prototype.toString=function(){return this.heapArray.toString()},e.prototype.get=function(t){return this.heapArray[t]},e.prototype.getChildrenOf=function(t){var r=this;return e.getChildrenIndexOf(t).map(function(n){return r.heapArray[n]}).filter(function(n){return n!==void 0})},e.prototype.getParentOf=function(t){var r=e.getParentIndexOf(t);return this.heapArray[r]},e.prototype[Symbol.iterator]=function(){return uNM(this,function(t){switch(t.label){case 0:return this.length?[4,this.pop()]:[3,2];case 1:return t.sent(),[3,0];case 2:return[2]}})},e.prototype.iterator=function(){return this.toArray()},e.prototype._applyLimit=function(){if(this._limit>0&&this._limit<this.heapArray.length)for(var t=this.heapArray.length-this._limit;t;)this.heapArray.pop(),--t},e.prototype._bottomN_push=function(t){var r=new e(this.compare);r.limit=t,r.heapArray=this.heapArray.slice(-t),r.init();for(var n=this.heapArray.length-1-t,i=e.getParentIndexOf(n),a=[],o=n;o>i;--o)a.push(o);for(var c=this.heapArray;a.length;){var o=a.shift();this.compare(c[o],r.peek())>0&&(r.replace(c[o]),o%2&&a.push(e.getParentIndexOf(o)))}return r.toArray()},e.prototype._moveNode=function(t,r){var n=this.heapArray[t];this.heapArray[t]=this.heapArray[r],this.heapArray[r]=n},e.prototype._sortNodeDown=function(t){for(var r=this.heapArray.length,n=t,i=this.heapArray[t],a=2*t+1;a<r;){var o=a+1,c=o>=r||this.compare(this.heapArray[a],this.heapArray[o])<0?a:o;if(this.compare(this.heapArray[c],i)<0)this.heapArray[t]=this.heapArray[c],t=c,a=2*t+1;else break}t!==n&&(this.heapArray[t]=i)},e.prototype._sortNodeUp=function(t){for(var r=this.heapArray[t],n=t;t>0;){var i=e.getParentIndexOf(t);if(this.compare(r,this.heapArray[i])<0)this.heapArray[t]=this.heapArray[i],t=i;else break}t!==n&&(this.heapArray[t]=r)},e.prototype._topN_push=function(t){var r=new e(this._invertedCompare);r.limit=t;for(var n=[0],i=this.heapArray;n.length;){var a=n.shift();a<i.length&&(r.length<t?(r.push(i[a]),n.push.apply(n,xIe([],Uwe(e.getChildrenIndexOf(a)),!1))):this.compare(i[a],r.peek())<0&&(r.replace(i[a]),n.push.apply(n,xIe([],Uwe(e.getChildrenIndexOf(a)),!1))))}return r.toArray()},e.prototype._topN_fill=function(t){var r=this.heapArray,n=new e(this._invertedCompare);n.limit=t,n.heapArray=r.slice(0,t),n.init();for(var i=e.getParentIndexOf(t-1)+1,a=[],o=i;o<t;++o)a.push.apply(a,xIe([],Uwe(e.getChildrenIndexOf(o).filter(function(c){return c<r.length})),!1));for((t-1)%2&&a.push(t);a.length;){var o=a.shift();o<r.length&&this.compare(r[o],n.peek())<0&&(n.replace(r[o]),a.push.apply(a,xIe([],Uwe(e.getChildrenIndexOf(o)),!1)))}return n.toArray()},e.prototype._topN_heap=function(t){for(var r=this.clone(),n=[],i=0;i<t;++i)n.push(r.pop());return n},e.prototype._topIdxOf=function(t){if(!t.length)return-1;for(var r=0,n=t[r],i=1;i<t.length;++i){var a=this.compare(t[i],n);a<0&&(r=i,n=t[i])}return r},e.prototype._topOf=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var n=new e(this.compare);return n.init(t),n.peek()},e})();function fXv(e,t,r,n,i){if(r<=0)return[];let a=n??(c=>c),o=new cXv(sNM);for(let c of t){let f=lXv.default.get(a(e),a(c));i!=null&&f>i||(o.push({neighbor:c,distance:f}),o.size()>r&&o.pop())}return cNM(o).reverse().map(c=>c.neighbor)}function sNM(e,t){return e.distance!==t.distance?t.distance-e.distance:t.neighbor.localeCompare(e.neighbor)}function cNM(e){let t=[];for(;e.size()>0;){let r=e.pop();r&&t.push(r)}return t}var lNM=3,fNM=5;function DJs(e,t){let r=fXv(e,t,lNM,dNM,fNM),n=Array.from(t),i=`Failed to locate API section ${e}.`;switch(r.length){case 0:return i=`${i} No similar API sections found. Available API sections:`,n.length===0?`${i} []`:`${i} [
|
|
3012
3012
|
${n.map(a=>` ${a}`).join(`,
|
|
3013
3013
|
`)}
|
|
3014
|
-
]`;case 1:return`${i} Did you mean ${r[0]}?`;case 2:return`${i} Did you mean ${r[0]} or ${r[1]}?`;default:return`${i} Did you mean ${r[0]}, ${r[1]}, or ${r[2]}?`}}function CJs(e){return`API section ${e} is specified multiple times, however will be only rendered once.`}function dNM(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function IJs({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:n,apiDefinitionId:i}){if(n)return e;let a=[],o=new Map;return e.forEach(c=>{if(c.type!=="endpoint"){a.push(c);return}let f=t(c.endpointId);if(f==null)throw new Error(`Endpoint ${c.endpointId} not found`);let s=`${f.method} ${r(f)}`,u=o.get(s);if(o.set(s,c),u==null||u.isResponseStream===c.isResponseStream){a.push(c);return}let l=a.indexOf(u),m=c.isResponseStream?c:u,A=c.isResponseStream?u:c,P={id:_l.V1.NodeId(`${i}:${A.endpointId}+${m.endpointId}`),type:"endpointPair",stream:m,nonStream:A};a[l]=P}),a}function dXv({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:n,disableEndpointPairs:i,apiDefinitionId:a}){return IJs({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:n,disableEndpointPairs:i,apiDefinitionId:a}).filter(o=>o.type==="apiPackage"?o.children.length>0:!0)}function $co(e,t){if(t!=null)return F3(e.absoluteFilePath,t)}function pXv({docsWorkspace:e,page:t,parentSlug:r,idgen:n,markdownFilesToFullSlugs:i,markdownFilesToNoIndex:a,hideChildren:o}){let c=_l.V1.PageId($co(e,t.absolutePath)),f=r.apply({fullSlug:i.get(t.absolutePath)?.split("/"),urlSlug:t.slug??z$(t.title)});return{id:n.get(c),type:"page",pageId:c,title:t.title,slug:f.get(),icon:t.icon,hidden:o||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,availability:t.availability}}var MJs=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;markdownFilesToTags;workspace;hideChildren;parentAvailability;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#u;#c;#f;disableEndpointPairs;constructor(t,r,n,i,a,o,c,f,s,u,l,m){this.apiSection=t,this.docsWorkspace=i,this.taskContext=a,this.markdownFilesToFullSlugs=o,this.markdownFilesToNoIndex=c,this.markdownFilesToTags=f,this.workspace=u,this.hideChildren=l,this.parentAvailability=m,this.disableEndpointPairs=i.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=_l.V1.ApiDefinitionId(r.id),this.#e=x5i.create(r,a),this.#f=s,this.#u=this.apiSection.overviewAbsolutePath!=null?_l.V1.PageId($co(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let A=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#c=n.apply({fullSlug:A?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??z$(this.apiSection.title)});let P=this.apiSection.availability??this.parentAvailability;this.apiSection.navigation!=null&&(this.#s=this.#d(this.apiSection.navigation,this.#e.api.rootPackage,this.#c,P)),this.#s=this.#g(this.#s.map(C=>this.#m(C,P)),this.#O(this.#e.api.rootPackage,this.#c,P))}get(){let t=_l.V1.followRedirects(this.#s),r=new oya(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.workspace?.changelog?.files.map(n=>n.absoluteFilepath),this.docsWorkspace,this.#f).orUndefined();return{id:this.#f.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#u,paginated:this.apiSection.paginated,slug:this.#c.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#c,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:this.apiSection.availability??this.parentAvailability,pointsTo:t,noindex:void 0,playground:this.#v(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#d(t,r,n,i){r=this.#e.resolveSubpackage(r);let a=r!=null?x5i.getSubpackageId(r):void 0;return t.map(o=>S$f(o)._visit({link:c=>({id:this.#f.get(c.url),type:"link",title:c.text,icon:c.icon,url:_l.Url(c.url)}),page:c=>this.#p(c,n,i),package:c=>this.#l(c,n,i),section:c=>this.#_(c,n,i),item:({value:c})=>this.#y(c,a,n,i),endpoint:c=>this.#h(c,a,n,i)})).filter(pj)}#p(t,r,n){return pXv({page:{...t,availability:t.availability??n},parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#f,hideChildren:this.hideChildren})}#l(t,r,n){let i=t.overviewAbsolutePath!=null?_l.V1.PageId($co(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.availability??n,c=this.#e.getSubpackageByIdOrLocator(t.package);if(c!=null){let f=x5i.getSubpackageId(c),s=this.#f.get(i??`${this.apiDefinitionId}:${f}`);this.#a.has(f)&&this.taskContext.logger.warn(CJs(t.package)),this.#a.add(f),this.#o.set(s,[f]);let u=t.slug??(gGr(c)?c.urlSlug:this.apiSection.slug??z$(this.apiSection.title)),l=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),m=this.#d(t.contents,c,l,o);return{id:s,type:"apiPackage",children:m,title:t.title??(gGr(c)?c.displayName??Jco(c.name):this.apiSection.title),slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#v(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(DJs(t.package,this.#e.subpackageLocators));let f=t.slug??z$(t.package),s=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),u=this.#d(t.contents,void 0,s,o);return{id:this.#f.get(i??`${this.apiDefinitionId}:${z$(t.package)}`),type:"apiPackage",children:u,title:t.title??t.package,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#v(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#_(t,r,n){let i=t.overviewAbsolutePath!=null?_l.V1.PageId($co(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,c=this.#f.get(i??a??r.get()),f=t.referencedSubpackages.map(A=>{let P=this.#e.getSubpackageByIdOrLocator(A),C=P!=null?x5i.getSubpackageId(P):void 0;if(C===void 0){this.taskContext.logger.error(DJs(A,this.#e.subpackageLocators));return}return{subpackageId:C,locator:A}}).filter(A=>A!=null).filter(pj);this.#o.set(c,f.map(A=>A.subpackageId)),f.forEach(A=>{this.#a.has(A.subpackageId)&&this.taskContext.logger.error(CJs(A.locator)),this.#a.add(A.subpackageId)});let s=t.slug??z$(t.title),u=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:s}),l=t.availability??n,m=this.#d(t.contents,void 0,u,l);return{id:c,type:"apiPackage",children:m,title:t.title,slug:u.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:l,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:o,playground:this.#v(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#y(t,r,n,i){t=t.trim();let a=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator($A(t));if(a!=null){let o=x5i.getSubpackageId(a),c=this.#f.get(`${this.apiDefinitionId}:${o}`);this.#a.has(o)&&this.taskContext.logger.error(CJs(t)),this.#a.add(o),this.#o.set(c,[o]);let f=gGr(a)?a.urlSlug:"",s=n.apply({urlSlug:f});return{id:c,type:"apiPackage",children:[],title:gGr(a)?a.displayName??Jco(a.name):this.apiSection.title,slug:s.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:i,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#h({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,availability:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,n,i)}#h(t,r,n,i){let a=(r!=null?this.#e.subpackages.get(uge.SubpackageId(r))?.endpoints.get(uge.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(a!=null){let f=this.#e.getEndpointId(a);if(f==null)this.taskContext.logger.debug(`Expected Endpoint ID for ${a.id} at path: ${SJs(a.method,a.path.parts)}. Got undefined.`);else{this.#t.has(f)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${f}`),this.#t.add(f);let s=t.slug!=null?n.append(t.slug):n.apply(a);return{id:this.#f.get(`${this.apiDefinitionId}:${f}`),type:"endpoint",method:a.method,endpointId:f,apiDefinitionId:this.apiDefinitionId,availability:t.availability??_l.V1.convertAvailability(a.availability)??i,isResponseStream:a.response?.type.type==="stream",title:t.title??a.name??Lwe(a.path.parts),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#v(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let o=(r!=null?this.#e.subpackages.get(uge.SubpackageId(r))?.webSockets.get(uge.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(o!=null){let f=this.#e.getWebSocketId(o);if(f==null)this.taskContext.logger.error(`Expected WebSocket ID for ${o.id}. Got undefined.`);else return this.#r.has(f)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${f}`),this.#r.add(f),{id:this.#f.get(`${this.apiDefinitionId}:${f}`),type:"webSocket",webSocketId:f,title:t.title??o.name??Lwe(o.path.parts),slug:(t.slug!=null?n.append(t.slug):n.apply(o)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:_l.V1.convertAvailability(o.availability)??i,playground:this.#v(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let c=(r!=null?this.#e.subpackages.get(uge.SubpackageId(r))?.webhooks.get(uge.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(_l.V1.WebhookId(t.endpoint));if(c!=null){let f=this.#e.getWebhookId(c);if(f==null)this.taskContext.logger.error(`Expected Webhook ID for ${c.id}. Got undefined.`);else return this.#n.has(f)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${f}`),this.#n.add(f),{id:this.#f.get(`${this.apiDefinitionId}:${f}`),type:"webhook",webhookId:f,method:c.method,title:t.title??c.name??(0,_Xv.default)("/",...c.path),slug:(t.slug!=null?n.append(t.slug):n.apply(c)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:i,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#g(t,r){return dXv({left:t,right:r,findEndpointById:n=>this.#e.endpoints.get(n),stringifyEndpointPathParts:n=>Lwe(n.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#m(t,r){return I$f({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(n,i,a)=>this.#A(n,i,a),mergeAndFilterChildren:this.#g.bind(this)})}#O(t,r,n){let i=[];return t.endpoints.forEach(a=>{if(a.protocol?.type==="grpc"){let o=this.#e.getGrpcId(a);if(o==null){this.taskContext.logger.error(`Expected Grpc ID for ${a.id} at path: ${SJs(a.method,a.path.parts)}. Got undefined.`);return}if(this.#i.has(o))return;let c=r.apply(a);i.push({id:_l.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"grpc",grpcId:o,title:a.name??Lwe(a.path.parts),method:a.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:n,slug:c.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let o=this.#e.getEndpointId(a);if(o==null){this.taskContext.logger.debug(`Expected Endpoint ID for ${a.id} at path: ${SJs(a.method,a.path.parts)}. Got undefined.`);return}if(this.#t.has(o))return;let c=r.apply(a);i.push({id:_l.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"endpoint",method:a.method,endpointId:o,apiDefinitionId:this.apiDefinitionId,availability:_l.V1.convertAvailability(a.availability)??n,isResponseStream:a.response?.type.type==="stream",title:a.name??Lwe(a.path.parts),slug:c.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(a=>{let o=this.#e.getWebSocketId(a);if(o==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}this.#r.has(o)||i.push({id:_l.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webSocket",webSocketId:o,title:a.name??Lwe(a.path.parts),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:_l.V1.convertAvailability(a.availability)??n,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(a=>{let o=this.#e.getWebhookId(a);if(o==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}this.#n.has(o)||i.push({id:_l.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webhook",webhookId:o,method:a.method,title:a.name??Jco(a.id),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:n,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(a=>{if(this.#a.has(a))return;let o=this.#e.getSubpackageByIdOrLocator(a);if(o==null){this.taskContext.logger.error(`Subpackage ${a} not found in ${this.apiDefinitionId}`);return}let c=gGr(o)?r.apply(o):r,f=this.#A(a,c,n);f.length>0&&i.push({id:_l.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"apiPackage",children:f,title:gGr(o)?o.displayName??Jco(o.name):this.apiSection.title,slug:c.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:n,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((a,o)=>{let c=a.type==="endpointPair"?a.nonStream.title:a.title,f=o.type==="endpointPair"?o.nonStream.title:o.title;return c.localeCompare(f)})),i}#A(t,r,n){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.debug(DJs(t||"unknown",[])),[]):this.#O(i,r,n)}#v(t){return nXv(t)}mergeEndpointPairs(t){return IJs({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>Lwe(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var hXv=Gi(require("crypto"),1);function pNM(e){return hXv.default.createHash("sha256").update(e).digest("hex")}var BJs=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),pNM(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),n=0;for(;this.#t.has(r);)if(r=this.#r(t),n++,n>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return _l.V1.NodeId(this.#n(t))}};function yXv(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0,phpSdk:e.php!=null?{package:typeof e.php=="string"?e.php:e.php.package,version:typeof e.php=="string"?void 0:e.php.version}:void 0,swiftSdk:e.swift!=null?{package:typeof e.swift=="string"?e.swift:e.swift.package,version:typeof e.swift=="string"?void 0:e.swift.version}:void 0,rustSdk:e.rust!=null?{package:typeof e.rust=="string"?e.rust:e.rust.package,version:typeof e.rust=="string"?void 0:e.rust.version}:void 0}}var qJs=Gi(eit(),1);var TJs=Gi(eit(),1);function vXv({auth:e,playgroundConfig:t,context:r}){if(e.schemes.length>0&&e.schemes[0]!=null){let n=e.schemes[0];return bXv({scheme:n,playgroundConfig:t,context:r})}}function bXv({scheme:e,playgroundConfig:t,context:r}){switch(e.type){case"basic":return{type:"basicAuth",passwordName:e.password.originalName,usernameName:e.username.originalName,description:e.docs};case"bearer":return{type:"bearerAuth",tokenName:e.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:e.name.wireValue,nameOverride:e.name.name.originalName,prefix:e.prefix,description:e.docs};case"oauth":{let n=e.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(i=>i.name.originalName).join(".")||"$.body.access_token";return t?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:TJs.FernRegistry.EndpointId(e.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:TJs.FernRegistry.JqString(n),headerName:e.configuration.tokenHeader,tokenPrefix:e.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}case"inferred":{e.tokenEndpoint.authenticatedRequestHeaders.length>1&&r.logger.warn("Inferred auth scheme has multiple authenticated request headers. Only the `Authentication` or first header will be pushed to FDR.");let n=e.tokenEndpoint.authenticatedRequestHeaders.find(a=>a.headerName.toLowerCase()==="authorization");if(n)return n.responseProperty.propertyPath!=null&&n.responseProperty.propertyPath.length>0&&r.logger.warn("Inferred Authentication header has a property path. The property wirevalue will be pushed to FDR without property path."),{type:"bearerAuth",tokenName:n.responseProperty.property.name.wireValue,description:e.docs};let i=e.tokenEndpoint.authenticatedRequestHeaders[0];return i?{type:"header",headerWireValue:i.headerName,prefix:i.valuePrefix,nameOverride:void 0,description:e.docs}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:ks(e)}}function gXv({auth:e,playgroundConfig:t,context:r}){let n={};for(let i of e.schemes){let a=bXv({scheme:i,playgroundConfig:t,context:r});a!=null&&(n[TJs.FernRegistry.AuthSchemeId(i.key)]=a)}return n}var YI=Gi(eit(),1);var z5i=Gi(eit(),1);function OXv(e){return e._visit({alias:t=>({type:"alias",value:O4(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:Zie(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>z5i.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:z5i.FernRegistry.PropertyKey(r.name.wireValue),valueType:O4(r.valueType),availability:Zie(r.availability),propertyAccess:r.propertyAccess})),extraProperties:yNM(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(n=>({key:z5i.FernRegistry.PropertyKey(n.name.wireValue),valueType:O4(n.valueType),availability:Zie(n.availability),description:n.docs,propertyAccess:n.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(n=>({description:n.docs??void 0,discriminantValue:n.discriminantValue.wireValue,displayName:n.displayName,availability:n.availability!=null?Zie(n.availability):void 0,additionalProperties:np.types.SingleUnionTypeProperties._visit(n.shape,{samePropertiesAsObject:i=>({extends:[z5i.FernRegistry.TypeId(i.typeId)],properties:r,extraProperties:void 0}),singleProperty:i=>({extends:[],properties:[{key:z5i.FernRegistry.PropertyKey(i.name.wireValue),valueType:O4(i.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+n.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:O4(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function O4(e){return e._visit({container:t=>np.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:O4(r)}),map:({keyType:r,valueType:n})=>({type:"map",keyType:O4(r),valueType:O4(n)}),optional:r=>({type:"optional",itemType:O4(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:O4(r)}),set:r=>({type:"set",itemType:O4(r)}),literal:r=>np.types.Literal._visit(r,{boolean:n=>({type:"literal",value:{type:"booleanLiteral",value:n}}),string:n=>({type:"literal",value:{type:"stringLiteral",value:n}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:z5i.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:np.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>hNM(t.v2),float:()=>mXv(t.v2),double:()=>mXv(t.v2),string:()=>_NM(t.v2),long:()=>({type:"long",default:t.v2?.type==="long"?t.v2.default:void 0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),uint:()=>({type:"uint"}),uint64:()=>({type:"uint64"}),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function _NM(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function hNM(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="integer"?e.default:void 0}}function mXv(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="double"?e.default:void 0}}function yNM(e){return typeof e=="boolean"?e?Ih.unknown():void 0:typeof e=="string"?{type:"id",value:z5i.FernRegistry.TypeId(e),default:void 0}:O4(e)}function T$f(e,t){let r=e.service!=null?t.services[e.service]:void 0,n=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,i=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?bNM(r,t):[],webhooks:n!=null?vNM(n):[],websockets:i!=null?[gNM(i,t)]:[],types:e.types.map(a=>YI.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>YI.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?YI.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function vNM(e){return e.map(t=>{let r=[];return t.v2Examples!=null?(r.push(...Object.values(t.v2Examples.userSpecifiedExamples)),r.push(...Object.values(t.v2Examples.autogeneratedExamples))):r.push(...t.examples?.map(n=>({payload:n.payload.jsonExample}))??[]),{description:t.docs??void 0,id:YI.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??Zoa(t.name.originalName),headers:t.headers.map(n=>({description:n.docs??void 0,key:n.name.wireValue,type:O4(n.valueType),availability:Zie(n.availability)})),payload:SNM(t.payload),examples:r}})}function bNM(e,t){let r=[];for(let n of e.endpoints){let i=n.autogeneratedExamples[0],a=[];if(n.v2Examples!=null){let c,f=n.v2Examples.userSpecifiedExamples,s=n.v2Examples.autogeneratedExamples,u=Object.values(f).map(m=>m.response?.statusCode).filter((m,A,P)=>P.indexOf(m)!==A).length>0;for(let[m,A]of Object.entries(f))c=wXv({shouldUseExampleName:u,exampleName:A.displayName??m,example:A,irEndpoint:n,irService:e,ir:t}),c!=null&&a.push(c);let l=Object.values(s).map(m=>m.response?.statusCode).filter((m,A,P)=>P.indexOf(m)!==A).length>0;for(let[m,A]of Object.entries(s))c=wXv({shouldUseExampleName:l,exampleName:A.displayName??m,example:A,irEndpoint:n,irService:e,ir:t}),c!=null&&a.push(c)}else if(n.userSpecifiedExamples.length>0)a.push(...n.userSpecifiedExamples.map(c=>B$f({userSpecifiedExample:c,...i!=null&&{autogeneratedExample:i},irEndpoint:n,ir:t})).filter(pj));else if(i!=null){let c=B$f({autogeneratedExample:i,irEndpoint:n,ir:t});c!=null&&a.push(c)}else if(n.response?.body?.type==="fileDownload"){let c=Iio({ir:t,service:e,endpoint:{...n,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(c.type==="success"){let f=B$f({autogeneratedExample:c,irEndpoint:n,ir:t});if(f!=null){let s={...f,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let o={slug:void 0,availability:Zie(n.availability??e.availability),auth:n.auth,authV2:mNM(n.security),description:n.docs??void 0,method:wNM(n.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?YI.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?ONM({environmentsConfig:t.environments,endpoint:n}):void 0,id:YI.FernRegistry.EndpointId(n.name.originalName),originalEndpointId:n.id,name:n.displayName??Zoa(n.name.originalName),path:n.basePath!=null?{pathParameters:n.pathParameters.map(c=>({description:c.docs??void 0,key:YI.FernRegistry.PropertyKey(c.name.originalName),type:O4(c.valueType),availability:void 0})),parts:[...Yco(n.basePath),...Yco(n.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...n.pathParameters].map(c=>({description:c.docs??void 0,key:YI.FernRegistry.PropertyKey(c.name.originalName),type:O4(c.valueType),availability:void 0})),parts:[...t.basePath!=null?Yco(t.basePath):[],...Yco(e.basePath),...Yco(n.path)]},queryParameters:n.queryParameters.map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:O4(c.valueType),availability:Zie(c.availability)})),headers:[...e.headers,...n.headers].map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:O4(c.valueType),availability:Zie(c.availability)})),request:n.requestBody!=null?AXv(n.requestBody):void 0,requestsV2:{requests:n.v2RequestBodies?.requestBodies?.map(AXv).filter(pj)},response:n.response!=null?PXv(n.response):void 0,responsesV2:{responses:n.v2Responses?.responses?.map(PXv).filter(pj)},errors:void 0,errorsV2:jNM(n.errors,t),examples:a,protocol:n.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:n.id}),proto:c=>({type:"grpc",methodName:n.id,methodType:c.methodType}),_other:()=>{}})};r.push(o)}return r}function gNM(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let n=Object.values(e.v2Examples.userSpecifiedExamples),i=Object.values(e.v2Examples.autogeneratedExamples),a=n.length>0?n[0]:i[0];a!=null&&r.push({name:"",description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(o=>({type:YI.FernRegistry.api.v1.WebSocketMessageId(o.type),body:o.body}))??[]})}else r=e.examples.map(n=>({name:n.name?.originalName,description:n.docs,path:n.url,pathParameters:n.pathParameters.reduce((i,a)=>(i[YI.FernRegistry.PropertyKey(a.name.originalName)]=a.value.jsonExample,i),{}),queryParameters:n.queryParameters.reduce((i,a)=>(i[a.name.wireValue]=a.value.jsonExample,i),{}),headers:n.headers.reduce((i,a)=>(i[a.name.wireValue]=a.value.jsonExample,i),{}),messages:n.messages.map(i=>({type:YI.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}));return{auth:e.auth,availability:Zie(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?YI.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?ANM({environmentsConfig:t.environments,channel:e}):[],id:YI.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??Zoa(e.name.originalName),path:{pathParameters:e.pathParameters.map(n=>({description:n.docs??void 0,key:YI.FernRegistry.PropertyKey(n.name.originalName),type:O4(n.valueType),availability:void 0})),parts:Yco(e.path)},headers:e.headers.map(n=>({key:n.name.wireValue,type:O4(n.valueType),description:n.docs,availability:Zie(n.availability)})),queryParameters:e.queryParameters.map(n=>({description:n.docs??void 0,key:n.name.wireValue,type:O4(n.valueType),availability:Zie(n.availability)})),messages:e.messages.map(n=>({type:YI.FernRegistry.api.v1.WebSocketMessageId(n.type),displayName:n.displayName,origin:n.origin,body:DNM(n.body),description:n.docs,availability:Zie(n.availability)})),examples:r}}function mNM(e){if(e==null)return;if(e.length===0)return[];let t=new Set(e.flatMap(r=>Object.keys(r)));return Array.from(t).map(r=>YI.FernRegistry.AuthSchemeId(r))}function Zie(e){if(e!=null)switch(e.status){case"DEPRECATED":return YI.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return YI.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return YI.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return YI.FernRegistry.Availability.Beta;default:ks(e.status)}}function ONM({environmentsConfig:e,endpoint:t}){let r=e.environments,n=t.baseUrl,i=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:YI.FernRegistry.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(i!=null)return i.flatMap(o=>r.environments.map(c=>{let f=c.urls[o];if(f==null)throw new Error(`Encountered undefined server name "${o}" at endpoint ${t.method.toUpperCase()} ${t.path}. Expected environment ${c.id} to contain url for ${o}`);return{id:YI.FernRegistry.EnvironmentId(o),baseUrl:f}})).filter((o,c,f)=>c===f.findIndex(s=>s.id===o.id&&s.baseUrl===o.baseUrl));if(n==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let o=a.urls[n];if(o==null)throw new Error(`Encountered undefined server name "${n}" at endpoint ${t.method.toUpperCase()} ${t.path.head}. Expected environment ${a.id} to contain url for ${n}`);return{id:YI.FernRegistry.EnvironmentId(a.id),baseUrl:o}});default:ks(r)}}function ANM({environmentsConfig:e,channel:t}){let r=e.environments,n=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:YI.FernRegistry.EnvironmentId(i.id),baseUrl:PNM(i.url,"wss")}));case"multipleBaseUrls":if(n==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(i=>{let a=i.urls[n];if(a==null)throw new Error(`Encountered undefined server name ${a} at channel ${t.name.originalName} ${t.path.head}. Expected environment ${i.id} to contain url for ${n}`);return{id:YI.FernRegistry.EnvironmentId(i.id),baseUrl:a}});default:ks(r)}}function PNM(e,t){return e.replace(/^[^:]+/,t)}function wNM(e){return np.http.HttpMethod._visit(e,{get:()=>YI.FernRegistry.HttpMethod.Get,post:()=>YI.FernRegistry.HttpMethod.Post,put:()=>YI.FernRegistry.HttpMethod.Put,patch:()=>YI.FernRegistry.HttpMethod.Patch,delete:()=>YI.FernRegistry.HttpMethod.Delete,head:()=>YI.FernRegistry.HttpMethod.Head,_other:()=>{throw new Error("Unknown http method: "+e)}})}function Yco(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:YI.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function AXv(e){let t=np.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??Y8.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(n=>YI.FernRegistry.TypeId(n.typeId)),properties:r.properties.map(n=>({description:n.docs??void 0,key:YI.FernRegistry.PropertyKey(n.name.wireValue),valueType:O4(n.valueType),availability:Zie(n.availability),propertyAccess:n.propertyAccess})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??Y8.APPLICATION_JSON,shape:{type:"reference",value:O4(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(n=>n._visit({file:i=>{let a=i._visit({file:o=>({type:"file",key:YI.FernRegistry.PropertyKey(o.key.wireValue),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),fileArray:o=>({type:"fileArray",key:YI.FernRegistry.PropertyKey(o.key.wireValue),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:i=>({type:"bodyProperty",key:YI.FernRegistry.PropertyKey(i.name.wireValue),valueType:O4(i.valueType),contentType:i.contentType,description:i.docs??void 0,availability:Zie(i.availability),exploded:i.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(pj)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function PXv(e){if(e.body==null)return;let t,r=np.http.HttpResponseBody._visit(e.body,{fileDownload:n=>(t=n.docs,{type:"fileDownload",contentType:void 0}),json:n=>(t=n.docs,{type:"reference",value:O4(n.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:n=>{if(n.type==="text")return t=n.docs,{type:"streamingText"};if(n.type==="json")return t=n.docs,{type:"stream",shape:{type:"reference",value:O4(n.payload)},terminator:n.terminator};if(n.type==="sse")return t=n.docs,{type:"stream",shape:{type:"reference",value:O4(n.payload)},terminator:n.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function jNM(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let n of e){let i=t.errors[n.error.errorId];i&&r.push({type:i.type==null?void 0:{type:"alias",value:O4(i.type)},statusCode:i.statusCode,description:i.docs??void 0,name:i.displayName??i.name.name.originalName,availability:void 0,examples:CNM(i)})}else for(let n of e){let i=t.errors[n.error.errorId];if(i){let a=[{key:YI.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:i.discriminantValue.name.originalName}},description:i.docs,availability:void 0,propertyAccess:void 0}];i.type!=null&&a.push({key:YI.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:O4(i.type),description:i.docs,availability:void 0,propertyAccess:void 0}),r.push({type:i.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:i.statusCode,description:i.docs??void 0,availability:void 0,name:i.displayName??i.name.name.originalName,examples:i.examples.map(o=>({name:o.name?.originalName,responseBody:{type:"json",value:o.jsonExample},description:o.docs}))})}}return r}function wXv({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:n,irService:i,ir:a}){if(r==null)return;let o=s=>{if(s.valueType.type==="container"&&s.valueType.container.type==="literal")return s.valueType.container.literal._visit({boolean:u=>`${u}`,string:u=>u,_other:()=>{}});if(s.valueType.type==="container"&&s.valueType.container.type==="optional"&&s.valueType.container.optional.type==="container"&&s.valueType.container.optional.container.type==="literal")return s.valueType.container.optional.container.literal._visit({boolean:u=>`${u}`,string:u=>u,_other:()=>{}})},c={};a.headers.forEach(s=>{let u=o(s);u!=null&&(c[s.name.wireValue]=u)}),i.headers.forEach(s=>{let u=o(s);u!=null&&(c[s.name.wireValue]=u)}),n.headers.forEach(s=>{let u=o(s);u!=null&&(c[s.name.wireValue]=u)});let f=r.response?.body!=null?r.response.body.value:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:(()=>{let u={...r.request?.headers??{}};for(let[l,m]of Object.entries(c))(u[l]===null||u[l]===void 0)&&(u[l]=m);return u})(),requestBody:r.request?.requestBody,requestBodyV3:n.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:s=>{if(r.request==null)return;let u={};if(PR(r.request.requestBody)){let l=r.request.requestBody;for(let m of s.properties)m._visit({file:A=>{let P=l[A.key.wireValue];if(A.type==="file")u[A.key.wireValue]={type:"filename",value:typeof P=="string"?P:"<file1>"};else if(A.type==="fileArray"){let C=(Array.isArray(P)?P:[P]).filter(M=>typeof M=="string");u[A.key.wireValue]={type:"filenames",value:C}}},bodyProperty:A=>{if(A.style==="exploded"){let P=l[A.name.wireValue];u[A.name.wireValue]={type:"exploded",value:Array.isArray(P)?P:[P]}}else u[A.name.wireValue]={type:"json",value:l[A.name.wireValue]}},_other:c_t})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??n.response?.statusCode??200,responseBody:f??void 0,responseBodyV3:f!=null?r.response?.body?._visit({json:s=>({type:"json",value:s}),stream:s=>Array.isArray(s)&&s.length>0&&s.every(ENM)?{type:"sse",value:s}:{type:"stream",value:s},error:()=>{},_other:()=>{throw new Error("Unknown ExampleResponseBody: "+r.response?.body?.type)}}):void 0,codeSamples:r.codeSamples?.map(s=>({name:s.name,description:s.docs??void 0,install:void 0,language:s.language,code:s.code})).filter(pj)}}function ENM(e){return typeof e=="object"&&e!==null&&"event"in e&&typeof e?.event=="string"&&"data"in e}function B$f({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:n}){let i=n.headers.map(c=>{let f;if(c.valueType.type==="container"&&c.valueType.container.type==="literal"?f=c.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):c.valueType.type==="container"&&c.valueType.container.type==="optional"&&c.valueType.container.optional.type==="container"&&c.valueType.container.optional.container.type==="literal"&&(f=c.valueType.container.optional.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}})),f!=null)return{name:c.name,value:{jsonExample:f,shape:np.ExampleTypeReferenceShape.primitive(np.ExamplePrimitive.string({original:f}))}}}).filter(pj),a=e?.example??t?.example;if(a==null)return;let{codeSamples:o}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((c,f)=>(c[YI.FernRegistry.PropertyKey(f.name.originalName)]=f.value.jsonExample,c),{}),queryParameters:a.queryParameters.reduce((c,f)=>(c[f.name.wireValue]=f.value.jsonExample,c),{}),headers:[...i,...a.serviceHeaders,...a.endpointHeaders].reduce((c,f)=>(c[f.name.wireValue]=f.value.jsonExample,c),{}),requestBody:a.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,reference:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,fileUpload:c=>{if(a.request==null)return;let f={};if(PR(a.request.jsonExample)){let s=a.request.jsonExample;for(let u of c.properties)u._visit({file:l=>{let m=s[l.key.wireValue];if(l.type==="file")f[l.key.wireValue]={type:"filename",value:typeof m=="string"?m:"<file1>"};else if(l.type==="fileArray"){let A=(Array.isArray(m)?m:[m]).filter(P=>typeof P=="string");f[l.key.wireValue]={type:"filenames",value:A}}},bodyProperty:l=>{if(l.style==="exploded"){let m=s[l.name.wireValue];f[l.name.wireValue]={type:"exploded",value:Array.isArray(m)?m:[m]}}else f[l.name.wireValue]={type:"json",value:s[l.name.wireValue]}},_other:c_t})}return{type:"form",value:f}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??np.http.ExampleResponse._visit(a.response,{ok:c=>c._visit({body:f=>f!=null?200:204,stream:f=>f.length>0?200:204,sse:f=>f.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:({error:c})=>{let f=n.errors[c.errorId];if(f==null)throw new Error("Cannot find error "+c.errorId);return f.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:c=>c._visit({body:f=>f?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:c=>c.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:c=>c._visit({body:f=>f!=null?{type:"json",value:f.jsonExample}:void 0,stream:f=>({type:"stream",value:f.map(s=>s.jsonExample)}),sse:f=>({type:"sse",value:f.map(({event:s,data:u})=>({event:s,data:u.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:c=>c.body!=null?{type:"json",value:c.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:o?.map(c=>rit._visit(c,{language:f=>({language:f.language,code:f.code,name:f.name?.originalName,description:f.docs??void 0,install:f.install}),sdk:f=>({language:f.sdk,code:f.code,name:f.name?.originalName,description:f.docs??void 0,install:void 0}),_other:()=>{}})).filter(pj)}}function SNM(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>YI.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:YI.FernRegistry.PropertyKey(t.name.wireValue),valueType:O4(t.valueType),availability:Zie(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:O4(e.payloadType)},description:e.docs};default:ks(e)}}function DNM(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>YI.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:YI.FernRegistry.PropertyKey(t.name.wireValue),valueType:O4(t.valueType),availability:Zie(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:O4(e.bodyType)};default:ks(e)}}function CNM(e){let t=e.v2Examples?.userSpecifiedExamples,r=e.v2Examples?.autogeneratedExamples,n=e.examples;return t!=null&&Object.keys(t).length>0?Object.entries(t).map(([i,a])=>({name:i,responseBody:{type:"json",value:a},description:void 0})):r!=null&&Object.keys(r).length>0?Object.entries(r).map(([i,a])=>({name:i,responseBody:{type:"json",value:a},description:void 0})):n.length>0?n.map(i=>({name:i.name?.originalName,responseBody:{type:"json",value:i.jsonExample},description:i.docs})):[]}function zIe({ir:e,snippetsConfig:t,playgroundConfig:r,context:n}){let i={types:{},subpackages:{},rootPackage:T$f(e.rootPackage,e),auth:vXv({auth:e.auth,playgroundConfig:r,context:n}),authSchemes:gXv({auth:e.auth,playgroundConfig:r,context:n}),snippetsConfiguration:t,globalHeaders:e.headers.map(a=>({availability:Zie(a.availability),description:a.docs??void 0,key:a.name.wireValue,type:O4(a.valueType)})),navigation:void 0};for(let[a,o]of Object.entries(e.types))i.types[qJs.FernRegistry.TypeId(a)]={description:o.docs??void 0,name:o.name.name.originalName,shape:OXv(o.shape),availability:Zie(o.availability),displayName:o.name.displayName};for(let[a,o]of Object.entries(e.subpackages)){let c=o.service!=null?e.services[o.service]:void 0;i.subpackages[qJs.FernRegistry.api.v1.SubpackageId(a)]={subpackageId:qJs.FernRegistry.api.v1.SubpackageId(a),displayName:c?.displayName??o.displayName,name:o.name.originalName,description:o.docs??void 0,...T$f(o,e)}}return i}var q$f=Gi(eit(),1);async function R$f({organization:e,workspace:t,context:r,token:n,audiences:i,snippetsConfig:a,playgroundConfig:o}){let c=dG({workspace:t,audiences:i,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new uG(r,t)}),f=Cca({token:n.value}),s=zIe({ir:c,snippetsConfig:a,playgroundConfig:o,context:r}),u=await f.api.v1.register.registerApiDefinition({orgId:q$f.FernRegistry.OrgId(e),apiId:q$f.FernRegistry.ApiId(c.apiName.originalName),definition:s});if(u.ok)return r.logger.debug(`Registered API Definition ${u.body.apiDefinitionId}`),{id:u.body.apiDefinitionId,ir:c};switch(u.error.error){case"UnauthorizedError":case"UserNotInOrgError":return r.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return r.failAndThrow("Failed to register API",u.error)}}var INM=new LGs({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function auu({ir:e,apiDefinitionId:t,playgroundConfig:r,context:n}){return UGs(zGs(zIe({ir:e,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:r,context:n}),uge.ApiDefinitionId(t),INM))}function MNM(e){return e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function BNM(e){return/^(https?:)?\/\//.test(e)}async function TNM({pathToImage:e,absolutePathToFernFolder:t}){if(e==null||BNM(e))return;let r=wj(t,ds.of(e));if(await Qv(r))return r}async function uya({iconPath:e,filepaths:t,docsWorkspace:r}){if(MNM(e)){let n=await TNM({pathToImage:e,absolutePathToFernFolder:r.absoluteFilePath});n&&t.add(n)}}async function jXv({parsedDocsConfig:e,docsWorkspace:t}){let r=new Set;return e.logo?.dark!=null&&r.add(e.logo.dark),e.logo?.light!=null&&r.add(e.logo.light),e.favicon!=null&&r.add(e.favicon),e.backgroundImage?.dark!=null&&r.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&r.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&r.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&r.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&r.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(i=>{r.add(i.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(i=>{r.add(i.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(i=>{r.add(i.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(i=>{i.image!=null&&r.add(i.image)}),(await N$f({navigation:e.navigation,docsWorkspace:t})).forEach(i=>{r.add(i)}),e.js!=null&&e.js.files.forEach(i=>{r.add(i.absolutePath)}),r}async function N$f({navigation:e,docsWorkspace:t}){let r=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(n=>Xco({item:n,filepaths:r,docsWorkspace:t})));break;case"tabbed":await Promise.all(e.items.map(async n=>{n.icon!=null&&await uya({iconPath:n.icon,filepaths:r,docsWorkspace:t}),n.child.type==="layout"&&n.child.layout!=null?await Promise.all(n.child.layout.map(i=>Xco({item:i,filepaths:r,docsWorkspace:t}))):n.child.type==="variants"&&n.child.variants!=null&&await Promise.all(n.child.variants.flatMap(i=>{let a=[];return i.icon!=null&&a.push(uya({iconPath:i.icon,filepaths:r,docsWorkspace:t})),a.push(...i.layout.map(o=>Xco({item:o,filepaths:r,docsWorkspace:t}))),a}))}));break;case"versioned":await Promise.all(e.versions.map(async n=>{n.landingPage!=null&&await Xco({item:n.landingPage,filepaths:r,docsWorkspace:t}),(await N$f({navigation:n.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break;case"productgroup":await Promise.all(e.products.map(async n=>{n.landingPage!=null&&await Xco({item:n.landingPage,filepaths:r,docsWorkspace:t}),(await N$f({navigation:n.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break}return r}async function Xco({item:e,filepaths:t,docsWorkspace:r}){switch(e.type){case"page":e.icon!=null&&await uya({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"section":e.icon!=null&&await uya({iconPath:e.icon,filepaths:t,docsWorkspace:r}),await Promise.all(e.contents.map(n=>Xco({item:n,filepaths:t,docsWorkspace:r})));break;case"apiSection":e.icon!=null&&await uya({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"link":e.icon!=null&&await uya({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"changelog":e.icon!=null&&await uya({iconPath:e.icon,filepaths:t,docsWorkspace:r});break}}async function EXv({navigation:e,apiWorkspaces:t,visitor:r,context:n}){RNM(e)?await Promise.all(e.map(async i=>{NNM(i)?await Promise.all(i.layout.map(async a=>{await RJs({navigationItem:a,visitor:r,apiWorkspaces:t,context:n})})):FNM(i)&&await Promise.all(i.variants.flatMap(a=>a.layout.map(async o=>{await RJs({navigationItem:o,visitor:r,apiWorkspaces:t,context:n})})))})):await Promise.all(e.map(async i=>{await RJs({navigationItem:i,visitor:r,apiWorkspaces:t,context:n})}))}async function RJs({navigationItem:e,visitor:t,apiWorkspaces:r,context:n}){if(await O5r(e,{alphabetized:Qc,api:Qc,apiName:Qc,audiences:Qc,displayErrors:Qc,snippets:Qc,summary:Qc,title:Qc,layout:Qc,icon:Qc,slug:Qc,hidden:Qc,skipSlug:Qc,paginated:Qc,playground:Qc,flattened:Qc,path:Qc,page:Qc,featureFlag:Qc,openrpc:Qc,contents:async i=>{i!=null&&await Promise.all(i.map(async a=>{await RJs({navigationItem:a,visitor:t,apiWorkspaces:r,context:n})}))},viewers:Qc,orphaned:Qc,availability:Qc}),qNM(e)){let i=r.find(a=>a.workspaceName===e.apiName);i!=null&&await t.apiSection?.({config:e,workspace:i,context:n})}}function qNM(e){return e.api!=null}function RNM(e){return e[0]?.tab!=null}function NNM(e){return"layout"in e&&Array.isArray(e.layout)}function FNM(e){return"variants"in e&&Array.isArray(e.variants)}function Tse(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}DXv.default.extend(CXv.default);var xNM=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),SXv=0,zNM=async({ir:e})=>(SXv++,`${e.apiName.snakeCase.unsafeName}-${SXv}`);var WNr=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;targetAudiences;constructor({domain:t,docsWorkspace:r,ossWorkspaces:n,apiWorkspaces:i,taskContext:a,editThisPage:o,uploadFiles:c=xNM,registerApi:f=zNM,targetAudiences:s}){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=n,this.apiWorkspaces=i,this.taskContext=a,this.editThisPage=o,this.uploadFiles=c,this.registerApi=f,this.targetAudiences=s}#e=BJs.init();shouldIncludeByAudience(t){return!t||t.length===0||!this.targetAudiences||this.targetAudiences.length===0?!0:t.some(r=>this.targetAudiences?.includes(r))}applyAudienceFiltering(t){let r=this.filterNavigationByAudience(t.navigation);return{...t,navigation:r}}filterNavigationByAudience(t){return t.type==="untabbed"||t.type==="tabbed"?t:t.type==="versioned"?{...t,versions:t.versions.filter(r=>this.shouldIncludeByAudience(this.getRawVersionAudiences(r.version)))}:t.type==="productgroup"?{...t,products:t.products.filter(r=>{let n=this.getRawProductAudiences(r.product);return this.shouldIncludeByAudience(n)})}:t}getRawProductAudiences(t){let n=this.docsWorkspace.config.products?.find(i=>i.displayName===t);return IGo(n?.audiences)}getRawVersionAudiences(t){let n=this.docsWorkspace.config.versions?.find(i=>i.displayName===t);return IGo(n?.audiences)}_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;markdownFilesToTags=new Map;rawMarkdownFiles={};async resolve(){this._parsedDocsConfig=await _sf({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.targetAudiences&&this.targetAudiences.length>0&&(this._parsedDocsConfig=this.applyAudienceFiltering(this._parsedDocsConfig));for(let[l,m]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[ds.of(l)]=m;let t=this.parsedDocsConfig.experimental?.openapiParserV3,r=t!=null&&!t;this.docsWorkspace.config.navigation!=null&&r&&await EXv({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:l})=>{(await l.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(A=>{let P=F3(this.docsWorkspace.absoluteFilePath,A.absoluteFilepath);this.parsedDocsConfig.pages[P]=A.contents,this.rawMarkdownFiles[ds.of(P)]=A.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages),this.markdownFilesToTags=await this.getMarkdownFilesToTags(this.parsedDocsConfig.pages);for(let[l,m]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[ds.of(l)]=await GLf({markdown:m,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(l),context:this.taskContext});for(let[l,m]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[ds.of(l)]=await HLf({markdown:m,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(l),context:this.taskContext});let n=await jXv({parsedDocsConfig:this.parsedDocsConfig,docsWorkspace:this.docsWorkspace});for(let[l,m]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:A,markdown:P}=kpa(m,{absolutePathToMarkdownFile:this.resolveFilepath(l),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[ds.of(l)]=P;for(let C of A)n.add(C)}catch(A){throw this.taskContext.logger.error(`Failed to parse ${l}: ${A instanceof Error?A.message:String(A)}`),A}let i=Array.from(n).map(l=>({absoluteFilePath:l,relativeFilePath:this.toRelativeFilepath(l)}));(await this.uploadFiles(i)).forEach(l=>{this.collectedFileIds.set(l.absoluteFilePath,l.fileId)});let o=await this.toRootNode(),c=await this.getMarkdownFilesToFullyQualifiedPathNames(o);for(let[l,m]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[ds.of(l)]=WLf(m,this.collectedFileIds,c,{absolutePathToMarkdownFile:this.resolveFilepath(l),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let f={};Object.entries(this.parsedDocsConfig.pages).forEach(([l,m])=>{let A=QNM(this.editThisPage,l),P=this.rawMarkdownFiles[ds.of(l)];f[xNr.PageId(l)]={markdown:m,editThisPageUrl:A?xNr.Url(A):void 0,rawMarkdown:P}});let s=await this.convertDocsConfiguration(o),u={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let l=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async m=>{let A=wj(this.docsWorkspace.absoluteFilePath,m);(await(0,FJs.stat)(A)).isDirectory()?(await tbe(A,"{js,ts,jsx,tsx,md,mdx}")).forEach(M=>{l.add(M)}):A.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&l.add(A)})),u=Object.fromEntries(await Promise.all([...l].map(async m=>{let A=this.toRelativeFilepath(m),P=(await(0,FJs.readFile)(m)).toString();return[A,P]})))}return{config:s,pages:f,jsFiles:u}}resolveFilepath(t){if(t!=null)return wj(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return F3(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[n,i]of Object.entries(t)){let o=(0,NJs.default)(i).data.slug;typeof o=="string"&&o.trim().length>0&&r.set(this.resolveFilepath(n),o.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[n,i]of Object.entries(t)){let o=(0,NJs.default)(i).data.noindex;typeof o=="boolean"&&r.set(this.resolveFilepath(n),o)}return r}async getMarkdownFilesToTags(t){let r=new Map;for(let[n,i]of Object.entries(t)){let o=(0,NJs.default)(i).data.tags;typeof o=="string"?r.set(this.resolveFilepath(n),o.split(",").map(c=>c.trim()).filter(c=>c.length>0)):Array.isArray(o)&&r.set(this.resolveFilepath(n),o)}return r}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},n=_l.migrate.FernNavigationV1ToLatest.create().root(t);return _l.NodeCollector.collect(n).slugMap.forEach((a,o)=>{if(a==null||!_l.isPage(a))return;let c=_l.getPageId(a);if(c==null)return;let f=kl(this.docsWorkspace.absoluteFilePath,ds.of(c));r[f]=o}),r}getDocsBasePath(){return new URL(Tse(this.domain)).pathname}async convertDocsConfiguration(t){return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt,location:this.parsedDocsConfig.aiChatConfig.location,datasources:this.parsedDocsConfig.aiChatConfig.datasources?.map(n=>({url:n.url,title:n.title}))}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?xNr.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(n=>n.type==="dropdown"?{...n,links:n.links?.map(i=>({...i,url:xNr.Url(i.url)}))}:{...n,url:xNr.Url(n.url)}),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,settings:this.parsedDocsConfig.settings,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(n=>({...n,value:xNr.Url(n.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,languages:this.parsedDocsConfig.languages,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,pageActions:this.parsedDocsConfig.pageActions,theme:this.parsedDocsConfig.theme,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(t.apiName!=null){let n=this.apiWorkspaces.find(i=>i.workspaceName===t.apiName);if(n!=null)return n}else if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}getOpenApiWorkspaceForApiSection(t){if(t.apiName!=null){let n=this.ossWorkspaces.find(i=>i.workspaceName===t.apiName);if(n!=null)return n}else if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}async toRootNode(){let t=_l.V1.SlugGenerator.init(_l.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),n=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:n,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(i=>_l.RoleId(i)),featureFlags:void 0}}async toRootChild(t){return lua(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 n=_l.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({urlSlug:t.slug??z$(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(n),title:t.title,slug:i.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:n}){let i=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,n):void 0,o=r.type==="tabbed"?await this.convertTabbedNavigation(i,r.items,n):await this.toSidebarRootNode(i,r.items,n);return{type:"unversioned",id:i,landingPage:a,child:o}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((i,a)=>this.toVersionNode(i,r,a===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:n}){let i=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,n):void 0;return{id:i,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(o=>this.toProductNode(o,n)))}}async toProductNode(t,r){let n=r.setProductSlug(t.slug??z$(t.product)),i;switch(t.navigation.type){case"tabbed":i={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,n)};break;case"untabbed":i={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,n)};break;case"versioned":i=await this.toVersionedNode(t.navigation,n);break;default:ks(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:_l.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:n.get(),child:i,default:!1,hidden:void 0,authed:void 0,icon:t.icon,image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}async toVersionNode(t,r,n){let i=this.#e.get(t.version),a=r.setVersionSlug(t.slug??z$(t.version)),o=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(i,t.navigation.items,a):await this.toSidebarRootNode(i,t.navigation.items,a);return{type:"version",id:i,versionId:_l.VersionId(t.version),title:t.version,slug:a.get(),child:o,default:n,availability:t.availability!=null?LNM(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,n){let i=this.#e.get(`${t}/root`),a=await Promise.all(r.map(c=>this.toNavigationChild({prefix:i,item:c,parentSlug:n}))),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(`${i}/group`),type:"sidebarGroup",children:[]},o.push(s)),s.children.push(c)}),{type:"sidebarRoot",id:i,children:o}}async toSidebarRootNodeWithVariants(t,r,n){let i=this.#e.get(`${t}/root`);return{type:"sidebarRoot",id:i,children:[{type:"varianted",id:i,children:await Promise.all(r.map(a=>this.toVariantNode(a,i,n)))}]}}async toVariantNode(t,r,n){let i=this.#e.get(`${r}/variant/${t.slug??z$(t.title)}`),a=await Promise.all(t.layout.map(o=>this.toVariantChild(o,i,n)));return{type:"variant",id:i,variantId:_l.V1.VariantId(t.title),subtitle:t.subtitle??"",default:t.default??!1,image:void 0,children:a,title:t.title,slug:n.apply({urlSlug:t.slug??z$(t.title),skipUrlSlug:t.skipUrlSlug}).get(),icon:t.icon,hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,pointsTo:void 0}}async toVariantChild(t,r,n){return lua(t)._visit({page:async i=>this.toPageNode({item:i,parentSlug:n}),apiSection:async i=>this.toApiSectionNode({item:i,parentSlug:n}),section:async i=>this.toSectionNode({prefix:r,item:i,parentSlug:n}),link:async i=>this.toLinkNode(i),changelog:async i=>this.toChangelogNode(i,n)})}async toNavigationChild({prefix:t,item:r,parentSlug:n,hideChildren:i,parentAvailability:a}){return lua(r)._visit({page:async o=>this.toPageNode({item:o,parentSlug:n,hideChildren:i,parentAvailability:a}),apiSection:async o=>this.toApiSectionNode({item:o,parentSlug:n,hideChildren:i,parentAvailability:a}),section:async o=>this.toSectionNode({prefix:t,item:o,parentSlug:n,hideChildren:i,parentAvailability:a}),link:async o=>this.toLinkNode(o),changelog:async o=>this.toChangelogNode(o,n,i)})}async toApiSectionNode({item:t,parentSlug:r,hideChildren:n,parentAvailability:i}){let a=yXv(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;if(f==null||f)try{o=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1})}catch{}o==null&&(o=dG({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 uG(this.taskContext,c)}));let u=await this.registerApi({ir:o,snippetsConfig:a,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName,workspace:c}),l=auu({ir:o,apiDefinitionId:u,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext});return new MJs(t,l,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,c,n,i??t.availability).get()}async toChangelogNode(t,r,n){return new oya(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:n||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:_l.V1.Url(t.url),icon:t.icon}}async toPageNode({item:t,parentSlug:r,hideChildren:n,parentAvailability:i}){let a=_l.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??z$(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:t.title,icon:t.icon,hidden:n||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??i}}async toSectionNode({prefix:t,item:r,parentSlug:n,hideChildren:i,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?_l.PageId(o):void 0,f=this.#e.get(c??`${t}/section`),s=n.apply({urlSlug:r.slug??z$(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=i||r.hidden;return{id:f,type:"section",overviewPageId:c,slug:s.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:l,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(m=>this.toNavigationChild({prefix:f,item:m,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,n){let i=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:i,children:await Promise.all(r.map(a=>this.toTabChild(i,a,n)))}}async toTabChild(t,r,n){return lua(r.child)._visit({link:({href:i})=>this.toTabLinkNode(r,i),layout:({layout:i})=>this.toTabNode(t,r,i,n),changelog:({changelog:i})=>this.toTabChangelogNode(r,i,n),variants:({variants:i})=>this.toTabNodeWithVariants(t,r,i,n)})}async toTabChangelogNode(t,r,n){return new oya(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:n,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:_l.V1.Url(r),icon:t.icon}}async toTabNode(t,r,n,i){let a=this.#e.get(`${t}/tab`),o=i.apply({urlSlug:r.slug??z$(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,n,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,n,i){let a=this.#e.get(`${t}/tab`),o=i.apply({urlSlug:r.slug??z$(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,n,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):xNr.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:n}=this.parsedDocsConfig,i=r?.[t],a=n?.[t];return{logo:this.getFileId(i),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 n=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${n}`,variants:t.variants.map(i=>({fontFile:this.getFileId(i.absolutePath),weight:i.weight,style:i.style!=null?[i.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(pj),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:xNr.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":n,...i}=this.parsedDocsConfig.metadata;return{...i,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(n)}}convertFileIdOrUrl(t){if(t!=null)return lua(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:xNr.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function QNM(e,t){if(e?.github==null)return;let{owner:r,repo:n,branch:i="main",host:a="https://github.com"}=e.github;return`${Tse(a)}/${r}/${n}/blob/${i}/fern/${t}?plain=1`}function LNM(e){switch(e){case"beta":return _l.V1.NavigationV1Availability.Beta;case"deprecated":return _l.V1.NavigationV1Availability.Deprecated;case"ga":return _l.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return _l.V1.NavigationV1Availability.Stable;default:ks(e)}}async function fge(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof tY?t:null))).filter(pj)}async function F$f(e,t,r){if(e instanceof rHr){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof tY))return;let n=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1});return zIe({ir:n,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 Jj={};yf(Jj,{AlgoliaSearchIndex:()=>IXv,ApiDefinitionId:()=>XXv,ApiId:()=>tZv,Availability:()=>yZv,DocsConfigId:()=>rZv,EndpointId:()=>iZv,EndpointPathLiteral:()=>_Zv,EnvironmentId:()=>nZv,FileId:()=>cZv,HttpMethod:()=>hZv,IndexSegmentId:()=>MXv,JqString:()=>fZv,OrgId:()=>kXv,PageId:()=>sZv,PayloadLocation:()=>VZv,PropertyKey:()=>dZv,PullRequestState:()=>xZv,RoleId:()=>pZv,TokenId:()=>eZv,TypeId:()=>uZv,Url:()=>lZv,VersionId:()=>ZXv,WebSocketId:()=>aZv,WebhookId:()=>oZv,algolia:()=>x$f,api:()=>K$f,commons:()=>$$f,diff:()=>vZv,docs:()=>iYf,generators:()=>oYf,git:()=>uYf,navigation:()=>lYf,sdks:()=>dYf,snippets:()=>LZv,snippetsFactory:()=>UZv,templates:()=>pYf,tokens:()=>WZv});var x$f={};yf(x$f,{AlgoliaSearchIndex:()=>IXv,IndexSegmentId:()=>MXv});function IXv(e){return e}function MXv(e){return e}var K$f={};yf(K$f,{latest:()=>L$f,v1:()=>J$f});var L$f={};yf(L$f,{AuthSchemeId:()=>BXv,WebhookHttpMethod:()=>NXv,auth:()=>z$f,commons:()=>TXv,endpoint:()=>qXv,type_:()=>RXv,webhook:()=>Q$f,websocket:()=>FXv});var z$f={};yf(z$f,{AuthSchemeId:()=>BXv});function BXv(e){return e}var TXv={};var qXv={};var RXv={};var Q$f={};yf(Q$f,{WebhookHttpMethod:()=>NXv});var NXv={Get:"GET",Post:"POST"};var FXv={};var J$f={};yf(J$f,{SubpackageId:()=>JXv,WebSocketMessageId:()=>KXv,WebSocketMessageOrigin:()=>$Xv,WebhookHttpMethod:()=>YXv,commons:()=>G$f,db:()=>U$f,read:()=>W$f,register:()=>H$f});var U$f={};yf(U$f,{endpoint:()=>xXv});var xXv={};var W$f={};yf(W$f,{SupportedLanguage:()=>zXv,endpoint:()=>V$f,type_:()=>QXv,webhook:()=>LXv,websocket:()=>UXv});var V$f={};yf(V$f,{SupportedLanguage:()=>zXv});var zXv={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var QXv={};var LXv={};var UXv={};var H$f={};yf(H$f,{SourceId:()=>UNM,endpoint:()=>VXv,type_:()=>WXv,webhook:()=>HXv,websocket:()=>GXv});var VXv={};var WXv={};var HXv={};var GXv={};function UNM(e){return e}var G$f={};yf(G$f,{SubpackageId:()=>JXv,WebSocketMessageId:()=>KXv,WebSocketMessageOrigin:()=>$Xv,WebhookHttpMethod:()=>YXv});function JXv(e){return e}function KXv(e){return e}var $Xv={Client:"client",Server:"server"};var YXv={Get:"GET",Post:"POST"};var $$f={};yf($$f,{ApiDefinitionId:()=>XXv,ApiId:()=>tZv,Availability:()=>yZv,DocsConfigId:()=>rZv,EndpointId:()=>iZv,EndpointPathLiteral:()=>_Zv,EnvironmentId:()=>nZv,FileId:()=>cZv,HttpMethod:()=>hZv,JqString:()=>fZv,OrgId:()=>kXv,PageId:()=>sZv,PropertyKey:()=>dZv,RoleId:()=>pZv,TokenId:()=>eZv,TypeId:()=>uZv,Url:()=>lZv,VersionId:()=>ZXv,WebSocketId:()=>aZv,WebhookId:()=>oZv});function XXv(e){return e}function ZXv(e){return e}function kXv(e){return e}function eZv(e){return e}function tZv(e){return e}function rZv(e){return e}function nZv(e){return e}function iZv(e){return e}function aZv(e){return e}function oZv(e){return e}function uZv(e){return e}function sZv(e){return e}function cZv(e){return e}function lZv(e){return e}function fZv(e){return e}function dZv(e){return e}function pZv(e){return e}function _Zv(e){return e}var hZv={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var yZv={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var vZv={};var iYf={};yf(iYf,{latest:()=>Z$f,v1:()=>rYf,v2:()=>nYf});var Z$f={};yf(Z$f,{Layout:()=>gZv,MdxEngine:()=>VNM,TwitterCardSetting:()=>mZv,commons:()=>bZv,frontmatter:()=>Y$f,seo:()=>X$f});var VNM={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var bZv={};var Y$f={};yf(Y$f,{Layout:()=>gZv});var gZv={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var X$f={};yf(X$f,{TwitterCardSetting:()=>mZv});var mZv={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var rYf={};yf(rYf,{commons:()=>tYf,db:()=>OZv,read:()=>AZv,write:()=>k$f});var OZv={};var AZv={};var k$f={};yf(k$f,{DocsRegistrationId:()=>HNM,FilePath:()=>WNM});function WNM(e){return e}function HNM(e){return e}var tYf={};yf(tYf,{ContentAlignment:()=>EZv,FontDisplay:()=>MZv,FontStyle:()=>IZv,HeaderPosition:()=>SZv,JsScriptStrategy:()=>CZv,ProgrammingLanguage:()=>PZv,SearchbarPlacement:()=>wZv,TabsPlacement:()=>jZv,TwitterCardSetting:()=>DZv,commons:()=>eYf});var eYf={};yf(eYf,{ContentAlignment:()=>EZv,FontDisplay:()=>MZv,FontStyle:()=>IZv,HeaderPosition:()=>SZv,JsScriptStrategy:()=>CZv,ProgrammingLanguage:()=>PZv,SearchbarPlacement:()=>wZv,TabsPlacement:()=>jZv,TwitterCardSetting:()=>DZv});var PZv={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 wZv={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var jZv={Header:"HEADER",Sidebar:"SIDEBAR"};var EZv={Center:"CENTER",Left:"LEFT"};var SZv={Fixed:"FIXED",Absolute:"ABSOLUTE"};var DZv={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var CZv={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var IZv={Normal:"normal",Italic:"italic"};var MZv={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var nYf={};yf(nYf,{read:()=>BZv,write:()=>TZv});var BZv={};var TZv={};var oYf={};yf(oYf,{ChangelogEntryType:()=>RZv,GeneratorId:()=>GNM,GeneratorLanguage:()=>JNM,ReleaseType:()=>NZv,cli:()=>qZv,commons:()=>aYf,versions:()=>FZv});var qZv={};var aYf={};yf(aYf,{ChangelogEntryType:()=>RZv,ReleaseType:()=>NZv});var RZv={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var NZv={Ga:"GA",Rc:"RC"};var FZv={};function GNM(e){return e}var JNM={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var uYf={};yf(uYf,{PullRequestState:()=>xZv});var xZv={Open:"open",Closed:"closed",Merged:"merged"};var lYf={};yf(lYf,{latest:()=>sYf,v1:()=>cYf});var sYf={};yf(sYf,{NodeId:()=>YNM,ProductId:()=>XNM,Slug:()=>KNM,TabId:()=>$NM});function KNM(e){return e}function $NM(e){return e}function YNM(e){return e}function XNM(e){return e}var cYf={};yf(cYf,{NavigationV1Availability:()=>rFM,NodeId:()=>eFM,ProductId:()=>tFM,Slug:()=>ZNM,TabId:()=>kNM});function ZNM(e){return e}function kNM(e){return e}function eFM(e){return e}function tFM(e){return e}var rFM={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var dYf={};yf(dYf,{Language:()=>zZv,VersionBump:()=>QZv,versions:()=>fYf});var fYf={};yf(fYf,{Language:()=>zZv,VersionBump:()=>QZv});var zZv={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var QZv={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var LZv={};var UZv={};var pYf={};yf(pYf,{PayloadLocation:()=>VZv});var VZv={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var WZv={};var xJs=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function mA(e){return e!=null}var GZv=Gi(EWo(),1);var HZv=["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 mGr(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,GZv.default)(e,{special:HZv}).replace(/V\s(\d)/g,"V$1")}function JZv({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(n=>{let i=[];n.namespace?.forEach(a=>{let o=[...i,a],c=Jj.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:mGr(a)},i.push(a)})}),r}var zJs=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 KZv(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var LO=class extends zJs{context;accessPath;pathId;constructor({input:t,context:r,accessPath:n,pathId:i}){if(super(t,r),this.context=r,this.accessPath=[...n],this.pathId=i,i!=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 ${KZv(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})}}},hte=class extends LO{},Oze=class extends hte{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var $Zv="x-fern-base-path",YZv="x-fern-availability",QJs="x-fern-sdk-group-name",XZv="x-fern-global-headers",ZZv="x-fern-sdk-method-name";var kZv="x-fern-webhook",ekv="x-fern-access-token-locator",tkv="x-fern-basic",rkv="x-fern-username-variable-name",nkv="x-fern-password-variable-name",ikv="x-fern-bearer",akv="x-fern-token-variable-name",okv="x-fern-header",ukv="x-fern-header-variable-name",skv="x-fern-server-name",ckv="x-fern-examples";var LJs=class extends LO{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[skv]}convert(){if(this.serverName!=null)return this.serverName}};var UJs=class extends LO{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,n])=>t.replace(`{${r}}`,n.default),this.input.url)??this.input.url,this.serverName=new LJs({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:Jj.EnvironmentId(t),baseUrl:this.url}}};function Q5i(e,t,r,n){let i=e??[],a=new Set(i.map(c=>c.url)),o=(t??[]).filter(c=>!a.has(c.url)).map((c,f)=>new UJs({input:c,context:r,accessPath:n,pathId:["servers",`${f}`]}));return[...i,...o]}function Zx(e){return typeof e=="object"&&mA(e)&&"$ref"in e&&typeof e.$ref=="string"}function dge(e,t,r){let n=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),i=t;for(let a of n){if(typeof i!="object"||i==null)return r;i=i[a]}return i==null?r:(Zx(i)&&(i=dge(i,t,r)),i)}function VJs(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return Zx(r)?dge(r,t,void 0):r}var Ckv=Gi(gK());var WJs=class extends LO{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[tkv];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var HJs=class extends LO{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[nkv]}convert(){return this.passwordVariableName}};var GJs=class extends LO{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[rkv]}convert(){return this.usernameVariableName}};var JJs=class extends LO{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ikv];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var KJs=class extends LO{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[akv]}convert(){return this.tokenVariableName}};function lkv(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var fkv="x-bearer-format",dkv="x-code-samples",pkv="x-codeSamples";var $Js=class extends LO{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[fkv]}convert(){return this.bearerFormat}};var YJs=class extends LO{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[okv];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var XJs=class extends LO{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[ukv]}convert(){return this.headerVariableName}};function _kv(e){return e.type==="apiKey"}var Zco=class extends LO{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){_kv(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new YJs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new XJs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new $Js({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 ZJs(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function kJs(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function eKs(e){let t=[],r=e.length;if(r===0)return t;let n=0,i="",a="",o=!1;for(e.charCodeAt(0)===46&&(t.push(""),n++);n<r;){let c=e[n];a?c==="\\"&&n+1<r?(n++,i+=e[n]):c===a?a="":i+=c:o?c==='"'||c==="'"?a=c:c==="]"?(o=!1,t.push(i),i=""):i+=c:c==="["?(o=!0,i&&(t.push(i),i="")):c==="."?i&&(t.push(i),i=""):i+=c,n++}return i&&t.push(i),t}function ouu(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(qUs(t))return r;let n=e[t];return n===void 0?ZJs(t)?ouu(e,eKs(t),r):r:n}case"number":case"symbol":{typeof t=="number"&&(t=kJs(t));let n=e[t];return n===void 0?r:n}default:{if(Array.isArray(t))return nFM(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),qUs(t))return r;let n=e[t];return n===void 0?r:n}}}function nFM(e,t,r){if(t.length===0)return r;let n=e;for(let i=0;i<t.length;i++){if(n==null||qUs(t[i]))return r;n=n[t[i]]}return n===void 0?r:n}function hkv(e){return function(t){return ouu(t,e)}}function ykv(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function _Yf(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function vkv(e,t,r){return typeof r!="function"?kco(e,t):hYf(e,t,function n(i,a,o,c,f,s){let u=r(i,a,o,c,f,s);return u!==void 0?!!u:hYf(i,a,n,s)},new Map)}function hYf(e,t,r,n){if(t===e)return!0;switch(typeof t){case"object":return iFM(e,t,r,n);case"function":return Object.keys(t).length>0?hYf(e,{...t},r,n):_Yf(e,t);default:return ykv(e)?typeof t=="string"?t==="":!0:_Yf(e,t)}}function iFM(e,t,r,n){if(t==null)return!0;if(Array.isArray(t))return bkv(e,t,r,n);if(t instanceof Map)return aFM(e,t,r,n);if(t instanceof Set)return oFM(e,t,r,n);let i=Object.keys(t);if(e==null)return i.length===0;if(i.length===0)return!0;if(n&&n.has(t))return n.get(t)===e;n&&n.set(t,e);try{for(let a=0;a<i.length;a++){let o=i[a];if(!DUs(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,n))return!1}return!0}finally{n&&n.delete(t)}}function aFM(e,t,r,n){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[i,a]of t.entries()){let o=e.get(i);if(r(o,a,i,e,t,n)===!1)return!1}return!0}function bkv(e,t,r,n){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let i=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(i.has(f))continue;let s=e[f],u=!1;if(r(s,o,a,e,t,n)&&(u=!0),u){i.add(f),c=!0;break}}if(!c)return!1}return!0}function oFM(e,t,r,n){return t.size===0?!0:e instanceof Set?bkv([...e],[...t],r,n):!1}function kco(e,t){return vkv(e,t,()=>{})}function gkv(e){return e=Fjv(e),t=>kco(t,e)}function mkv(e,t){return Njv(e,(r,n,i,a)=>{let o=t?.(r,n,i,a);if(o!==void 0)return o;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case MUs:case IUs:case BUs:{let c=new e.constructor(e?.valueOf());return s5i(c,e),c}case TUs:{let c={};return s5i(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function Okv(e){return mkv(e)}var uFM=/^(?:0|[1-9]\d*)$/;function Akv(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 uFM.test(e)}}function Pkv(e){return e!==null&&typeof e=="object"&&CUs(e)==="[object Arguments]"}function wkv(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&ZJs(t)&&e?.[t]==null?r=eKs(t):r=[t],r.length===0)return!1;let n=e;for(let i=0;i<r.length;i++){let a=r[i];if((n==null||!Object.hasOwn(n,a))&&!((Array.isArray(n)||Pkv(n))&&Akv(a)&&a<n.length))return!1;n=n[a]}return!0}function jkv(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=kJs(e);break}}return t=Okv(t),function(r){let n=ouu(r,e);return n===void 0?wkv(r,e):t===void 0?n===void 0:kco(n,t)}}function Ekv(e){if(e==null)return AVs;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?jkv(e[0],e[1]):gkv(e);case"string":case"symbol":case"number":return hkv(e)}}function yYf(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(yYf).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function tKs(e,t=AVs){return e==null?{}:nge(e,Ekv(t))}function Skv(e){return typeof e!="string"&&(e=yYf(e)),e.replace(/['\u2019]/g,"")}function HNr(e){return zjv(Skv(e))}function e5(e){if(e!=null)return Array.isArray(e)?e:[e]}function rKs({namespace:e,path:t,method:r,sdkMethodName:n,operationId:i,displayName:a,isWebhook:o}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(n==null&&i==null&&a==null&&c==null))return`${sFM(o)}${cFM(e)}.${lFM(n,i,a,c)}`}function sFM(e){return e?"webhook_":"endpoint_"}function cFM(e){return e!=null?e5(e)?.map(t=>HNr(t)).join("/"):""}function lFM(e,t,r,n){return e||t||HNr(r??"")||HNr(n??"")}function Dkv(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var nKs=class extends LO{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[ekv],this.accessTokenLocator!=null&&(Dkv(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 iKs=class extends LO{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 Zco({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new nKs({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=rKs({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:Jj.EndpointId(r),accessTokenLocator:Jj.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var elo=class extends LO{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 WJs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new GJs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new HJs({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 JJs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new KJs({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":{lkv(this.input)?(this.authScheme="header",this.headerAuthNode=new Zco({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 iKs({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 Ckv.UnreachableCaseError(this.authScheme);return}}};var tlo=class extends LO{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(n=>{let i=VJs(n,this.context.document);if(i==null){this.context.errors.warning({message:`No auth scheme found for ${n}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new elo({input:i,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[n]=a):this.context.errors.warning({message:`No auth scheme found for ${n}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let n=r.convert();if(n!=null)return[t,n]}).filter(mA))}};var aKs=class extends LO{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[$Zv],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 Ikv(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function Mkv(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function rlo(e,t){return e==null?void 0:Object.entries(e).map(([n,i])=>e5(i.convert())?.map(o=>((t!=null&&!t.includes(n)||t==null&&!Ikv(i))&&(o=Mkv(o,o.type==="enum"?o.default:void 0)),{key:Jj.PropertyKey(n),valueShape:o,description:i.description,availability:i.availability?.convert()})).filter(mA)).filter(mA).reduce((n,i)=>n.flatMap(a=>i.length>0?i.map(o=>[...a,o]):[[...a]]),[[]])}function oKs(e,t){return Zx(e)?dge(e,t,void 0):e}function L5i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function Bkv(e,t){let r={...e};for(let[n,i]of Object.entries(t??{}))r[n]=[...r[n]??[],...i];return Object.keys(r).length>0?r:void 0}function Tkv(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let n of e)for(let i of t)r.push({path:n.path??i.path,responseStatusCode:n.responseStatusCode??i.responseStatusCode,name:n.name??i.name,description:n.description??i.description,pathParameters:n.pathParameters??i.pathParameters,queryParameters:n.queryParameters??i.queryParameters,headers:n.headers??i.headers,requestBody:n.requestBody??i.requestBody,responseBody:n.responseBody??i.responseBody,snippets:{...i.snippets,...n.snippets}});return r}var qkv=Gi(gK());var vYf=["decimal","decimal128","double-int","double","float","sf-decimal"],bYf=["int16","int32","int64","int8","sf-integer","uint8"],gYf=["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"],mYf=["beta","pre-release","in-development","generally-available","deprecated"];function yte(e,t){return Zx(e)?dge(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var Uvt=class extends LO{availability;constructor(t){super(t),this.safeParse()}parse(){if(yte(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[YZv];r!=null&&(mYf.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${mYf.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return Jj.Availability.Beta;case"in-development":return Jj.Availability.InDevelopment;case"generally-available":return Jj.Availability.GenerallyAvailable;case"deprecated":return Jj.Availability.Deprecated;case void 0:return;default:new qkv.UnreachableCaseError(this.availability);return}}};var sKs=Gi(gK());function Rkv(e){return typeof e=="object"&&e!=null&&"language"in e}function Nkv(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Fkv(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function xkv(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function uKs(e){return typeof e=="object"&&e!=null&&"event"in e}function OYf(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(uKs)}function U5i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function zkv(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var cKs=class extends LO{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,n,i,a){super(t),this.path=r,this.successResponseStatusCode=n,this.requestBodyByContentType=i,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[ckv]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([i,a])=>{let o=typeof r=="object"?r[i]:void 0;switch(a.multipartType){case"file":return U5i(o)?[i,{type:"filenameWithData",filename:o.filename,data:Jj.FileId(o.data)}]:o!=null?[i,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>U5i(c)))return[i,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:Jj.FileId(c.data)}))}];if(o.every(c=>typeof c=="string"))return[i,{type:"filenames",value:o}]}return}case"property":return[i,{type:"json",value:o}];case void 0:return;default:new sKs.UnreachableCaseError(a.multipartType);return}}).filter(mA))};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(n=>{let i=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(i!=null)switch(i.contentType){case"form-data":a=zkv(r.request)?this.convertFormDataExampleRequest(i,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 sKs.UnreachableCaseError(i.contentType);break}let o;switch(n.contentType){case"application/json":{Fkv(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{OYf(r.response)&&(o={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!OYf(r.response)&&xkv(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new sKs.UnreachableCaseError(n.contentType);break}let c={};r["code-samples"]?.forEach(l=>{Rkv(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})):Nkv(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,m])=>[Jj.PropertyKey(l),m])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,m])=>[Jj.PropertyKey(l),m])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([l,m])=>[Jj.PropertyKey(l),m]));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 uuu=class extends LO{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[QJs]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>Jj.api.v1.SubpackageId(HNr(r)))}};var lKs=class extends LO{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[ZZv]}convert(){return this.sdkMethodName}};var fKs=class extends LO{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[kZv]}convert(){return this.isWebhook}};var dKs=class extends LO{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[dkv]??[],...this.input[pkv]??[]],this.codeSamples.forEach(t=>{[...Object.values(Jj.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 sya=Gi(gK());function AYf(e,t){return Zx(e)?dge(e,t,void 0):e}function Qkv(e,t){return e.replace(/{(\w+)}/g,(r,n)=>t[n]!=null&&typeof t[n]=="string"||typeof t[n]=="number"||typeof t[n]=="boolean"?`${t[n]}`:r)}var vpe="",OGr=class extends LO{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,n,i,a){super(t),this.path=r,this.responseStatusCode=n,this.name=i,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,n])=>{let i=this.resolvedRequestInput?.value[r];switch(n.multipartType){case"file":return t&&(U5i(i)||typeof i=="string");case"files":return t&&Array.isArray(i)&&i.every(a=>U5i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new sya.UnreachableCaseError(n.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=AYf(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=AYf(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 sya.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(uKs)){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 sya.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,n])=>{let i=this.resolvedRequestInput?.value?.[r];switch(n.multipartType){case"file":return U5i(i)?[r,{type:"filenameWithData",filename:i.filename,data:Jj.FileId(i.data)}]:[r,{type:"filename",value:i}];case"files":{if(Array.isArray(i)){if(i.every(a=>U5i(a)))return[r,{type:"filenamesWithData",value:i.map(a=>({filename:a.filename,data:Jj.FileId(a.data)}))}];if(i.every(a=>typeof a=="string"))return[r,{type:"filenames",value:i}]}return}case"property":return[r,{type:"json",value:i}];case void 0:return;default:new sya.UnreachableCaseError(n.multipartType);return}}).filter(mA))};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 sya.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 sya.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let n=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([o,c])=>[o,c.example({includeOptionals:!1,override:o})]));n=Object.keys(n).length>0?n:void 0;let i=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(mA));i=Object.keys(i).length>0?i: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(mA));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&i==null&&n==null))return{path:Qkv(this.path,n??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?mGr(this.name):this.summary!=null?mGr(this.summary):void 0,description:this.convertDescription(),pathParameters:n,queryParameters:i,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function Lkv(e,t){return Zx(e)?dge(e,t,void 0):e}var eeb=Gi(gK());var Ukv="#/components/schemas/";function nlo(e){if(e.$ref.startsWith(Ukv))return e.$ref.replace(Ukv,"")}function eEi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function V5i(e){return typeof e.type=="string"&&e.type==="array"}function Vkv(e){return e.type==="boolean"}function Wkv(e){return e.type==="integer"}function W5i(e){return!Array.isArray(e.type)&&!V5i(e)}function Hkv(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||W5i(t)||V5i(t))}function Gkv(e){return"nullable"in e&&typeof e.nullable=="boolean"}function Jkv(e){return e.type==="null"}function Kkv(e){return e.type==="number"}function PYf(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function $kv(e){return e.type==="string"}var pKs=class extends Oze{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new LU({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 e5(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 _Ks=class extends hte{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 Uvt({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 hKs=class extends Oze{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 LU({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(mA)}convert(){if(this.typeNodes==null)return;let n=this.typeNodes.map(i=>e5(i.convert())?.map(o=>({displayName:i.name,shape:o,description:i.description,availability:i.availability?.convert()}))).filter(mA).reduce((i,a)=>i.flatMap(o=>a.length>0?a.map(c=>[...o,c]):[[...o]]),[[]]).map(i=>({type:"undiscriminatedUnion",variants:i}));return this.nullable?n.map(eEi).filter(mA):n}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function yKs(e){return e!=null&&e.length>0?e:[void 0]}var ilo=class extends Oze{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 LU({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 LU({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(Zx(t))return nlo(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([n,i])=>[n,new LU({input:i,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",n],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(mA))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return rlo(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}}}]:e5(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(mA)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(n=>yKs(r).map(i=>(this.extends==null||this.extends.length===0)&&n.length===0&&i!=null?{type:"alias",value:i}:{type:"object",extends:this.extends.map(a=>Jj.TypeId(a)),properties:n,extraProperties:i}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(n=>{let i=yte(n,this.context.document);i!=null&&(r={...r,...Object.fromEntries(Object.entries(i.properties??{}).map(([a,o])=>[a,new LU({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((n,i)=>{let a=r?.[i];return n[i]=a?.example({includeOptionals:t,override:i}),n},{}):Object.entries(r).reduce((n,[i,a])=>(n[i]=a?.example({includeOptionals:t,override:i}),n),{}))}};var vKs=class extends Oze{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=>yte(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>yte(t,this.context.document)?.type!=="null"?new LU({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(mA);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(([n,i])=>{let a=yte({$ref:i},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${i}`,path:[...this.accessPath,"discriminator","mapping",n]});return}r[n]=new LU({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",n],pathId:n,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let i=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(mA);return this.isNullable&&i!=null?i.map(eEi).filter(mA):i}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:Jj.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([i,a])=>e5(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:i,displayName:a.name??mGr(i),availability:a.availability?.convert(),description:a.description,...c}}).filter(mA)).filter(mA)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(i=>e5(i.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?mGr(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:i.name??(o.type==="alias"&&o.value.type==="id"?mGr(o.value.id):c),shape:o,description:i.description,availability:i.availability?.convert()}}).filter(mA)).filter(mA)}:void 0,n=this.isNullable?eEi(r):r;return n!=null?[n]: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 bKs=class extends hte{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 H5i=class extends hte{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,n)=>{if(t){if(Zx(r)){let i=yte(r,this.context.document);r=typeof i=="string"?i:typeof i?.default=="string"?i?.default:typeof i?.example=="string"?i.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${n}]`]}),t=!1;return}return r}}).filter(mA),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 Ykv=Gi(gK());function fFM(e){return bYf.includes(e)}var gKs=class extends hte{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&&(fFM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${bYf.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 Ykv.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 mKs=class extends hte{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return eEi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var Xkv=Gi(gK());function dFM(e){return vYf.includes(e)}var OKs=class extends hte{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&&(dFM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${vYf.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 Xkv.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 Zkv=Gi(gK());function pFM(e){return gYf.includes(e)}var AKs=class extends hte{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 Zkv.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&&(pFM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${gYf.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new H5i({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 kkv=Gi(gK());var PKs=class extends hte{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,kkv.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var cya=class extends Oze{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=nlo(this.input);let t=yte(this.input,this.context.document);t?.enum!=null&&W5i(t)&&(this.maybeEnumConverterNode=new H5i({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:Jj.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=yte(this.input,this.context.document);if(r!=null)return new LU({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var LU=class e extends Oze{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 Uvt({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),W5i(this.input)&&Gkv(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),Zx(this.input)){let t=nlo(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 cya({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 _Ks({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(Hkv(this.input))this.typeShapeNode=new hKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(W5i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new vKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(PYf(this.input)&&this.input.allOf!=null)this.typeShapeNode=new ilo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(W5i(this.input)&&this.input.enum!=null)this.typeShapeNode=new H5i({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":PYf(this.input)&&(this.typeShapeNode=new ilo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":V5i(this.input)&&(this.typeShapeNode=new pKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":Vkv(this.input)&&(this.typeShapeNode=new bKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":Wkv(this.input)&&(this.typeShapeNode=new gKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":Kkv(this.input)&&(this.typeShapeNode=new OKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":$kv(this.input)&&(this.typeShapeNode=new AKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":Jkv(this.input)&&(this.typeShapeNode=new mKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new eeb.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 ilo({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 PKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!Zx(this.input)&&(!V5i(this.input)&&this.input==null||V5i(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=e5(t)?.map(n=>this.nullable?eEi(n):n).filter(mA);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function G5i(e){if(e!=null)return rlo(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(mA))}var AGr=class extends hte{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;Zx(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 Uvt({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new LU({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let n=Lkv(this.input,this.context.document);this.inputExample=n?.example??Object.values(n?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function teb(e,t){return Zx(e)?dge(e,t,void 0):e}var wYf=Gi(gK());function wKs(e){let{uniqueId:t,type:r,contextTypes:n,description:i,availability:a}=e;n[Jj.TypeId(t)]={name:t,shape:r,description:i,availability:a}}var reb=Gi(Ckl(),1),alo=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,n,i,a,o){this.type=t,this.subtype=r,this.essence=n,this.parameters=i,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=reb.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 _FM(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var jKs=class extends LO{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 LU({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),_FM(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],n)=>{let i;if(Zx(r)?i=VJs(r.$ref,this.context.document):i=r,i!=null)return[t,new elo({input:i,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${n}`]})]}).filter(mA)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let n=r.convert();if(n!=null)return[Jj.api.latest.AuthSchemeId(t),n]}).filter(mA)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let n=r.name??t,i=e5(r.convert());return i==null?[t,void 0]:[Jj.TypeId(t),{name:n,shape:i[0],description:r.description,availability:void 0}]}).filter(([t,r])=>mA(r))):void 0}}};var EKs=class extends LU{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=yte(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${Zx(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=yte(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 SKs=class extends LO{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 n=yte(this.input.schema,this.context.document);this.availability=new Uvt({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=Zx(this.input.schema)?new cya({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 i=alo.parse(t);i?.containsJSON()?(this.contentType="json",this.schema=this.schema??new LU({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):i?.isOctetStream()?(this.contentType="bytes",this.isOptional=n?.required==null):i?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=n?.required,this.fields=Object.fromEntries(Object.entries(n?.properties??{}).map(([a,o])=>{if(o!=null)return[a,new EKs({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(mA))):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?{[vpe]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[vpe]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:e5(t)?.map(n=>{let i=n.type;switch(i){case"object":case"alias":return n;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=HNr([this.method,this.path,this.contentType,"request"].join("_"));return wKs({uniqueId:a,type:n,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Jj.TypeId(a),default:n.type==="enum"&&n.default!=null?{type:"enum",value:n.default}:void 0}}}case void 0:return;default:new wYf.UnreachableCaseError(i);return}}).filter(mA)}convert(){if(this.schema instanceof cya)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(([n,i])=>{switch(i.multipartType){case"file":return[{type:i.multipartType,key:Jj.PropertyKey(n),isOptional:this.requiredFields?.includes(n)==null,contentType:i.contentType,description:i.description,availability:i.availability?.convert()}];case"files":return[{type:i.multipartType,key:Jj.PropertyKey(n),isOptional:this.requiredFields?.includes(n)==null,contentType:i.contentType,description:i.description,availability:i.availability?.convert()}];case"property":{let a=e5(i.convert()),o=i.multipartType;return a?.map(c=>({type:o,key:Jj.PropertyKey(n),contentType:i.contentType,exploded:void 0,valueShape:c,description:i.description,availability:i.availability?.convert()}))}case void 0:return[];default:return new wYf.UnreachableCaseError(i.multipartType),[]}}).filter(mA).reduce((n,i)=>n.flatMap(a=>i.length>0?i.map(o=>[...a,o]):[[...a]]),[[]]).map(n=>({type:"formData",fields:n,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var DKs=class extends LO{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let n=teb(this.input,this.context.document);if(n==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(n.content).forEach(([i,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[i]=new SKs({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:i,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>e5(r.convert())?.map(i=>({description:this.description,contentType:t,body:i}))).filter(mA)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>e5(t.convert())?.map(n=>{if(!(n.type!=="alias"&&n.type!=="object"))return{description:this.description,shape:n}})).filter(mA)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var neb={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 ieb(e,t){if(Zx(e)){let r=dge(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var CKs=Gi(gK());var aeb="application/json";var oeb="application/octet-stream";function ueb(e,t){return e===t||t===vpe||e===vpe}var suu=class extends LO{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,n,i,a,o,c,f){super(t),this.streamingFormat=n,this.path=i,this.method=a,this.statusCode=o,this.requests=c,this.shapes=f,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,n){for(let i of t)for(let[a,o]of Object.entries(i?.examples??{}))for(let[c,f]of Object.entries(r))for(let s of f)ueb(c,a)&&(n.add(c),this.examples?.push(new OGr({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,L5i(a,c),{requestBody:i,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let n=0;for(let i of t){let a=0;for(let[o,c]of r){if(a===n){let[f,s,u]=i??[void 0,void 0,void 0];this.examples?.push(...c.map(l=>new OGr({input:{requestExample:u,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,L5i(s,o),{requestBody:f,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}n++}if(t.length>r.length)for(let i of t.slice(r.length)){let[a,o]=r[r.length-1]??[void 0,void 0],[c,f,s]=i??[void 0,void 0,void 0];this.examples?.push(...(o??[void 0]).map(u=>new OGr({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:f!=null&&f!==""?["examples",f]:"examples"},this.path,this.statusCode,L5i(f,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[i,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 OGr({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,L5i(a,c),{requestBody:i,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,n,i){let a=t[vpe];if(a!=null)for(let o of a)this.examples?.push(new OGr({input:{requestExample:i,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:n!=null&&n!==""?["examples",n]:"examples"},this.path,this.statusCode,L5i(n,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 n of t)if(Object.keys(n.examples??{}).length===0)this.pushResponseExample(r,n,void 0,void 0);else for(let[i,a]of Object.entries(n.examples??{}))this.pushResponseExample(r,n,i,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=alo.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=aeb,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 LU({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=oeb,this.contentSubtype=yte(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 LU({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=tKs(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[vpe]??=[],r[vpe]=[{value:this.input.example}]);let n=yte(this.input.schema,this.context.document);if(n!=null&&(n.examples!=null&&Object.keys(r).length===0&&(r=tKs(n.examples,c=>[c])),n.example!=null&&Object.keys(r).length===0&&(r[vpe]??=[],r[vpe]?.push({value:n.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[vpe]??=[],r[vpe]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let i=new Set;this.matchRequestResponseExamplesByName(this.requests,r,i);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([f])=>!i.has(f)&&f!==vpe).map(([f,s])=>[c,f,s]));let o=Object.entries(r).filter(([c,f])=>!i.has(c)&&mA(f)&&c!==vpe);Object.keys(r).every(c=>c===vpe)||this.matchExamplesByIndex(a,o),!i.has(vpe)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return e5(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new CKs.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return e5(this.schema?.convert())?.map(r=>{let n=r.type;switch(n){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let i=HNr([this.method,this.path,this.statusCode,"response"].join("_"));return wKs({uniqueId:i,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Jj.TypeId(i),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new CKs.UnreachableCaseError(n);return}}).filter(mA)}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 CKs.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var cuu=class extends LO{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,n,i,a,o){super(t),this.path=r,this.method=n,this.statusCode=i,this.requests=a,this.shapes=o,this.safeParse()}parse(t){this.description=this.input.description;let r=ieb(this.input,this.context.document);if(r==null){this.context.errors.error({message:Zx(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([n,i])=>{this.headers??={},this.headers[n]=new AGr({input:i,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:n})}),r.content==null?(this.responses??=[],this.responses.push(new suu({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(([n,i])=>{this.responses??=[],this.responses.push(new suu({input:i,context:this.context,accessPath:this.accessPath,pathId:["content",n]},n,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(mA)}};var IKs=class extends LO{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,n,i,a){super(t),this.path=r,this.method=n,this.requests=i,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,n])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new cuu({input:{...t,...n},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new cuu({input:n,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 n=r.convert();if(n!=null)return yKs(G5i(r.headers)).flatMap(i=>n?.map(a=>({headers:i,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(o=>(o.examples??[]).map(c=>c.convert()).filter(mA))})))}).filter(mA)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(n=>{let i=n.schema,a=e5(i?.convert());if(i!=null)return a?.map(o=>({statusCode:parseInt(t),shape:o,description:r.description??i.description,availability:i.availability?.convert(),name:i.name??neb[parseInt(t)]??"UNKNOWN ERROR",examples:n.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(mA)})).filter(mA)})).filter(mA)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var J5i=class extends LO{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,n){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new OGr({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,L5i(n,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 Uvt({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=Q5i(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new fKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((n,i)=>{if(Zx(n)){let a=oKs(n,this.context.document);if(a!=null)n=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${n.$ref}`,path:[...this.accessPath,`parameters[${i}]`]});return}}n.in==="path"?n.schema!=null&&(this.pathParameters??={},this.pathParameters[n.name]=new AGr({input:n,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${i}`],parameterName:n.name})):n.in==="query"?n.schema!=null&&(this.queryParameters??={},this.queryParameters[n.name]=new AGr({input:n,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${i}`],parameterName:n.name})):n.in==="header"&&n.schema!=null&&(this.requestHeaders??={},this.requestHeaders[n.name]=new AGr({input:n,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${i}`],parameterName:n.name}))});for(let n of this.extractPathParameterIds()??[])this.pathParameters?.[n]==null&&this.context.errors.warning({message:`Path parameter not defined: ${n}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new dKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new DKs({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 IKs({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 n=this.requests?.requestBodiesByContentType;n==null||Object.keys(n).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(n).forEach(i=>{if(Object.keys(i.examples??{}).length===0){let a=i.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},i,void 0)}else Object.entries(i.examples??{}).forEach(([a,o])=>{this.pushEmptyResponseExample(o,i,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(n=>Number(n)>=200&&Number(n)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new tlo({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new uuu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(n=>n.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((n,i)=>new uuu({input:{[QJs]:n},context:this.context,accessPath:this.accessPath,pathId:["tags",`${i}`]})));let r=new lKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(n=>rKs({namespace:e5(n?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(mA),this.xFernExamplesNode=new cKs({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(mA)}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((i,a)=>(i.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?i.push({type:"pathParameter",value:Jj.PropertyKey(a.slice(1,-1).trim())}):i.push({type:"literal",value:a}),i),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},n=this.emptyResponseExamples?.map(u=>u.convert()).filter(mA),i=Tkv(this.xFernExamplesNode?.convert(),[...n??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:Bkv(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:Jj.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(m=>m.value.toString())??[],queryParameters:G5i(this.queryParameters)?.flat(),headers:G5i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(mA)}}).filter(mA);let a=this.servers?.map(u=>u.convert()).filter(mA),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(mA);return this.endpointIds.map((u,l)=>({id:Jj.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(m=>Jj.api.v1.SubpackageId(m)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(m=>Jj.api.latest.AuthSchemeId(m)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:G5i(this.pathParameters)?.flat(),queryParameters:G5i(this.queryParameters)?.flat(),requestHeaders:G5i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(m=>m.response),errors:r,examples:i,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var olo=class extends LO{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:n,isWebhook:i}){this.description=this.input.description;let a=Q5i(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 J5i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:o,method:"GET",basePath:n,isWebhook:i})),this.input.post!=null&&(this.post=new J5i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:o,method:"POST",basePath:n,isWebhook:i})),this.input.put!=null&&(this.put=new J5i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:o,method:"PUT",basePath:n,isWebhook:!1})),this.input.patch!=null&&(this.patch=new J5i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:o,method:"PATCH",basePath:n,isWebhook:!1})),this.input.delete!=null&&(this.delete=new J5i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:o,method:"DELETE",basePath:n,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(mA)}};function MKs(e){return"payloads"in e}var BKs=class extends LO{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:n}){this.paths=Object.entries(this.input).map(([i,a])=>{if(a!=null)return new olo({input:a,context:this.context,accessPath:this.accessPath,pathId:i,servers:Q5i(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:n,isWebhook:void 0})}).filter(mA)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(n=>{let i=n.convert();i?.forEach(a=>{MKs(a)?r[Jj.WebhookId(a.id)]=a:t[Jj.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var TKs=class extends LO{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[XZv]?.map(r=>{let{header:n,...i}=r;return(i.optional!=null&&!i.optional||oKs(i,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(n)),[n,new AGr({input:i,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:n})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return rlo(this.globalHeaders,this.requiredProperties)?.flat()}};function seb(e,t){if(Zx(e)){let r=dge(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var qKs=class extends LO{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:n}){this.webhooks=Object.entries(this.input??{}).map(([i,a])=>{let o=seb(a,this.context.document);if(o!=null)return new olo({input:o,context:this.context,accessPath:this.accessPath,pathId:i,servers:t,globalAuth:r,basePath:n,isWebhook:!0})}).filter(mA)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(n=>{MKs(n)&&(t[Jj.WebhookId(n.id)]=n)}),t),{})}};var RKs=class extends LO{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=Q5i(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new tlo({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new aKs({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 BKs({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 qKs({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 jKs({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new TKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=yit(),{webhookEndpoints:r,endpoints:n}=this.paths?.convert()??{},i={...this.webhooks?.convert()??{},...r??{}},a=JZv({endpoints:n,webhookEndpoints:i}),{types:o,auths:c}=this.components?.convert()??{};return{id:Jj.ApiDefinitionId(t),endpoints:n??{},websockets:{},webhooks:i,types:{...o,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};async function jYf(e,t){if(e instanceof rHr){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof tY))return;let r=new $Rr(e.absoluteFilePath),n=await Mvt({context:t,specs:e.specs}),i=await r.loadDocuments({context:t,specs:n}),a;for(let o of i){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new xJs,generatedTypes:{}},f=new RKs({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=Hkl(a,f.convert())}return a}var Plb=Gi(DYf(),1),wlb=Gi(A$s(),1),jlb=require("fs/promises"),Elb=Gi(require("http"),1),Slb=Gi(require("path"),1);var sab=require("events"),S$s=Gi(require("fs"),1),gya=Gi(require("path"),1);var Wib=Gi(require("os"),1),Hib=300,eLi=20,Tuu=1e7,Gib=Wib.default.platform();var B8M=Gib==="darwin",JXf=Gib==="win32",tLi=B8M||JXf,Jib=3e3,Kib=2e4,KXf=1250;var EGr;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(EGr||(EGr={}));var bya;(function(e){e.CHANGE="change",e.RENAME="rename"})(bya||(bya={}));var quu;(function(e){e.CHANGE="change",e.ERROR="error"})(quu||(quu={}));var zS;(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"})(zS||(zS={}));var UIe;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(UIe||(UIe={}));var T8M=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,f=0,s=0,u=()=>{let q=Date.now(),V=q-f,$=q-s,re=V>=t||$>=a;return[q,re]},l=q=>{if(s=q,!o)return;let V=o;o=void 0,e.apply(void 0,V)},m=()=>{z(0)},A=()=>{c&&(m(),l(Date.now()))},P=q=>{if(s=q,n)return l(q)},C=q=>{if(i&&o)return l(q);o=void 0},M=()=>{c=void 0;let[q,V]=u();return V?C(q):T(q)},T=q=>{let V=q-f,$=q-s,re=t-V,X=a-$,k=Math.min(re,X);return z(k)},z=q=>{c&&clearTimeout(c),!(q<=0)&&(c=setTimeout(M,q))},U=(...q)=>{let[V,$]=u(),re=!!c;if(o=q,f=V,($||!c)&&z(t),$)return re?l(V):P(V)};return U.cancel=m,U.flush=A,U},P$s=T8M;var ZXf=Gi(require("fs"),1),j$s=Gi(require("path"),1);var d6=Gi(require("fs"),1),pge=require("util");var rEi=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},SGr=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var $Xf=Gi(require("process"),1),$ib=$Xf.default.getuid?!$Xf.default.getuid():!1,Yib=1e4,jze=()=>{};var Ruu={isChangeErrorOk:e=>{if(!Ruu.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!$ib&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!Ruu.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(!Ruu.isNodeError(e))throw e;if(!Ruu.isChangeErrorOk(e))throw e}},vte=Ruu;var YXf=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Yib,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(n),n=()=>t(r);this.add(n)}),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()}}}}},Xib=new YXf;var nEi=(e,t)=>function(n){return function i(...a){return Xib.schedule().then(o=>{let c=s=>(o(),s),f=s=>{if(o(),Date.now()>=n)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(m=>setTimeout(m,u)).then(()=>i.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,f)})}},iEi=(e,t)=>function(n){return function i(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>n)throw o;if(t(o))return i.apply(void 0,a);throw o}}};var q8M={attempt:{chmod:rEi((0,pge.promisify)(d6.default.chmod),vte.onChangeError),chown:rEi((0,pge.promisify)(d6.default.chown),vte.onChangeError),close:rEi((0,pge.promisify)(d6.default.close),jze),fsync:rEi((0,pge.promisify)(d6.default.fsync),jze),mkdir:rEi((0,pge.promisify)(d6.default.mkdir),jze),realpath:rEi((0,pge.promisify)(d6.default.realpath),jze),stat:rEi((0,pge.promisify)(d6.default.stat),jze),unlink:rEi((0,pge.promisify)(d6.default.unlink),jze),chmodSync:SGr(d6.default.chmodSync,vte.onChangeError),chownSync:SGr(d6.default.chownSync,vte.onChangeError),closeSync:SGr(d6.default.closeSync,jze),existsSync:SGr(d6.default.existsSync,jze),fsyncSync:SGr(d6.default.fsync,jze),mkdirSync:SGr(d6.default.mkdirSync,jze),realpathSync:SGr(d6.default.realpathSync,jze),statSync:SGr(d6.default.statSync,jze),unlinkSync:SGr(d6.default.unlinkSync,jze)},retry:{close:nEi((0,pge.promisify)(d6.default.close),vte.isRetriableError),fsync:nEi((0,pge.promisify)(d6.default.fsync),vte.isRetriableError),open:nEi((0,pge.promisify)(d6.default.open),vte.isRetriableError),readFile:nEi((0,pge.promisify)(d6.default.readFile),vte.isRetriableError),rename:nEi((0,pge.promisify)(d6.default.rename),vte.isRetriableError),stat:nEi((0,pge.promisify)(d6.default.stat),vte.isRetriableError),write:nEi((0,pge.promisify)(d6.default.write),vte.isRetriableError),writeFile:nEi((0,pge.promisify)(d6.default.writeFile),vte.isRetriableError),closeSync:iEi(d6.default.closeSync,vte.isRetriableError),fsyncSync:iEi(d6.default.fsyncSync,vte.isRetriableError),openSync:iEi(d6.default.openSync,vte.isRetriableError),readFileSync:iEi(d6.default.readFileSync,vte.isRetriableError),renameSync:iEi(d6.default.renameSync,vte.isRetriableError),statSync:iEi(d6.default.statSync,vte.isRetriableError),writeSync:iEi(d6.default.writeSync,vte.isRetriableError),writeFileSync:iEi(d6.default.writeFileSync,vte.isRetriableError)}},Zib=q8M;var w$s=Gi(require("fs"),1),Nuu=Gi(require("path"),1);var XXf=()=>{};var R8M=()=>{let e=XXf,t=XXf,r=!1,n=!1;return{promise:new Promise((f,s)=>{e=u=>(r=!0,f(u)),t=u=>(n=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},kib=R8M;var N8M=()=>{let{promise:e,resolve:t,isPending:r}=kib(),n=0,i=()=>{n+=1},a=()=>{n-=1,!n&&t()};return(()=>{i(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:i,decrement:a}},eab=N8M;var tab={then:e=>{e()}};var rab=e=>Array.isArray(e)?e:[e],nab=e=>typeof e=="function";var F8M=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,a=t?.ignore??[],o=rab(a).map(ze=>nab(ze)?ze:Me=>ze.test(Me)),c=ze=>o.some(Me=>Me(ze)),f=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],l=new Set,m={},A=[],P=new Set,C={},M=[],T=new Set,z={},U={},q=new Set,V={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},$={directories:u,directoriesNames:l,directoriesNamesToPaths:m,files:A,filesNames:P,filesNamesToPaths:C,symlinks:M,symlinksNames:T,symlinksNamesToPaths:z,map:U},{promise:re,increment:X,decrement:k}=eab(),ne=0,Oe=(ze,Me,$t,rt)=>{q.has(Me)||ne>=i||(ne+=1,ze.directories.push(Me),ze.directoriesNames.add($t),u.push(Me),l.add($t),m.propertyIsEnumerable($t)||(m[$t]=[]),m[$t].push(Me),q.add(Me),!(rt>=n)&&(ne>=i||Se(Me,rt+1)))},ve=(ze,Me,$t)=>{q.has(Me)||ne>=i||(ne+=1,ze.files.push(Me),ze.filesNames.add($t),A.push(Me),P.add($t),C.propertyIsEnumerable($t)||(C[$t]=[]),C[$t].push(Me),q.add(Me))},me=(ze,Me,$t,rt)=>{q.has(Me)||ne>=i||(ne+=1,ze.symlinks.push(Me),ze.symlinksNames.add($t),M.push(Me),T.add($t),z.propertyIsEnumerable($t)||(z[$t]=[]),z[$t].push(Me),q.add(Me),r&&(rt>=n||ne>=i||jt(Me,rt+1)))},be=(ze,Me,$t,rt,nr)=>{f.aborted||c(Me)||(rt.isDirectory()?Oe(ze,Me,$t,nr):rt.isFile()?ve(ze,Me,$t):rt.isSymbolicLink()&&me(ze,Me,$t,nr))},Ie=(ze,Me,$t,rt)=>{if(f.aborted)return;let nr=Me===Nuu.default.sep?"":Nuu.default.sep,Ft=$t.name,Xe=`${Me}${nr}${Ft}`;c(Xe)||($t.isDirectory()?Oe(ze,Xe,Ft,rt):$t.isFile()?ve(ze,Xe,Ft):$t.isSymbolicLink()&&me(ze,Xe,Ft,rt))},Be=(ze,Me,$t,rt)=>{for(let nr=0,Ft=$t.length;nr<Ft;nr++)Ie(ze,Me,$t[nr],rt)},Se=(ze,Me)=>{f.aborted||Me>n||ne>=i||(X(),w$s.default.readdir(ze,{withFileTypes:!0},($t,rt)=>{if($t||f.aborted||!rt.length)return k();(s(rt)||tab).then(()=>{let Ft=U[ze]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Be(Ft,ze,rt,Me),k()})}))},jt=(ze,Me)=>{X(),w$s.default.realpath(ze,($t,rt)=>{if($t||f.aborted)return k();w$s.default.stat(rt,(nr,Ft)=>{if(nr||f.aborted)return k();let Xe=Nuu.default.basename(rt),pt=U[ze]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};be(pt,rt,Xe,Ft,Me),k()})})};return(async(ze,Me=1)=>(ze=Nuu.default.normalize(ze),q.add(ze),Se(ze,Me),await re,f.aborted?V:$))(e)},iab=F8M;var DGr={lang:{debounce:P$s,attempt:e=>{try{return e()}catch(t){return DGr.lang.castError(t)}},castArray:e=>DGr.lang.isArray(e)?e:[e],castError:e=>DGr.lang.isError(e)?e:DGr.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(DGr.lang.isNaN(e))return DGr.lang.isNaN(t);if(DGr.lang.isPrimitive(e)||DGr.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(j$s.default.sep).length-1),getRealPath:(e,t)=>{try{return t?ZXf.default.realpathSync.native(e):ZXf.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===j$s.default.sep&&t.length-e.length>j$s.default.sep.length,poll:(e,t=Kib)=>Zib.retry.stat(t)(e,{bigint:!0}).catch(DGr.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await iab(e,{depth:r,limit:n,ignore:t,signal:i});return[o.directories,o.files]}}}},SB=DGr;var E$s=Gi(require("path"),1);var kXf=class{constructor(t,r,n){this.base=n,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||SB.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=Hib){return(()=>{let r=this.watcher._readyWait,n=[],i=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=SB.lang.debounce(()=>{this.watcher.isClosed()||(r=a(n,i),n=[],i=new Set)},t);return async(c,f="",s=!1)=>{s?await this.eventsPopulate([f],n,!0):i.add(f),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[a,o]=i,c=r[o];return a===c||a===zS.CHANGE&&c===zS.ADD||(r[o]=a,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let a=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,i]),o===zS.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):o===zS.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let a=this.options.recursive?this.options.depth??eLi:Math.min(1,this.options.depth??eLi),o=this.options.limit??Tuu,[c,f]=await SB.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],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let a of this.watcher._poller.stats.keys())SB.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(zS.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!tLi&&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(zS.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(zS.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(E$s.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(zS.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(E$s.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(zS.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===zS.ADD?this.onTargetAdd(n):r===zS.ADD_DIR?this.onTargetAddDir(n):r===zS.CHANGE?this.onTargetChange(n):r===zS.UNLINK?this.onTargetUnlink(n):r===zS.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=bya.CHANGE,r){if(this.watcher.isClosed())return;let n=E$s.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){JXf&&t.code==="EPERM"?this.onWatcherChange(bya.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(quu.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(quu.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(bya.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&tLi&&this.options.native!==!1?this.options.depth??eLi:Math.min(1,this.options.depth??eLi),n=this.options.limit??Tuu,[i,a]=await SB.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...i,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(bya.CHANGE,c,t)}))}}},aab=kXf;var VIe={interval:100,intervalId:void 0,fns:new Map,init:()=>{VIe.intervalId||(VIe.intervalId=setInterval(VIe.resolve,VIe.interval))},reset:()=>{VIe.intervalId&&(clearInterval(VIe.intervalId),delete VIe.intervalId)},add:(e,t)=>{VIe.fns.set(e,Date.now()+t),VIe.init()},remove:e=>{VIe.fns.delete(e)},resolve:()=>{if(!VIe.fns.size)return VIe.reset();let e=Date.now();for(let[t,r]of VIe.fns)r>=e||(VIe.remove(t),t())}},Fuu=VIe;var xuu=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=KXf){let{ino:n,targetPath:i,events:a,locks:o}=t,c=()=>{let l=this._watcher._poller.paths.find(n||-1,m=>m!==i);if(l&&l!==i){if(SB.fs.getRealPath(i,!0)===l)return;this._watcher.event(a.rename,l,i)}else this._watcher.event(a.add,i)};if(!n)return c();let f=()=>{o.add.delete(n),Fuu.remove(s)},s=()=>{f(),c()};Fuu.add(s,r);let u=()=>{let l=o.unlink.get(n);if(!l)return;f();let m=l();i===m?a.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(a.change,i):this._watcher.event(a.rename,m,i)};o.add.set(n,u),u()}getLockUnlink(t,r=KXf){let{ino:n,targetPath:i,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,i)};if(!n)return c();let f=()=>{o.unlink.delete(n),Fuu.remove(s)},s=()=>{f(),c()};Fuu.add(s,r);let u=()=>(f(),i);o.unlink.set(n,u),o.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,zS.ADD,EGr.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,zS.ADD_DIR,EGr.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,zS.UNLINK,EGr.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,zS.UNLINK_DIR,EGr.DIR);return this.getLockUnlink({ino:n,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}}};xuu.DIR_EVENTS={add:zS.ADD_DIR,rename:zS.RENAME_DIR,unlink:zS.UNLINK_DIR};xuu.FILE_EVENTS={add:zS.ADD,change:zS.CHANGE,rename:zS.RENAME,unlink:zS.UNLINK};var oab=xuu;var eZf=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(SB.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(SB.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(SB.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(SB.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return SB.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);SB.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},tZf=eZf;var rZf=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}},uab=rZf;var nZf=class{constructor(){this.inos={},this.paths=new tZf,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let a=i[t];if(a&&!(n&&a[1]!==n))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await SB.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new uab(n)}reset(){this.inos={},this.paths=new tZf,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,zS.ADD,i),[zS.ADD];if(i.isDirectory())return this.updateIno(t,zS.ADD_DIR,i),[zS.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,zS.UNLINK,n),[zS.UNLINK];if(n.isDirectory())return this.updateIno(t,zS.UNLINK_DIR,n),[zS.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,zS.CHANGE,i),[zS.CHANGE]);if(i.isDirectory())return this.updateIno(t,zS.UNLINK,n),this.updateIno(t,zS.ADD_DIR,i),[zS.UNLINK,zS.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,zS.UNLINK_DIR,n),this.updateIno(t,zS.ADD,i),[zS.UNLINK_DIR,zS.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,zS.UNLINK_DIR,n),this.updateIno(t,zS.ADD_DIR,i),[zS.UNLINK_DIR,zS.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=n.isFile()?EGr.FILE:EGr.DIR;i[t]=[n.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},iZf=nZf;var aZf=class e extends sab.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(UIe.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(UIe.CLOSE,i)),this._readyWait=new Promise(i=>this.on(UIe.READY,i)),this._locker=new oab(this),this._roots=new Set,this._poller=new iZf,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(SB.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(UIe.CLOSE))}error(t){if(this.isClosed())return!1;let r=SB.lang.castError(t);return this.emit(UIe.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(UIe.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(UIe.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&SB.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&SB.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let a of[...i])r&&a.filePath!==r||this.watcherClose(a);if(n)for(let a in this._watchers)SB.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let i in this._watchers)this.watchersClose(i,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,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let a=new aab(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 n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=SB.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(c=>c.handler===n&&(!c.filePath||c.filePath===i)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=gya.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??eLi))&&u.handler===n&&(!u.filePath||u.filePath===i)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&tLi&&u.options.native!==!1)))return!0;if(!tLi)break;let s=gya.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,n,i,a){if(this.isClosed())return;t=SB.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,n,i))try{let f=!r.recursive||tLi&&r.native!==!1?r:{...r,recursive:!1},u={watcher:S$s.default.watch(c,f),handler:n,options:r,folderPath:c,filePath:i},l=o=await this.watcherAdd(u,a);if(this._roots.has(i||c)){let A={...r,ignoreInitial:!0,recursive:!1},P=gya.default.dirname(c),C=c;await this.watchDirectories([P],A,n,C,l)}}catch(f){this.error(f)}return o}async watchDirectory(t,r,n,i,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||tLi&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,a));{r={...r,recursive:!0};let o=r.depth??eLi,c=r.limit??Tuu,[f]=await SB.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,n,i,a);if(f.length){let u=SB.fs.getDepth(t);for(let l of f){let m=SB.fs.getDepth(l),A=Math.max(0,o-(m-u)),P={...r,depth:A};await this.watchDirectories([l],P,n,i,a||s)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},a=(s,u)=>{u===t&&(f(),n())},o=new e(a),c=()=>{this._subwatchers.add(i),this.on(UIe.CLOSE,f),o.watchFile(t,r,a)},f=()=>{this._subwatchers.delete(i),this.removeListener(UIe.CLOSE,f),o.close()};return c()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=gya.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,a=new iZf,o=await this.watchPolling(t,r,async()=>{i||!(await a.update(t,r.pollingTimeout)).length||i||(i=!0,o(),n())})}async watchPolling(t,r,n){if(this.isClosed())return SB.lang.noop;if(this.pollerExists(t,r))return SB.lang.noop;let i={...r,interval:r.pollingInterval??Jib},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(UIe.CLOSE,c),S$s.default.watchFile(t,i,n)},c=()=>{this._pollers.delete(a),this.removeListener(UIe.CLOSE,c),S$s.default.unwatchFile(t,n)};return SB.lang.attempt(o),()=>SB.lang.attempt(c)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=SB.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,f)=>f===o||!SB.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,n)));else for(let a of t)await this.watchPath(a,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=gya.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await SB.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let a=gya.default.dirname(t);return(await SB.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=SB.lang.noop){if(SB.lang.isFunction(t))return this.watch([],{},t);if(SB.lang.isUndefined(t))return this.watch([],r,n);if(SB.lang.isFunction(r))return this.watch(t,{},r);if(SB.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=SB.lang.castArray(t);i.forEach(a=>this._roots.add(a)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==SB.lang.noop&&this.on(UIe.ALL,n),r.readdirMap=void 0,this.ready())}},D$s=aZf;TRs();var ulb=Gi(hYs(),1),HIe=require("fs/promises"),slb=require("os"),clb=Gi(TCe(),1),llb=Gi(olb(),1),BYs=process.platform==="win32",hLM="etag",yLM="preview",vLM="app-preview",bLM="bundle",gLM=".next",mLM="standalone",OLM=".fern",ALM="packages/fern-docs/bundle/.next/server/instrumentation.js",PLM=".npmrc",wLM=".pnpmfile.cjs",jLM="pnpm-workspace.yaml",ELM='Cannot find matching keyid: {"signatures":';function SLM(){return kl(L_.of((0,slb.homedir)()),ds.of(OLM))}function TYs({app:e=!1}){return kl(SLM(),ds.of(e?vLM:yLM))}function lLi({app:e=!1}){return kl(TYs({app:e}),ds.of(e?gLM:bLM))}function ssu({app:e=!1}){return kl(lLi({app:e}),ds.of(mLM))}function DLM({app:e=!1}){return kl(ssu({app:e}),ds.of(ALM))}function CLM({app:e=!1}){return kl(ssu({app:e}),ds.of(jLM))}function ILM({app:e=!1}){return kl(ssu({app:e}),ds.of(wLM))}function MLM({app:e=!1}){return kl(ssu({app:e}),ds.of(PLM))}function jya(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function BLM({app:e=!1}){return kl(TYs({app:e}),ds.of(hLM))}var TLM=`packages:
|
|
3014
|
+
]`;case 1:return`${i} Did you mean ${r[0]}?`;case 2:return`${i} Did you mean ${r[0]} or ${r[1]}?`;default:return`${i} Did you mean ${r[0]}, ${r[1]}, or ${r[2]}?`}}function CJs(e){return`API section ${e} is specified multiple times, however will be only rendered once.`}function dNM(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function IJs({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:n,apiDefinitionId:i}){if(n)return e;let a=[],o=new Map;return e.forEach(c=>{if(c.type!=="endpoint"){a.push(c);return}let f=t(c.endpointId);if(f==null)throw new Error(`Endpoint ${c.endpointId} not found`);let s=`${f.method} ${r(f)}`,u=o.get(s);if(o.set(s,c),u==null||u.isResponseStream===c.isResponseStream){a.push(c);return}let l=a.indexOf(u),m=c.isResponseStream?c:u,A=c.isResponseStream?u:c,P={id:_l.V1.NodeId(`${i}:${A.endpointId}+${m.endpointId}`),type:"endpointPair",stream:m,nonStream:A};a[l]=P}),a}function dXv({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:n,disableEndpointPairs:i,apiDefinitionId:a}){return IJs({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:n,disableEndpointPairs:i,apiDefinitionId:a}).filter(o=>o.type==="apiPackage"?o.children.length>0:!0)}function $co(e,t){if(t!=null)return F3(e.absoluteFilePath,t)}function pXv({docsWorkspace:e,page:t,parentSlug:r,idgen:n,markdownFilesToFullSlugs:i,markdownFilesToNoIndex:a,hideChildren:o}){let c=_l.V1.PageId($co(e,t.absolutePath)),f=r.apply({fullSlug:i.get(t.absolutePath)?.split("/"),urlSlug:t.slug??z$(t.title)});return{id:n.get(c),type:"page",pageId:c,title:t.title,slug:f.get(),icon:t.icon,hidden:o||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,availability:t.availability}}var MJs=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;markdownFilesToTags;workspace;hideChildren;parentAvailability;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#s=[];#u;#c;#f;disableEndpointPairs;constructor(t,r,n,i,a,o,c,f,s,u,l,m){this.apiSection=t,this.docsWorkspace=i,this.taskContext=a,this.markdownFilesToFullSlugs=o,this.markdownFilesToNoIndex=c,this.markdownFilesToTags=f,this.workspace=u,this.hideChildren=l,this.parentAvailability=m,this.disableEndpointPairs=i.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=_l.V1.ApiDefinitionId(r.id),this.#e=x5i.create(r,a),this.#f=s,this.#u=this.apiSection.overviewAbsolutePath!=null?_l.V1.PageId($co(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let A=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#c=n.apply({fullSlug:A?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??z$(this.apiSection.title)});let P=this.apiSection.availability??this.parentAvailability;this.apiSection.navigation!=null&&(this.#s=this.#d(this.apiSection.navigation,this.#e.api.rootPackage,this.#c,P)),this.#s=this.#g(this.#s.map(C=>this.#m(C,P)),this.#O(this.#e.api.rootPackage,this.#c,P))}get(){let t=_l.V1.followRedirects(this.#s),r=new oya(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.workspace?.changelog?.files.map(n=>n.absoluteFilepath),this.docsWorkspace,this.#f).orUndefined();return{id:this.#f.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#u,paginated:this.apiSection.paginated,slug:this.#c.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#c,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:this.apiSection.availability??this.parentAvailability,pointsTo:t,noindex:void 0,playground:this.#v(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#d(t,r,n,i){r=this.#e.resolveSubpackage(r);let a=r!=null?x5i.getSubpackageId(r):void 0;return t.map(o=>S$f(o)._visit({link:c=>({id:this.#f.get(c.url),type:"link",title:c.text,icon:c.icon,url:_l.Url(c.url)}),page:c=>this.#p(c,n,i),package:c=>this.#l(c,n,i),section:c=>this.#_(c,n,i),item:({value:c})=>this.#y(c,a,n,i),endpoint:c=>this.#h(c,a,n,i)})).filter(pj)}#p(t,r,n){return pXv({page:{...t,availability:t.availability??n},parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#f,hideChildren:this.hideChildren})}#l(t,r,n){let i=t.overviewAbsolutePath!=null?_l.V1.PageId($co(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.availability??n,c=this.#e.getSubpackageByIdOrLocator(t.package);if(c!=null){let f=x5i.getSubpackageId(c),s=this.#f.get(i??`${this.apiDefinitionId}:${f}`);this.#a.has(f)&&this.taskContext.logger.warn(CJs(t.package)),this.#a.add(f),this.#o.set(s,[f]);let u=t.slug??(gGr(c)?c.urlSlug:this.apiSection.slug??z$(this.apiSection.title)),l=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),m=this.#d(t.contents,c,l,o);return{id:s,type:"apiPackage",children:m,title:t.title??(gGr(c)?c.displayName??Jco(c.name):this.apiSection.title),slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#v(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(DJs(t.package,this.#e.subpackageLocators));let f=t.slug??z$(t.package),s=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:f}),u=this.#d(t.contents,void 0,s,o);return{id:this.#f.get(i??`${this.apiDefinitionId}:${z$(t.package)}`),type:"apiPackage",children:u,title:t.title??t.package,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#v(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#_(t,r,n){let i=t.overviewAbsolutePath!=null?_l.V1.PageId($co(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,c=this.#f.get(i??a??r.get()),f=t.referencedSubpackages.map(A=>{let P=this.#e.getSubpackageByIdOrLocator(A),C=P!=null?x5i.getSubpackageId(P):void 0;if(C===void 0){this.taskContext.logger.error(DJs(A,this.#e.subpackageLocators));return}return{subpackageId:C,locator:A}}).filter(A=>A!=null).filter(pj);this.#o.set(c,f.map(A=>A.subpackageId)),f.forEach(A=>{this.#a.has(A.subpackageId)&&this.taskContext.logger.error(CJs(A.locator)),this.#a.add(A.subpackageId)});let s=t.slug??z$(t.title),u=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:s}),l=t.availability??n,m=this.#d(t.contents,void 0,u,l);return{id:c,type:"apiPackage",children:m,title:t.title,slug:u.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:l,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:o,playground:this.#v(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#y(t,r,n,i){t=t.trim();let a=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator($A(t));if(a!=null){let o=x5i.getSubpackageId(a),c=this.#f.get(`${this.apiDefinitionId}:${o}`);this.#a.has(o)&&this.taskContext.logger.error(CJs(t)),this.#a.add(o),this.#o.set(c,[o]);let f=gGr(a)?a.urlSlug:"",s=n.apply({urlSlug:f});return{id:c,type:"apiPackage",children:[],title:gGr(a)?a.displayName??Jco(a.name):this.apiSection.title,slug:s.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:i,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#h({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,availability:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,n,i)}#h(t,r,n,i){let a=(r!=null?this.#e.subpackages.get(uge.SubpackageId(r))?.endpoints.get(uge.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(a!=null){let f=this.#e.getEndpointId(a);if(f==null)this.taskContext.logger.debug(`Expected Endpoint ID for ${a.id} at path: ${SJs(a.method,a.path.parts)}. Got undefined.`);else{this.#t.has(f)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${f}`),this.#t.add(f);let s=t.slug!=null?n.append(t.slug):n.apply(a);return{id:this.#f.get(`${this.apiDefinitionId}:${f}`),type:"endpoint",method:a.method,endpointId:f,apiDefinitionId:this.apiDefinitionId,availability:t.availability??_l.V1.convertAvailability(a.availability)??i,isResponseStream:a.response?.type.type==="stream",title:t.title??a.name??Lwe(a.path.parts),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#v(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let o=(r!=null?this.#e.subpackages.get(uge.SubpackageId(r))?.webSockets.get(uge.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(o!=null){let f=this.#e.getWebSocketId(o);if(f==null)this.taskContext.logger.error(`Expected WebSocket ID for ${o.id}. Got undefined.`);else return this.#r.has(f)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${f}`),this.#r.add(f),{id:this.#f.get(`${this.apiDefinitionId}:${f}`),type:"webSocket",webSocketId:f,title:t.title??o.name??Lwe(o.path.parts),slug:(t.slug!=null?n.append(t.slug):n.apply(o)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:_l.V1.convertAvailability(o.availability)??i,playground:this.#v(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let c=(r!=null?this.#e.subpackages.get(uge.SubpackageId(r))?.webhooks.get(uge.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(_l.V1.WebhookId(t.endpoint));if(c!=null){let f=this.#e.getWebhookId(c);if(f==null)this.taskContext.logger.error(`Expected Webhook ID for ${c.id}. Got undefined.`);else return this.#n.has(f)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${f}`),this.#n.add(f),{id:this.#f.get(`${this.apiDefinitionId}:${f}`),type:"webhook",webhookId:f,method:c.method,title:t.title??c.name??(0,_Xv.default)("/",...c.path),slug:(t.slug!=null?n.append(t.slug):n.apply(c)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:i,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#g(t,r){return dXv({left:t,right:r,findEndpointById:n=>this.#e.endpoints.get(n),stringifyEndpointPathParts:n=>Lwe(n.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#m(t,r){return I$f({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(n,i,a)=>this.#A(n,i,a),mergeAndFilterChildren:this.#g.bind(this)})}#O(t,r,n){let i=[];return t.endpoints.forEach(a=>{if(a.protocol?.type==="grpc"){let o=this.#e.getGrpcId(a);if(o==null){this.taskContext.logger.error(`Expected Grpc ID for ${a.id} at path: ${SJs(a.method,a.path.parts)}. Got undefined.`);return}if(this.#i.has(o))return;let c=r.apply(a);i.push({id:_l.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"grpc",grpcId:o,title:a.name??Lwe(a.path.parts),method:a.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:n,slug:c.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let o=this.#e.getEndpointId(a);if(o==null){this.taskContext.logger.debug(`Expected Endpoint ID for ${a.id} at path: ${SJs(a.method,a.path.parts)}. Got undefined.`);return}if(this.#t.has(o))return;let c=r.apply(a);i.push({id:_l.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"endpoint",method:a.method,endpointId:o,apiDefinitionId:this.apiDefinitionId,availability:_l.V1.convertAvailability(a.availability)??n,isResponseStream:a.response?.type.type==="stream",title:a.name??Lwe(a.path.parts),slug:c.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(a=>{let o=this.#e.getWebSocketId(a);if(o==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}this.#r.has(o)||i.push({id:_l.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webSocket",webSocketId:o,title:a.name??Lwe(a.path.parts),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:_l.V1.convertAvailability(a.availability)??n,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(a=>{let o=this.#e.getWebhookId(a);if(o==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}this.#n.has(o)||i.push({id:_l.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webhook",webhookId:o,method:a.method,title:a.name??Jco(a.id),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:n,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(a=>{if(this.#a.has(a))return;let o=this.#e.getSubpackageByIdOrLocator(a);if(o==null){this.taskContext.logger.error(`Subpackage ${a} not found in ${this.apiDefinitionId}`);return}let c=gGr(o)?r.apply(o):r,f=this.#A(a,c,n);f.length>0&&i.push({id:_l.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"apiPackage",children:f,title:gGr(o)?o.displayName??Jco(o.name):this.apiSection.title,slug:c.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:n,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((a,o)=>{let c=a.type==="endpointPair"?a.nonStream.title:a.title,f=o.type==="endpointPair"?o.nonStream.title:o.title;return c.localeCompare(f)})),i}#A(t,r,n){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.debug(DJs(t||"unknown",[])),[]):this.#O(i,r,n)}#v(t){return nXv(t)}mergeEndpointPairs(t){return IJs({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>Lwe(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var hXv=Gi(require("crypto"),1);function pNM(e){return hXv.default.createHash("sha256").update(e).digest("hex")}var BJs=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),pNM(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),n=0;for(;this.#t.has(r);)if(r=this.#r(t),n++,n>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return _l.V1.NodeId(this.#n(t))}};function yXv(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0,phpSdk:e.php!=null?{package:typeof e.php=="string"?e.php:e.php.package,version:typeof e.php=="string"?void 0:e.php.version}:void 0,swiftSdk:e.swift!=null?{package:typeof e.swift=="string"?e.swift:e.swift.package,version:typeof e.swift=="string"?void 0:e.swift.version}:void 0,rustSdk:e.rust!=null?{package:typeof e.rust=="string"?e.rust:e.rust.package,version:typeof e.rust=="string"?void 0:e.rust.version}:void 0}}var qJs=Gi(eit(),1);var TJs=Gi(eit(),1);function vXv({auth:e,playgroundConfig:t,context:r}){if(e.schemes.length>0&&e.schemes[0]!=null){let n=e.schemes[0];return bXv({scheme:n,playgroundConfig:t,context:r})}}function bXv({scheme:e,playgroundConfig:t,context:r}){switch(e.type){case"basic":return{type:"basicAuth",passwordName:e.password.originalName,usernameName:e.username.originalName,description:e.docs};case"bearer":return{type:"bearerAuth",tokenName:e.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:e.name.wireValue,nameOverride:e.name.name.originalName,prefix:e.prefix,description:e.docs};case"oauth":{let n=e.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(i=>i.name.originalName).join(".")||"$.body.access_token";return t?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:TJs.FernRegistry.EndpointId(e.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:TJs.FernRegistry.JqString(n),headerName:e.configuration.tokenHeader,tokenPrefix:e.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}case"inferred":{e.tokenEndpoint.authenticatedRequestHeaders.length>1&&r.logger.warn("Inferred auth scheme has multiple authenticated request headers. Only the `Authentication` or first header will be pushed to FDR.");let n=e.tokenEndpoint.authenticatedRequestHeaders.find(a=>a.headerName.toLowerCase()==="authorization");if(n)return n.responseProperty.propertyPath!=null&&n.responseProperty.propertyPath.length>0&&r.logger.warn("Inferred Authentication header has a property path. The property wirevalue will be pushed to FDR without property path."),{type:"bearerAuth",tokenName:n.responseProperty.property.name.wireValue,description:e.docs};let i=e.tokenEndpoint.authenticatedRequestHeaders[0];return i?{type:"header",headerWireValue:i.headerName,prefix:i.valuePrefix,nameOverride:void 0,description:e.docs}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:ks(e)}}function gXv({auth:e,playgroundConfig:t,context:r}){let n={};for(let i of e.schemes){let a=bXv({scheme:i,playgroundConfig:t,context:r});a!=null&&(n[TJs.FernRegistry.AuthSchemeId(i.key)]=a)}return n}var YI=Gi(eit(),1);var z5i=Gi(eit(),1);function OXv(e){return e._visit({alias:t=>({type:"alias",value:O4(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:Zie(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>z5i.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:z5i.FernRegistry.PropertyKey(r.name.wireValue),valueType:O4(r.valueType),availability:Zie(r.availability),propertyAccess:r.propertyAccess})),extraProperties:yNM(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(n=>({key:z5i.FernRegistry.PropertyKey(n.name.wireValue),valueType:O4(n.valueType),availability:Zie(n.availability),description:n.docs,propertyAccess:n.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(n=>({description:n.docs??void 0,discriminantValue:n.discriminantValue.wireValue,displayName:n.displayName,availability:n.availability!=null?Zie(n.availability):void 0,additionalProperties:np.types.SingleUnionTypeProperties._visit(n.shape,{samePropertiesAsObject:i=>({extends:[z5i.FernRegistry.TypeId(i.typeId)],properties:r,extraProperties:void 0}),singleProperty:i=>({extends:[],properties:[{key:z5i.FernRegistry.PropertyKey(i.name.wireValue),valueType:O4(i.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+n.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:O4(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function O4(e){return e._visit({container:t=>np.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:O4(r)}),map:({keyType:r,valueType:n})=>({type:"map",keyType:O4(r),valueType:O4(n)}),optional:r=>({type:"optional",itemType:O4(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:O4(r)}),set:r=>({type:"set",itemType:O4(r)}),literal:r=>np.types.Literal._visit(r,{boolean:n=>({type:"literal",value:{type:"booleanLiteral",value:n}}),string:n=>({type:"literal",value:{type:"stringLiteral",value:n}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:z5i.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:np.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>hNM(t.v2),float:()=>mXv(t.v2),double:()=>mXv(t.v2),string:()=>_NM(t.v2),long:()=>({type:"long",default:t.v2?.type==="long"?t.v2.default:void 0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),uint:()=>({type:"uint"}),uint64:()=>({type:"uint64"}),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function _NM(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function hNM(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="integer"?e.default:void 0}}function mXv(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="double"?e.default:void 0}}function yNM(e){return typeof e=="boolean"?e?Ih.unknown():void 0:typeof e=="string"?{type:"id",value:z5i.FernRegistry.TypeId(e),default:void 0}:O4(e)}function T$f(e,t){let r=e.service!=null?t.services[e.service]:void 0,n=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,i=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?bNM(r,t):[],webhooks:n!=null?vNM(n):[],websockets:i!=null?[gNM(i,t)]:[],types:e.types.map(a=>YI.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>YI.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?YI.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function vNM(e){return e.map(t=>{let r=[];return t.v2Examples!=null?(r.push(...Object.values(t.v2Examples.userSpecifiedExamples)),r.push(...Object.values(t.v2Examples.autogeneratedExamples))):r.push(...t.examples?.map(n=>({payload:n.payload.jsonExample}))??[]),{description:t.docs??void 0,id:YI.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??Zoa(t.name.originalName),headers:t.headers.map(n=>({description:n.docs??void 0,key:n.name.wireValue,type:O4(n.valueType),availability:Zie(n.availability)})),payload:SNM(t.payload),examples:r}})}function bNM(e,t){let r=[];for(let n of e.endpoints){let i=n.autogeneratedExamples[0],a=[];if(n.v2Examples!=null){let c,f=n.v2Examples.userSpecifiedExamples,s=n.v2Examples.autogeneratedExamples,u=Object.values(f).map(m=>m.response?.statusCode).filter((m,A,P)=>P.indexOf(m)!==A).length>0;for(let[m,A]of Object.entries(f))c=wXv({shouldUseExampleName:u,exampleName:A.displayName??m,example:A,irEndpoint:n,irService:e,ir:t}),c!=null&&a.push(c);let l=Object.values(s).map(m=>m.response?.statusCode).filter((m,A,P)=>P.indexOf(m)!==A).length>0;for(let[m,A]of Object.entries(s))c=wXv({shouldUseExampleName:l,exampleName:A.displayName??m,example:A,irEndpoint:n,irService:e,ir:t}),c!=null&&a.push(c)}else if(n.userSpecifiedExamples.length>0)a.push(...n.userSpecifiedExamples.map(c=>B$f({userSpecifiedExample:c,...i!=null&&{autogeneratedExample:i},irEndpoint:n,ir:t})).filter(pj));else if(i!=null){let c=B$f({autogeneratedExample:i,irEndpoint:n,ir:t});c!=null&&a.push(c)}else if(n.response?.body?.type==="fileDownload"){let c=Iio({ir:t,service:e,endpoint:{...n,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(c.type==="success"){let f=B$f({autogeneratedExample:c,irEndpoint:n,ir:t});if(f!=null){let s={...f,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let o={slug:void 0,availability:Zie(n.availability??e.availability),auth:n.auth,authV2:mNM(n.security),description:n.docs??void 0,method:wNM(n.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?YI.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?ONM({environmentsConfig:t.environments,endpoint:n}):void 0,id:YI.FernRegistry.EndpointId(n.name.originalName),originalEndpointId:n.id,name:n.displayName??Zoa(n.name.originalName),path:n.basePath!=null?{pathParameters:n.pathParameters.map(c=>({description:c.docs??void 0,key:YI.FernRegistry.PropertyKey(c.name.originalName),type:O4(c.valueType),availability:void 0})),parts:[...Yco(n.basePath),...Yco(n.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...n.pathParameters].map(c=>({description:c.docs??void 0,key:YI.FernRegistry.PropertyKey(c.name.originalName),type:O4(c.valueType),availability:void 0})),parts:[...t.basePath!=null?Yco(t.basePath):[],...Yco(e.basePath),...Yco(n.path)]},queryParameters:n.queryParameters.map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:O4(c.valueType),availability:Zie(c.availability)})),headers:[...e.headers,...n.headers].map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:O4(c.valueType),availability:Zie(c.availability)})),request:n.requestBody!=null?AXv(n.requestBody):void 0,requestsV2:{requests:n.v2RequestBodies?.requestBodies?.map(AXv).filter(pj)},response:n.response!=null?PXv(n.response):void 0,responsesV2:{responses:n.v2Responses?.responses?.map(PXv).filter(pj)},errors:void 0,errorsV2:jNM(n.errors,t),examples:a,protocol:n.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:n.id}),proto:c=>({type:"grpc",methodName:n.id,methodType:c.methodType}),_other:()=>{}})};r.push(o)}return r}function gNM(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let n=Object.values(e.v2Examples.userSpecifiedExamples),i=Object.values(e.v2Examples.autogeneratedExamples),a=n.length>0?n[0]:i[0];a!=null&&r.push({name:"",description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(o=>({type:YI.FernRegistry.api.v1.WebSocketMessageId(o.type),body:o.body}))??[]})}else r=e.examples.map(n=>({name:n.name?.originalName,description:n.docs,path:n.url,pathParameters:n.pathParameters.reduce((i,a)=>(i[YI.FernRegistry.PropertyKey(a.name.originalName)]=a.value.jsonExample,i),{}),queryParameters:n.queryParameters.reduce((i,a)=>(i[a.name.wireValue]=a.value.jsonExample,i),{}),headers:n.headers.reduce((i,a)=>(i[a.name.wireValue]=a.value.jsonExample,i),{}),messages:n.messages.map(i=>({type:YI.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}));return{auth:e.auth,availability:Zie(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?YI.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?ANM({environmentsConfig:t.environments,channel:e}):[],id:YI.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??Zoa(e.name.originalName),path:{pathParameters:e.pathParameters.map(n=>({description:n.docs??void 0,key:YI.FernRegistry.PropertyKey(n.name.originalName),type:O4(n.valueType),availability:void 0})),parts:Yco(e.path)},headers:e.headers.map(n=>({key:n.name.wireValue,type:O4(n.valueType),description:n.docs,availability:Zie(n.availability)})),queryParameters:e.queryParameters.map(n=>({description:n.docs??void 0,key:n.name.wireValue,type:O4(n.valueType),availability:Zie(n.availability)})),messages:e.messages.map(n=>({type:YI.FernRegistry.api.v1.WebSocketMessageId(n.type),displayName:n.displayName,origin:n.origin,body:DNM(n.body),description:n.docs,availability:Zie(n.availability)})),examples:r}}function mNM(e){if(e==null)return;if(e.length===0)return[];let t=new Set(e.flatMap(r=>Object.keys(r)));return Array.from(t).map(r=>YI.FernRegistry.AuthSchemeId(r))}function Zie(e){if(e!=null)switch(e.status){case"DEPRECATED":return YI.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return YI.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return YI.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return YI.FernRegistry.Availability.Beta;default:ks(e.status)}}function ONM({environmentsConfig:e,endpoint:t}){let r=e.environments,n=t.baseUrl,i=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:YI.FernRegistry.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(i!=null)return i.flatMap(o=>r.environments.map(c=>{let f=c.urls[o];if(f==null)throw new Error(`Encountered undefined server name "${o}" at endpoint ${t.method.toUpperCase()} ${t.path}. Expected environment ${c.id} to contain url for ${o}`);return{id:YI.FernRegistry.EnvironmentId(o),baseUrl:f}})).filter((o,c,f)=>c===f.findIndex(s=>s.id===o.id&&s.baseUrl===o.baseUrl));if(n==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let o=a.urls[n];if(o==null)throw new Error(`Encountered undefined server name "${n}" at endpoint ${t.method.toUpperCase()} ${t.path.head}. Expected environment ${a.id} to contain url for ${n}`);return{id:YI.FernRegistry.EnvironmentId(a.id),baseUrl:o}});default:ks(r)}}function ANM({environmentsConfig:e,channel:t}){let r=e.environments,n=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:YI.FernRegistry.EnvironmentId(i.id),baseUrl:PNM(i.url,"wss")}));case"multipleBaseUrls":if(n==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(i=>{let a=i.urls[n];if(a==null)throw new Error(`Encountered undefined server name ${a} at channel ${t.name.originalName} ${t.path.head}. Expected environment ${i.id} to contain url for ${n}`);return{id:YI.FernRegistry.EnvironmentId(i.id),baseUrl:a}});default:ks(r)}}function PNM(e,t){return e.replace(/^[^:]+/,t)}function wNM(e){return np.http.HttpMethod._visit(e,{get:()=>YI.FernRegistry.HttpMethod.Get,post:()=>YI.FernRegistry.HttpMethod.Post,put:()=>YI.FernRegistry.HttpMethod.Put,patch:()=>YI.FernRegistry.HttpMethod.Patch,delete:()=>YI.FernRegistry.HttpMethod.Delete,head:()=>YI.FernRegistry.HttpMethod.Head,_other:()=>{throw new Error("Unknown http method: "+e)}})}function Yco(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:YI.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function AXv(e){let t=np.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??Y8.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(n=>YI.FernRegistry.TypeId(n.typeId)),properties:r.properties.map(n=>({description:n.docs??void 0,key:YI.FernRegistry.PropertyKey(n.name.wireValue),valueType:O4(n.valueType),availability:Zie(n.availability),propertyAccess:n.propertyAccess})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??Y8.APPLICATION_JSON,shape:{type:"reference",value:O4(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(n=>n._visit({file:i=>{let a=i._visit({file:o=>({type:"file",key:YI.FernRegistry.PropertyKey(o.key.wireValue),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),fileArray:o=>({type:"fileArray",key:YI.FernRegistry.PropertyKey(o.key.wireValue),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:i=>({type:"bodyProperty",key:YI.FernRegistry.PropertyKey(i.name.wireValue),valueType:O4(i.valueType),contentType:i.contentType,description:i.docs??void 0,availability:Zie(i.availability),exploded:i.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(pj)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function PXv(e){if(e.body==null)return;let t,r=np.http.HttpResponseBody._visit(e.body,{fileDownload:n=>(t=n.docs,{type:"fileDownload",contentType:void 0}),json:n=>(t=n.docs,{type:"reference",value:O4(n.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:n=>{if(n.type==="text")return t=n.docs,{type:"streamingText"};if(n.type==="json")return t=n.docs,{type:"stream",shape:{type:"reference",value:O4(n.payload)},terminator:n.terminator};if(n.type==="sse")return t=n.docs,{type:"stream",shape:{type:"reference",value:O4(n.payload)},terminator:n.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function jNM(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let n of e){let i=t.errors[n.error.errorId];i&&r.push({type:i.type==null?void 0:{type:"alias",value:O4(i.type)},statusCode:i.statusCode,description:i.docs??void 0,name:i.displayName??i.name.name.originalName,availability:void 0,examples:CNM(i)})}else for(let n of e){let i=t.errors[n.error.errorId];if(i){let a=[{key:YI.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:i.discriminantValue.name.originalName}},description:i.docs,availability:void 0,propertyAccess:void 0}];i.type!=null&&a.push({key:YI.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:O4(i.type),description:i.docs,availability:void 0,propertyAccess:void 0}),r.push({type:i.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:i.statusCode,description:i.docs??void 0,availability:void 0,name:i.displayName??i.name.name.originalName,examples:i.examples.map(o=>({name:o.name?.originalName,responseBody:{type:"json",value:o.jsonExample},description:o.docs}))})}}return r}function wXv({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:n,irService:i,ir:a}){if(r==null)return;let o=s=>{if(s.valueType.type==="container"&&s.valueType.container.type==="literal")return s.valueType.container.literal._visit({boolean:u=>`${u}`,string:u=>u,_other:()=>{}});if(s.valueType.type==="container"&&s.valueType.container.type==="optional"&&s.valueType.container.optional.type==="container"&&s.valueType.container.optional.container.type==="literal")return s.valueType.container.optional.container.literal._visit({boolean:u=>`${u}`,string:u=>u,_other:()=>{}})},c={};a.headers.forEach(s=>{let u=o(s);u!=null&&(c[s.name.wireValue]=u)}),i.headers.forEach(s=>{let u=o(s);u!=null&&(c[s.name.wireValue]=u)}),n.headers.forEach(s=>{let u=o(s);u!=null&&(c[s.name.wireValue]=u)});let f=r.response?.body!=null?r.response.body.value:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:(()=>{let u={...r.request?.headers??{}};for(let[l,m]of Object.entries(c))(u[l]===null||u[l]===void 0)&&(u[l]=m);return u})(),requestBody:r.request?.requestBody,requestBodyV3:n.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:s=>{if(r.request==null)return;let u={};if(PR(r.request.requestBody)){let l=r.request.requestBody;for(let m of s.properties)m._visit({file:A=>{let P=l[A.key.wireValue];if(A.type==="file")u[A.key.wireValue]={type:"filename",value:typeof P=="string"?P:"<file1>"};else if(A.type==="fileArray"){let C=(Array.isArray(P)?P:[P]).filter(M=>typeof M=="string");u[A.key.wireValue]={type:"filenames",value:C}}},bodyProperty:A=>{if(A.style==="exploded"){let P=l[A.name.wireValue];u[A.name.wireValue]={type:"exploded",value:Array.isArray(P)?P:[P]}}else u[A.name.wireValue]={type:"json",value:l[A.name.wireValue]}},_other:c_t})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??n.response?.statusCode??200,responseBody:f??void 0,responseBodyV3:f!=null?r.response?.body?._visit({json:s=>({type:"json",value:s}),stream:s=>Array.isArray(s)&&s.length>0&&s.every(ENM)?{type:"sse",value:s}:{type:"stream",value:s},error:()=>{},_other:()=>{throw new Error("Unknown ExampleResponseBody: "+r.response?.body?.type)}}):void 0,codeSamples:r.codeSamples?.map(s=>({name:s.name,description:s.docs??void 0,install:void 0,language:s.language,code:s.code})).filter(pj)}}function ENM(e){return typeof e=="object"&&e!==null&&"event"in e&&typeof e?.event=="string"&&"data"in e}function B$f({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:n}){let i=n.headers.map(c=>{let f;if(c.valueType.type==="container"&&c.valueType.container.type==="literal"?f=c.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):c.valueType.type==="container"&&c.valueType.container.type==="optional"&&c.valueType.container.optional.type==="container"&&c.valueType.container.optional.container.type==="literal"&&(f=c.valueType.container.optional.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}})),f!=null)return{name:c.name,value:{jsonExample:f,shape:np.ExampleTypeReferenceShape.primitive(np.ExamplePrimitive.string({original:f}))}}}).filter(pj),a=e?.example??t?.example;if(a==null)return;let{codeSamples:o}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((c,f)=>(c[YI.FernRegistry.PropertyKey(f.name.originalName)]=f.value.jsonExample,c),{}),queryParameters:a.queryParameters.reduce((c,f)=>(c[f.name.wireValue]=f.value.jsonExample,c),{}),headers:[...i,...a.serviceHeaders,...a.endpointHeaders].reduce((c,f)=>(c[f.name.wireValue]=f.value.jsonExample,c),{}),requestBody:a.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,reference:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,fileUpload:c=>{if(a.request==null)return;let f={};if(PR(a.request.jsonExample)){let s=a.request.jsonExample;for(let u of c.properties)u._visit({file:l=>{let m=s[l.key.wireValue];if(l.type==="file")f[l.key.wireValue]={type:"filename",value:typeof m=="string"?m:"<file1>"};else if(l.type==="fileArray"){let A=(Array.isArray(m)?m:[m]).filter(P=>typeof P=="string");f[l.key.wireValue]={type:"filenames",value:A}}},bodyProperty:l=>{if(l.style==="exploded"){let m=s[l.name.wireValue];f[l.name.wireValue]={type:"exploded",value:Array.isArray(m)?m:[m]}}else f[l.name.wireValue]={type:"json",value:s[l.name.wireValue]}},_other:c_t})}return{type:"form",value:f}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??np.http.ExampleResponse._visit(a.response,{ok:c=>c._visit({body:f=>f!=null?200:204,stream:f=>f.length>0?200:204,sse:f=>f.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:({error:c})=>{let f=n.errors[c.errorId];if(f==null)throw new Error("Cannot find error "+c.errorId);return f.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:c=>c._visit({body:f=>f?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:c=>c.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:c=>c._visit({body:f=>f!=null?{type:"json",value:f.jsonExample}:void 0,stream:f=>({type:"stream",value:f.map(s=>s.jsonExample)}),sse:f=>({type:"sse",value:f.map(({event:s,data:u})=>({event:s,data:u.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+c.type)}}),error:c=>c.body!=null?{type:"json",value:c.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:o?.map(c=>rit._visit(c,{language:f=>({language:f.language,code:f.code,name:f.name?.originalName,description:f.docs??void 0,install:f.install}),sdk:f=>({language:f.sdk,code:f.code,name:f.name?.originalName,description:f.docs??void 0,install:void 0}),_other:()=>{}})).filter(pj)}}function SNM(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>YI.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:YI.FernRegistry.PropertyKey(t.name.wireValue),valueType:O4(t.valueType),availability:Zie(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:O4(e.payloadType)},description:e.docs};default:ks(e)}}function DNM(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>YI.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:YI.FernRegistry.PropertyKey(t.name.wireValue),valueType:O4(t.valueType),availability:Zie(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:O4(e.bodyType)};default:ks(e)}}function CNM(e){let t=e.v2Examples?.userSpecifiedExamples,r=e.v2Examples?.autogeneratedExamples,n=e.examples;return t!=null&&Object.keys(t).length>0?Object.entries(t).map(([i,a])=>({name:i,responseBody:{type:"json",value:a},description:void 0})):r!=null&&Object.keys(r).length>0?Object.entries(r).map(([i,a])=>({name:i,responseBody:{type:"json",value:a},description:void 0})):n.length>0?n.map(i=>({name:i.name?.originalName,responseBody:{type:"json",value:i.jsonExample},description:i.docs})):[]}function zIe({ir:e,snippetsConfig:t,playgroundConfig:r,context:n}){let i={types:{},subpackages:{},rootPackage:T$f(e.rootPackage,e),auth:vXv({auth:e.auth,playgroundConfig:r,context:n}),authSchemes:gXv({auth:e.auth,playgroundConfig:r,context:n}),snippetsConfiguration:t,globalHeaders:e.headers.map(a=>({availability:Zie(a.availability),description:a.docs??void 0,key:a.name.wireValue,type:O4(a.valueType)})),navigation:void 0};for(let[a,o]of Object.entries(e.types))i.types[qJs.FernRegistry.TypeId(a)]={description:o.docs??void 0,name:o.name.name.originalName,shape:OXv(o.shape),availability:Zie(o.availability),displayName:o.name.displayName};for(let[a,o]of Object.entries(e.subpackages)){let c=o.service!=null?e.services[o.service]:void 0;i.subpackages[qJs.FernRegistry.api.v1.SubpackageId(a)]={subpackageId:qJs.FernRegistry.api.v1.SubpackageId(a),displayName:c?.displayName??o.displayName,name:o.name.originalName,description:o.docs??void 0,...T$f(o,e)}}return i}var q$f=Gi(eit(),1);async function R$f({organization:e,workspace:t,context:r,token:n,audiences:i,snippetsConfig:a,playgroundConfig:o}){let c=dG({workspace:t,audiences:i,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new uG(r,t)}),f=Cca({token:n.value}),s=zIe({ir:c,snippetsConfig:a,playgroundConfig:o,context:r}),u=await f.api.v1.register.registerApiDefinition({orgId:q$f.FernRegistry.OrgId(e),apiId:q$f.FernRegistry.ApiId(c.apiName.originalName),definition:s});if(u.ok)return r.logger.debug(`Registered API Definition ${u.body.apiDefinitionId}`),{id:u.body.apiDefinitionId,ir:c};switch(u.error.error){case"UnauthorizedError":case"UserNotInOrgError":return r.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return r.failAndThrow("Failed to register API",u.error)}}var INM=new LGs({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function auu({ir:e,apiDefinitionId:t,playgroundConfig:r,context:n}){return UGs(zGs(zIe({ir:e,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:r,context:n}),uge.ApiDefinitionId(t),INM))}function MNM(e){return e.startsWith(".")||e.includes("/")||e.includes("\\")||e.includes(":")}function BNM(e){return/^(https?:)?\/\//.test(e)}async function TNM({pathToImage:e,absolutePathToFernFolder:t}){if(e==null||BNM(e))return;let r=wj(t,ds.of(e));if(await Qv(r))return r}async function uya({iconPath:e,filepaths:t,docsWorkspace:r}){if(MNM(e)){let n=await TNM({pathToImage:e,absolutePathToFernFolder:r.absoluteFilePath});n&&t.add(n)}}async function jXv({parsedDocsConfig:e,docsWorkspace:t}){let r=new Set;return e.logo?.dark!=null&&r.add(e.logo.dark),e.logo?.light!=null&&r.add(e.logo.light),e.favicon!=null&&r.add(e.favicon),e.backgroundImage?.dark!=null&&r.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&r.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&r.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&r.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&r.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(i=>{r.add(i.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(i=>{r.add(i.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(i=>{r.add(i.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(i=>{i.image!=null&&r.add(i.image)}),(await N$f({navigation:e.navigation,docsWorkspace:t})).forEach(i=>{r.add(i)}),e.js!=null&&e.js.files.forEach(i=>{r.add(i.absolutePath)}),r}async function N$f({navigation:e,docsWorkspace:t}){let r=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(n=>Xco({item:n,filepaths:r,docsWorkspace:t})));break;case"tabbed":await Promise.all(e.items.map(async n=>{n.icon!=null&&await uya({iconPath:n.icon,filepaths:r,docsWorkspace:t}),n.child.type==="layout"&&n.child.layout!=null?await Promise.all(n.child.layout.map(i=>Xco({item:i,filepaths:r,docsWorkspace:t}))):n.child.type==="variants"&&n.child.variants!=null&&await Promise.all(n.child.variants.flatMap(i=>{let a=[];return i.icon!=null&&a.push(uya({iconPath:i.icon,filepaths:r,docsWorkspace:t})),a.push(...i.layout.map(o=>Xco({item:o,filepaths:r,docsWorkspace:t}))),a}))}));break;case"versioned":await Promise.all(e.versions.map(async n=>{n.landingPage!=null&&await Xco({item:n.landingPage,filepaths:r,docsWorkspace:t}),(await N$f({navigation:n.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break;case"productgroup":await Promise.all(e.products.map(async n=>{n.landingPage!=null&&await Xco({item:n.landingPage,filepaths:r,docsWorkspace:t}),(await N$f({navigation:n.navigation,docsWorkspace:t})).forEach(a=>r.add(a))}));break}return r}async function Xco({item:e,filepaths:t,docsWorkspace:r}){switch(e.type){case"page":e.icon!=null&&await uya({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"section":e.icon!=null&&await uya({iconPath:e.icon,filepaths:t,docsWorkspace:r}),await Promise.all(e.contents.map(n=>Xco({item:n,filepaths:t,docsWorkspace:r})));break;case"apiSection":e.icon!=null&&await uya({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"link":e.icon!=null&&await uya({iconPath:e.icon,filepaths:t,docsWorkspace:r});break;case"changelog":e.icon!=null&&await uya({iconPath:e.icon,filepaths:t,docsWorkspace:r});break}}async function EXv({navigation:e,apiWorkspaces:t,visitor:r,context:n}){RNM(e)?await Promise.all(e.map(async i=>{NNM(i)?await Promise.all(i.layout.map(async a=>{await RJs({navigationItem:a,visitor:r,apiWorkspaces:t,context:n})})):FNM(i)&&await Promise.all(i.variants.flatMap(a=>a.layout.map(async o=>{await RJs({navigationItem:o,visitor:r,apiWorkspaces:t,context:n})})))})):await Promise.all(e.map(async i=>{await RJs({navigationItem:i,visitor:r,apiWorkspaces:t,context:n})}))}async function RJs({navigationItem:e,visitor:t,apiWorkspaces:r,context:n}){if(await O5r(e,{alphabetized:Qc,api:Qc,apiName:Qc,audiences:Qc,displayErrors:Qc,snippets:Qc,summary:Qc,title:Qc,layout:Qc,icon:Qc,slug:Qc,hidden:Qc,skipSlug:Qc,paginated:Qc,playground:Qc,flattened:Qc,path:Qc,page:Qc,featureFlag:Qc,openrpc:Qc,contents:async i=>{i!=null&&await Promise.all(i.map(async a=>{await RJs({navigationItem:a,visitor:t,apiWorkspaces:r,context:n})}))},viewers:Qc,orphaned:Qc,availability:Qc}),qNM(e)){let i=r.find(a=>a.workspaceName===e.apiName);i!=null&&await t.apiSection?.({config:e,workspace:i,context:n})}}function qNM(e){return e.api!=null}function RNM(e){return e[0]?.tab!=null}function NNM(e){return"layout"in e&&Array.isArray(e.layout)}function FNM(e){return"variants"in e&&Array.isArray(e.variants)}function Tse(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}DXv.default.extend(CXv.default);var xNM=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),SXv=0,zNM=async({ir:e})=>(SXv++,`${e.apiName.snakeCase.unsafeName}-${SXv}`);var WNr=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;targetAudiences;constructor({domain:t,docsWorkspace:r,ossWorkspaces:n,apiWorkspaces:i,taskContext:a,editThisPage:o,uploadFiles:c=xNM,registerApi:f=zNM,targetAudiences:s}){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=n,this.apiWorkspaces=i,this.taskContext=a,this.editThisPage=o,this.uploadFiles=c,this.registerApi=f,this.targetAudiences=s}#e=BJs.init();shouldIncludeByAudience(t){return!t||t.length===0||!this.targetAudiences||this.targetAudiences.length===0?!0:t.some(r=>this.targetAudiences?.includes(r))}applyAudienceFiltering(t){let r=this.filterNavigationByAudience(t.navigation);return{...t,navigation:r}}filterNavigationByAudience(t){return t.type==="untabbed"||t.type==="tabbed"?t:t.type==="versioned"?{...t,versions:t.versions.filter(r=>this.shouldIncludeByAudience(this.getRawVersionAudiences(r.version)))}:t.type==="productgroup"?{...t,products:t.products.filter(r=>{let n=this.getRawProductAudiences(r.product);return this.shouldIncludeByAudience(n)})}:t}getRawProductAudiences(t){let n=this.docsWorkspace.config.products?.find(i=>i.displayName===t);return IGo(n?.audiences)}getRawVersionAudiences(t){let n=this.docsWorkspace.config.versions?.find(i=>i.displayName===t);return IGo(n?.audiences)}_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;markdownFilesToTags=new Map;rawMarkdownFiles={};async resolve(){this._parsedDocsConfig=await _sf({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.targetAudiences&&this.targetAudiences.length>0&&(this._parsedDocsConfig=this.applyAudienceFiltering(this._parsedDocsConfig));for(let[l,m]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[ds.of(l)]=m;let t=this.parsedDocsConfig.experimental?.openapiParserV3,r=t!=null&&!t;this.docsWorkspace.config.navigation!=null&&r&&await EXv({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:l})=>{(await l.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(A=>{let P=F3(this.docsWorkspace.absoluteFilePath,A.absoluteFilepath);this.parsedDocsConfig.pages[P]=A.contents,this.rawMarkdownFiles[ds.of(P)]=A.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages),this.markdownFilesToTags=await this.getMarkdownFilesToTags(this.parsedDocsConfig.pages);for(let[l,m]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[ds.of(l)]=await GLf({markdown:m,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(l),context:this.taskContext});for(let[l,m]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[ds.of(l)]=await HLf({markdown:m,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(l),context:this.taskContext});let n=await jXv({parsedDocsConfig:this.parsedDocsConfig,docsWorkspace:this.docsWorkspace});for(let[l,m]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:A,markdown:P}=kpa(m,{absolutePathToMarkdownFile:this.resolveFilepath(l),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[ds.of(l)]=P;for(let C of A)n.add(C)}catch(A){throw this.taskContext.logger.error(`Failed to parse ${l}: ${A instanceof Error?A.message:String(A)}`),A}let i=Array.from(n).map(l=>({absoluteFilePath:l,relativeFilePath:this.toRelativeFilepath(l)}));(await this.uploadFiles(i)).forEach(l=>{this.collectedFileIds.set(l.absoluteFilePath,l.fileId)});let o=await this.toRootNode(),c=await this.getMarkdownFilesToFullyQualifiedPathNames(o);for(let[l,m]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[ds.of(l)]=WLf(m,this.collectedFileIds,c,{absolutePathToMarkdownFile:this.resolveFilepath(l),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let f={};Object.entries(this.parsedDocsConfig.pages).forEach(([l,m])=>{let A=QNM(this.editThisPage,l),P=this.rawMarkdownFiles[ds.of(l)];f[xNr.PageId(l)]={markdown:m,editThisPageUrl:A?xNr.Url(A):void 0,rawMarkdown:P}});let s=await this.convertDocsConfiguration(o),u={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let l=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async m=>{let A=wj(this.docsWorkspace.absoluteFilePath,m);(await(0,FJs.stat)(A)).isDirectory()?(await tbe(A,"{js,ts,jsx,tsx,md,mdx}")).forEach(M=>{l.add(M)}):A.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&l.add(A)})),u=Object.fromEntries(await Promise.all([...l].map(async m=>{let A=this.toRelativeFilepath(m),P=(await(0,FJs.readFile)(m)).toString();return[A,P]})))}return{config:s,pages:f,jsFiles:u}}resolveFilepath(t){if(t!=null)return wj(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return F3(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[n,i]of Object.entries(t)){let o=(0,NJs.default)(i).data.slug;typeof o=="string"&&o.trim().length>0&&r.set(this.resolveFilepath(n),o.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[n,i]of Object.entries(t)){let o=(0,NJs.default)(i).data.noindex;typeof o=="boolean"&&r.set(this.resolveFilepath(n),o)}return r}async getMarkdownFilesToTags(t){let r=new Map;for(let[n,i]of Object.entries(t)){let o=(0,NJs.default)(i).data.tags;typeof o=="string"?r.set(this.resolveFilepath(n),o.split(",").map(c=>c.trim()).filter(c=>c.length>0)):Array.isArray(o)&&r.set(this.resolveFilepath(n),o)}return r}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},n=_l.migrate.FernNavigationV1ToLatest.create().root(t);return _l.NodeCollector.collect(n).slugMap.forEach((a,o)=>{if(a==null||!_l.isPage(a))return;let c=_l.getPageId(a);if(c==null)return;let f=kl(this.docsWorkspace.absoluteFilePath,ds.of(c));r[f]=o}),r}getDocsBasePath(){return new URL(Tse(this.domain)).pathname}async convertDocsConfiguration(t){return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt,location:this.parsedDocsConfig.aiChatConfig.location,datasources:this.parsedDocsConfig.aiChatConfig.datasources?.map(n=>({url:n.url,title:n.title}))}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?xNr.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(n=>n.type==="dropdown"?{...n,links:n.links?.map(i=>({...i,url:xNr.Url(i.url)}))}:{...n,url:xNr.Url(n.url)}),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,settings:this.parsedDocsConfig.settings,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(n=>({...n,value:xNr.Url(n.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,languages:this.parsedDocsConfig.languages,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,pageActions:this.parsedDocsConfig.pageActions,theme:this.parsedDocsConfig.theme,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(t.apiName!=null){let n=this.apiWorkspaces.find(i=>i.workspaceName===t.apiName);if(n!=null)return n}else if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}getOpenApiWorkspaceForApiSection(t){if(t.apiName!=null){let n=this.ossWorkspaces.find(i=>i.workspaceName===t.apiName);if(n!=null)return n}else if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}async toRootNode(){let t=_l.V1.SlugGenerator.init(_l.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),n=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:n,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(i=>_l.RoleId(i)),featureFlags:void 0}}async toRootChild(t){return lua(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 n=_l.PageId(this.toRelativeFilepath(t.absolutePath)),i=r.apply({urlSlug:t.slug??z$(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(n),title:t.title,slug:i.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:n}){let i=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,n):void 0,o=r.type==="tabbed"?await this.convertTabbedNavigation(i,r.items,n):await this.toSidebarRootNode(i,r.items,n);return{type:"unversioned",id:i,landingPage:a,child:o}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((i,a)=>this.toVersionNode(i,r,a===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:n}){let i=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,n):void 0;return{id:i,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(o=>this.toProductNode(o,n)))}}async toProductNode(t,r){let n=r.setProductSlug(t.slug??z$(t.product)),i;switch(t.navigation.type){case"tabbed":i={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,n)};break;case"untabbed":i={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,n)};break;case"versioned":i=await this.toVersionedNode(t.navigation,n);break;default:ks(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:_l.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:n.get(),child:i,default:!1,hidden:void 0,authed:void 0,icon:t.icon,image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}async toVersionNode(t,r,n){let i=this.#e.get(t.version),a=r.setVersionSlug(t.slug??z$(t.version)),o=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(i,t.navigation.items,a):await this.toSidebarRootNode(i,t.navigation.items,a);return{type:"version",id:i,versionId:_l.VersionId(t.version),title:t.version,slug:a.get(),child:o,default:n,availability:t.availability!=null?LNM(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,n){let i=this.#e.get(`${t}/root`),a=await Promise.all(r.map(c=>this.toNavigationChild({prefix:i,item:c,parentSlug:n}))),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(`${i}/group`),type:"sidebarGroup",children:[]},o.push(s)),s.children.push(c)}),{type:"sidebarRoot",id:i,children:o}}async toSidebarRootNodeWithVariants(t,r,n){let i=this.#e.get(`${t}/root`);return{type:"sidebarRoot",id:i,children:[{type:"varianted",id:i,children:await Promise.all(r.map(a=>this.toVariantNode(a,i,n)))}]}}async toVariantNode(t,r,n){let i=this.#e.get(`${r}/variant/${t.slug??z$(t.title)}`),a=n.apply({urlSlug:t.slug??z$(t.title),skipUrlSlug:t.skipUrlSlug}),o=await Promise.all(t.layout.map(c=>this.toVariantChild(c,i,a)));return{type:"variant",id:i,variantId:_l.V1.VariantId(t.title),subtitle:t.subtitle??"",default:t.default??!1,image:void 0,children:o,title:t.title,slug:a.get(),icon:t.icon,hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,pointsTo:void 0}}async toVariantChild(t,r,n){return lua(t)._visit({page:async i=>this.toPageNode({item:i,parentSlug:n}),apiSection:async i=>this.toApiSectionNode({item:i,parentSlug:n}),section:async i=>this.toSectionNode({prefix:r,item:i,parentSlug:n}),link:async i=>this.toLinkNode(i),changelog:async i=>this.toChangelogNode(i,n)})}async toNavigationChild({prefix:t,item:r,parentSlug:n,hideChildren:i,parentAvailability:a}){return lua(r)._visit({page:async o=>this.toPageNode({item:o,parentSlug:n,hideChildren:i,parentAvailability:a}),apiSection:async o=>this.toApiSectionNode({item:o,parentSlug:n,hideChildren:i,parentAvailability:a}),section:async o=>this.toSectionNode({prefix:t,item:o,parentSlug:n,hideChildren:i,parentAvailability:a}),link:async o=>this.toLinkNode(o),changelog:async o=>this.toChangelogNode(o,n,i)})}async toApiSectionNode({item:t,parentSlug:r,hideChildren:n,parentAvailability:i}){let a=yXv(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;if(f==null||f)try{o=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1})}catch{}o==null&&(o=dG({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 uG(this.taskContext,c)}));let u=await this.registerApi({ir:o,snippetsConfig:a,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName,workspace:c}),l=auu({ir:o,apiDefinitionId:u,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext});return new MJs(t,l,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,c,n,i??t.availability).get()}async toChangelogNode(t,r,n){return new oya(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:n||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:_l.V1.Url(t.url),icon:t.icon}}async toPageNode({item:t,parentSlug:r,hideChildren:n,parentAvailability:i}){let a=_l.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??z$(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:t.title,icon:t.icon,hidden:n||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??i}}async toSectionNode({prefix:t,item:r,parentSlug:n,hideChildren:i,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?_l.PageId(o):void 0,f=this.#e.get(c??`${t}/section`),s=n.apply({urlSlug:r.slug??z$(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=i||r.hidden;return{id:f,type:"section",overviewPageId:c,slug:s.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:l,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(m=>this.toNavigationChild({prefix:f,item:m,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,n){let i=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:i,children:await Promise.all(r.map(a=>this.toTabChild(i,a,n)))}}async toTabChild(t,r,n){return lua(r.child)._visit({link:({href:i})=>this.toTabLinkNode(r,i),layout:({layout:i})=>this.toTabNode(t,r,i,n),changelog:({changelog:i})=>this.toTabChangelogNode(r,i,n),variants:({variants:i})=>this.toTabNodeWithVariants(t,r,i,n)})}async toTabChangelogNode(t,r,n){return new oya(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:n,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:_l.V1.Url(r),icon:t.icon}}async toTabNode(t,r,n,i){let a=this.#e.get(`${t}/tab`),o=i.apply({urlSlug:r.slug??z$(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,n,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,n,i){let a=this.#e.get(`${t}/tab`),o=i.apply({urlSlug:r.slug??z$(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,n,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):xNr.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:n}=this.parsedDocsConfig,i=r?.[t],a=n?.[t];return{logo:this.getFileId(i),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 n=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${n}`,variants:t.variants.map(i=>({fontFile:this.getFileId(i.absolutePath),weight:i.weight,style:i.style!=null?[i.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(pj),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:xNr.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":n,...i}=this.parsedDocsConfig.metadata;return{...i,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(n)}}convertFileIdOrUrl(t){if(t!=null)return lua(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:xNr.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function QNM(e,t){if(e?.github==null)return;let{owner:r,repo:n,branch:i="main",host:a="https://github.com"}=e.github;return`${Tse(a)}/${r}/${n}/blob/${i}/fern/${t}?plain=1`}function LNM(e){switch(e){case"beta":return _l.V1.NavigationV1Availability.Beta;case"deprecated":return _l.V1.NavigationV1Availability.Deprecated;case"ga":return _l.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return _l.V1.NavigationV1Availability.Stable;default:ks(e)}}async function fge(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof tY?t:null))).filter(pj)}async function F$f(e,t,r){if(e instanceof rHr){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof tY))return;let n=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1});return zIe({ir:n,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 Jj={};yf(Jj,{AlgoliaSearchIndex:()=>IXv,ApiDefinitionId:()=>XXv,ApiId:()=>tZv,Availability:()=>yZv,DocsConfigId:()=>rZv,EndpointId:()=>iZv,EndpointPathLiteral:()=>_Zv,EnvironmentId:()=>nZv,FileId:()=>cZv,HttpMethod:()=>hZv,IndexSegmentId:()=>MXv,JqString:()=>fZv,OrgId:()=>kXv,PageId:()=>sZv,PayloadLocation:()=>VZv,PropertyKey:()=>dZv,PullRequestState:()=>xZv,RoleId:()=>pZv,TokenId:()=>eZv,TypeId:()=>uZv,Url:()=>lZv,VersionId:()=>ZXv,WebSocketId:()=>aZv,WebhookId:()=>oZv,algolia:()=>x$f,api:()=>K$f,commons:()=>$$f,diff:()=>vZv,docs:()=>iYf,generators:()=>oYf,git:()=>uYf,navigation:()=>lYf,sdks:()=>dYf,snippets:()=>LZv,snippetsFactory:()=>UZv,templates:()=>pYf,tokens:()=>WZv});var x$f={};yf(x$f,{AlgoliaSearchIndex:()=>IXv,IndexSegmentId:()=>MXv});function IXv(e){return e}function MXv(e){return e}var K$f={};yf(K$f,{latest:()=>L$f,v1:()=>J$f});var L$f={};yf(L$f,{AuthSchemeId:()=>BXv,WebhookHttpMethod:()=>NXv,auth:()=>z$f,commons:()=>TXv,endpoint:()=>qXv,type_:()=>RXv,webhook:()=>Q$f,websocket:()=>FXv});var z$f={};yf(z$f,{AuthSchemeId:()=>BXv});function BXv(e){return e}var TXv={};var qXv={};var RXv={};var Q$f={};yf(Q$f,{WebhookHttpMethod:()=>NXv});var NXv={Get:"GET",Post:"POST"};var FXv={};var J$f={};yf(J$f,{SubpackageId:()=>JXv,WebSocketMessageId:()=>KXv,WebSocketMessageOrigin:()=>$Xv,WebhookHttpMethod:()=>YXv,commons:()=>G$f,db:()=>U$f,read:()=>W$f,register:()=>H$f});var U$f={};yf(U$f,{endpoint:()=>xXv});var xXv={};var W$f={};yf(W$f,{SupportedLanguage:()=>zXv,endpoint:()=>V$f,type_:()=>QXv,webhook:()=>LXv,websocket:()=>UXv});var V$f={};yf(V$f,{SupportedLanguage:()=>zXv});var zXv={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var QXv={};var LXv={};var UXv={};var H$f={};yf(H$f,{SourceId:()=>UNM,endpoint:()=>VXv,type_:()=>WXv,webhook:()=>HXv,websocket:()=>GXv});var VXv={};var WXv={};var HXv={};var GXv={};function UNM(e){return e}var G$f={};yf(G$f,{SubpackageId:()=>JXv,WebSocketMessageId:()=>KXv,WebSocketMessageOrigin:()=>$Xv,WebhookHttpMethod:()=>YXv});function JXv(e){return e}function KXv(e){return e}var $Xv={Client:"client",Server:"server"};var YXv={Get:"GET",Post:"POST"};var $$f={};yf($$f,{ApiDefinitionId:()=>XXv,ApiId:()=>tZv,Availability:()=>yZv,DocsConfigId:()=>rZv,EndpointId:()=>iZv,EndpointPathLiteral:()=>_Zv,EnvironmentId:()=>nZv,FileId:()=>cZv,HttpMethod:()=>hZv,JqString:()=>fZv,OrgId:()=>kXv,PageId:()=>sZv,PropertyKey:()=>dZv,RoleId:()=>pZv,TokenId:()=>eZv,TypeId:()=>uZv,Url:()=>lZv,VersionId:()=>ZXv,WebSocketId:()=>aZv,WebhookId:()=>oZv});function XXv(e){return e}function ZXv(e){return e}function kXv(e){return e}function eZv(e){return e}function tZv(e){return e}function rZv(e){return e}function nZv(e){return e}function iZv(e){return e}function aZv(e){return e}function oZv(e){return e}function uZv(e){return e}function sZv(e){return e}function cZv(e){return e}function lZv(e){return e}function fZv(e){return e}function dZv(e){return e}function pZv(e){return e}function _Zv(e){return e}var hZv={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var yZv={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var vZv={};var iYf={};yf(iYf,{latest:()=>Z$f,v1:()=>rYf,v2:()=>nYf});var Z$f={};yf(Z$f,{Layout:()=>gZv,MdxEngine:()=>VNM,TwitterCardSetting:()=>mZv,commons:()=>bZv,frontmatter:()=>Y$f,seo:()=>X$f});var VNM={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var bZv={};var Y$f={};yf(Y$f,{Layout:()=>gZv});var gZv={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var X$f={};yf(X$f,{TwitterCardSetting:()=>mZv});var mZv={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var rYf={};yf(rYf,{commons:()=>tYf,db:()=>OZv,read:()=>AZv,write:()=>k$f});var OZv={};var AZv={};var k$f={};yf(k$f,{DocsRegistrationId:()=>HNM,FilePath:()=>WNM});function WNM(e){return e}function HNM(e){return e}var tYf={};yf(tYf,{ContentAlignment:()=>EZv,FontDisplay:()=>MZv,FontStyle:()=>IZv,HeaderPosition:()=>SZv,JsScriptStrategy:()=>CZv,ProgrammingLanguage:()=>PZv,SearchbarPlacement:()=>wZv,TabsPlacement:()=>jZv,TwitterCardSetting:()=>DZv,commons:()=>eYf});var eYf={};yf(eYf,{ContentAlignment:()=>EZv,FontDisplay:()=>MZv,FontStyle:()=>IZv,HeaderPosition:()=>SZv,JsScriptStrategy:()=>CZv,ProgrammingLanguage:()=>PZv,SearchbarPlacement:()=>wZv,TabsPlacement:()=>jZv,TwitterCardSetting:()=>DZv});var PZv={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 wZv={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var jZv={Header:"HEADER",Sidebar:"SIDEBAR"};var EZv={Center:"CENTER",Left:"LEFT"};var SZv={Fixed:"FIXED",Absolute:"ABSOLUTE"};var DZv={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var CZv={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var IZv={Normal:"normal",Italic:"italic"};var MZv={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var nYf={};yf(nYf,{read:()=>BZv,write:()=>TZv});var BZv={};var TZv={};var oYf={};yf(oYf,{ChangelogEntryType:()=>RZv,GeneratorId:()=>GNM,GeneratorLanguage:()=>JNM,ReleaseType:()=>NZv,cli:()=>qZv,commons:()=>aYf,versions:()=>FZv});var qZv={};var aYf={};yf(aYf,{ChangelogEntryType:()=>RZv,ReleaseType:()=>NZv});var RZv={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var NZv={Ga:"GA",Rc:"RC"};var FZv={};function GNM(e){return e}var JNM={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var uYf={};yf(uYf,{PullRequestState:()=>xZv});var xZv={Open:"open",Closed:"closed",Merged:"merged"};var lYf={};yf(lYf,{latest:()=>sYf,v1:()=>cYf});var sYf={};yf(sYf,{NodeId:()=>YNM,ProductId:()=>XNM,Slug:()=>KNM,TabId:()=>$NM});function KNM(e){return e}function $NM(e){return e}function YNM(e){return e}function XNM(e){return e}var cYf={};yf(cYf,{NavigationV1Availability:()=>rFM,NodeId:()=>eFM,ProductId:()=>tFM,Slug:()=>ZNM,TabId:()=>kNM});function ZNM(e){return e}function kNM(e){return e}function eFM(e){return e}function tFM(e){return e}var rFM={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var dYf={};yf(dYf,{Language:()=>zZv,VersionBump:()=>QZv,versions:()=>fYf});var fYf={};yf(fYf,{Language:()=>zZv,VersionBump:()=>QZv});var zZv={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var QZv={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var LZv={};var UZv={};var pYf={};yf(pYf,{PayloadLocation:()=>VZv});var VZv={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var WZv={};var xJs=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function mA(e){return e!=null}var GZv=Gi(EWo(),1);var HZv=["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 mGr(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,GZv.default)(e,{special:HZv}).replace(/V\s(\d)/g,"V$1")}function JZv({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(n=>{let i=[];n.namespace?.forEach(a=>{let o=[...i,a],c=Jj.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:mGr(a)},i.push(a)})}),r}var zJs=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 KZv(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var LO=class extends zJs{context;accessPath;pathId;constructor({input:t,context:r,accessPath:n,pathId:i}){if(super(t,r),this.context=r,this.accessPath=[...n],this.pathId=i,i!=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 ${KZv(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})}}},hte=class extends LO{},Oze=class extends hte{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var $Zv="x-fern-base-path",YZv="x-fern-availability",QJs="x-fern-sdk-group-name",XZv="x-fern-global-headers",ZZv="x-fern-sdk-method-name";var kZv="x-fern-webhook",ekv="x-fern-access-token-locator",tkv="x-fern-basic",rkv="x-fern-username-variable-name",nkv="x-fern-password-variable-name",ikv="x-fern-bearer",akv="x-fern-token-variable-name",okv="x-fern-header",ukv="x-fern-header-variable-name",skv="x-fern-server-name",ckv="x-fern-examples";var LJs=class extends LO{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[skv]}convert(){if(this.serverName!=null)return this.serverName}};var UJs=class extends LO{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,n])=>t.replace(`{${r}}`,n.default),this.input.url)??this.input.url,this.serverName=new LJs({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:Jj.EnvironmentId(t),baseUrl:this.url}}};function Q5i(e,t,r,n){let i=e??[],a=new Set(i.map(c=>c.url)),o=(t??[]).filter(c=>!a.has(c.url)).map((c,f)=>new UJs({input:c,context:r,accessPath:n,pathId:["servers",`${f}`]}));return[...i,...o]}function Zx(e){return typeof e=="object"&&mA(e)&&"$ref"in e&&typeof e.$ref=="string"}function dge(e,t,r){let n=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),i=t;for(let a of n){if(typeof i!="object"||i==null)return r;i=i[a]}return i==null?r:(Zx(i)&&(i=dge(i,t,r)),i)}function VJs(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return Zx(r)?dge(r,t,void 0):r}var Ckv=Gi(gK());var WJs=class extends LO{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[tkv];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var HJs=class extends LO{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[nkv]}convert(){return this.passwordVariableName}};var GJs=class extends LO{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[rkv]}convert(){return this.usernameVariableName}};var JJs=class extends LO{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ikv];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var KJs=class extends LO{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[akv]}convert(){return this.tokenVariableName}};function lkv(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var fkv="x-bearer-format",dkv="x-code-samples",pkv="x-codeSamples";var $Js=class extends LO{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[fkv]}convert(){return this.bearerFormat}};var YJs=class extends LO{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[okv];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var XJs=class extends LO{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[ukv]}convert(){return this.headerVariableName}};function _kv(e){return e.type==="apiKey"}var Zco=class extends LO{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){_kv(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new YJs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new XJs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new $Js({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 ZJs(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function kJs(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function eKs(e){let t=[],r=e.length;if(r===0)return t;let n=0,i="",a="",o=!1;for(e.charCodeAt(0)===46&&(t.push(""),n++);n<r;){let c=e[n];a?c==="\\"&&n+1<r?(n++,i+=e[n]):c===a?a="":i+=c:o?c==='"'||c==="'"?a=c:c==="]"?(o=!1,t.push(i),i=""):i+=c:c==="["?(o=!0,i&&(t.push(i),i="")):c==="."?i&&(t.push(i),i=""):i+=c,n++}return i&&t.push(i),t}function ouu(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(qUs(t))return r;let n=e[t];return n===void 0?ZJs(t)?ouu(e,eKs(t),r):r:n}case"number":case"symbol":{typeof t=="number"&&(t=kJs(t));let n=e[t];return n===void 0?r:n}default:{if(Array.isArray(t))return nFM(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),qUs(t))return r;let n=e[t];return n===void 0?r:n}}}function nFM(e,t,r){if(t.length===0)return r;let n=e;for(let i=0;i<t.length;i++){if(n==null||qUs(t[i]))return r;n=n[t[i]]}return n===void 0?r:n}function hkv(e){return function(t){return ouu(t,e)}}function ykv(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function _Yf(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function vkv(e,t,r){return typeof r!="function"?kco(e,t):hYf(e,t,function n(i,a,o,c,f,s){let u=r(i,a,o,c,f,s);return u!==void 0?!!u:hYf(i,a,n,s)},new Map)}function hYf(e,t,r,n){if(t===e)return!0;switch(typeof t){case"object":return iFM(e,t,r,n);case"function":return Object.keys(t).length>0?hYf(e,{...t},r,n):_Yf(e,t);default:return ykv(e)?typeof t=="string"?t==="":!0:_Yf(e,t)}}function iFM(e,t,r,n){if(t==null)return!0;if(Array.isArray(t))return bkv(e,t,r,n);if(t instanceof Map)return aFM(e,t,r,n);if(t instanceof Set)return oFM(e,t,r,n);let i=Object.keys(t);if(e==null)return i.length===0;if(i.length===0)return!0;if(n&&n.has(t))return n.get(t)===e;n&&n.set(t,e);try{for(let a=0;a<i.length;a++){let o=i[a];if(!DUs(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,n))return!1}return!0}finally{n&&n.delete(t)}}function aFM(e,t,r,n){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[i,a]of t.entries()){let o=e.get(i);if(r(o,a,i,e,t,n)===!1)return!1}return!0}function bkv(e,t,r,n){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let i=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(i.has(f))continue;let s=e[f],u=!1;if(r(s,o,a,e,t,n)&&(u=!0),u){i.add(f),c=!0;break}}if(!c)return!1}return!0}function oFM(e,t,r,n){return t.size===0?!0:e instanceof Set?bkv([...e],[...t],r,n):!1}function kco(e,t){return vkv(e,t,()=>{})}function gkv(e){return e=Fjv(e),t=>kco(t,e)}function mkv(e,t){return Njv(e,(r,n,i,a)=>{let o=t?.(r,n,i,a);if(o!==void 0)return o;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case MUs:case IUs:case BUs:{let c=new e.constructor(e?.valueOf());return s5i(c,e),c}case TUs:{let c={};return s5i(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function Okv(e){return mkv(e)}var uFM=/^(?:0|[1-9]\d*)$/;function Akv(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 uFM.test(e)}}function Pkv(e){return e!==null&&typeof e=="object"&&CUs(e)==="[object Arguments]"}function wkv(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&ZJs(t)&&e?.[t]==null?r=eKs(t):r=[t],r.length===0)return!1;let n=e;for(let i=0;i<r.length;i++){let a=r[i];if((n==null||!Object.hasOwn(n,a))&&!((Array.isArray(n)||Pkv(n))&&Akv(a)&&a<n.length))return!1;n=n[a]}return!0}function jkv(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=kJs(e);break}}return t=Okv(t),function(r){let n=ouu(r,e);return n===void 0?wkv(r,e):t===void 0?n===void 0:kco(n,t)}}function Ekv(e){if(e==null)return AVs;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?jkv(e[0],e[1]):gkv(e);case"string":case"symbol":case"number":return hkv(e)}}function yYf(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(yYf).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function tKs(e,t=AVs){return e==null?{}:nge(e,Ekv(t))}function Skv(e){return typeof e!="string"&&(e=yYf(e)),e.replace(/['\u2019]/g,"")}function HNr(e){return zjv(Skv(e))}function e5(e){if(e!=null)return Array.isArray(e)?e:[e]}function rKs({namespace:e,path:t,method:r,sdkMethodName:n,operationId:i,displayName:a,isWebhook:o}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(n==null&&i==null&&a==null&&c==null))return`${sFM(o)}${cFM(e)}.${lFM(n,i,a,c)}`}function sFM(e){return e?"webhook_":"endpoint_"}function cFM(e){return e!=null?e5(e)?.map(t=>HNr(t)).join("/"):""}function lFM(e,t,r,n){return e||t||HNr(r??"")||HNr(n??"")}function Dkv(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var nKs=class extends LO{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[ekv],this.accessTokenLocator!=null&&(Dkv(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 iKs=class extends LO{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 Zco({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new nKs({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=rKs({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:Jj.EndpointId(r),accessTokenLocator:Jj.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var elo=class extends LO{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 WJs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new GJs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new HJs({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 JJs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new KJs({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":{lkv(this.input)?(this.authScheme="header",this.headerAuthNode=new Zco({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 iKs({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 Ckv.UnreachableCaseError(this.authScheme);return}}};var tlo=class extends LO{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(n=>{let i=VJs(n,this.context.document);if(i==null){this.context.errors.warning({message:`No auth scheme found for ${n}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new elo({input:i,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[n]=a):this.context.errors.warning({message:`No auth scheme found for ${n}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let n=r.convert();if(n!=null)return[t,n]}).filter(mA))}};var aKs=class extends LO{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[$Zv],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 Ikv(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function Mkv(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function rlo(e,t){return e==null?void 0:Object.entries(e).map(([n,i])=>e5(i.convert())?.map(o=>((t!=null&&!t.includes(n)||t==null&&!Ikv(i))&&(o=Mkv(o,o.type==="enum"?o.default:void 0)),{key:Jj.PropertyKey(n),valueShape:o,description:i.description,availability:i.availability?.convert()})).filter(mA)).filter(mA).reduce((n,i)=>n.flatMap(a=>i.length>0?i.map(o=>[...a,o]):[[...a]]),[[]])}function oKs(e,t){return Zx(e)?dge(e,t,void 0):e}function L5i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function Bkv(e,t){let r={...e};for(let[n,i]of Object.entries(t??{}))r[n]=[...r[n]??[],...i];return Object.keys(r).length>0?r:void 0}function Tkv(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let n of e)for(let i of t)r.push({path:n.path??i.path,responseStatusCode:n.responseStatusCode??i.responseStatusCode,name:n.name??i.name,description:n.description??i.description,pathParameters:n.pathParameters??i.pathParameters,queryParameters:n.queryParameters??i.queryParameters,headers:n.headers??i.headers,requestBody:n.requestBody??i.requestBody,responseBody:n.responseBody??i.responseBody,snippets:{...i.snippets,...n.snippets}});return r}var qkv=Gi(gK());var vYf=["decimal","decimal128","double-int","double","float","sf-decimal"],bYf=["int16","int32","int64","int8","sf-integer","uint8"],gYf=["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"],mYf=["beta","pre-release","in-development","generally-available","deprecated"];function yte(e,t){return Zx(e)?dge(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var Uvt=class extends LO{availability;constructor(t){super(t),this.safeParse()}parse(){if(yte(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[YZv];r!=null&&(mYf.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${mYf.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return Jj.Availability.Beta;case"in-development":return Jj.Availability.InDevelopment;case"generally-available":return Jj.Availability.GenerallyAvailable;case"deprecated":return Jj.Availability.Deprecated;case void 0:return;default:new qkv.UnreachableCaseError(this.availability);return}}};var sKs=Gi(gK());function Rkv(e){return typeof e=="object"&&e!=null&&"language"in e}function Nkv(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Fkv(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function xkv(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function uKs(e){return typeof e=="object"&&e!=null&&"event"in e}function OYf(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(uKs)}function U5i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function zkv(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var cKs=class extends LO{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,n,i,a){super(t),this.path=r,this.successResponseStatusCode=n,this.requestBodyByContentType=i,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[ckv]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([i,a])=>{let o=typeof r=="object"?r[i]:void 0;switch(a.multipartType){case"file":return U5i(o)?[i,{type:"filenameWithData",filename:o.filename,data:Jj.FileId(o.data)}]:o!=null?[i,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>U5i(c)))return[i,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:Jj.FileId(c.data)}))}];if(o.every(c=>typeof c=="string"))return[i,{type:"filenames",value:o}]}return}case"property":return[i,{type:"json",value:o}];case void 0:return;default:new sKs.UnreachableCaseError(a.multipartType);return}}).filter(mA))};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(n=>{let i=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(i!=null)switch(i.contentType){case"form-data":a=zkv(r.request)?this.convertFormDataExampleRequest(i,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 sKs.UnreachableCaseError(i.contentType);break}let o;switch(n.contentType){case"application/json":{Fkv(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{OYf(r.response)&&(o={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!OYf(r.response)&&xkv(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new sKs.UnreachableCaseError(n.contentType);break}let c={};r["code-samples"]?.forEach(l=>{Rkv(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})):Nkv(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,m])=>[Jj.PropertyKey(l),m])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,m])=>[Jj.PropertyKey(l),m])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([l,m])=>[Jj.PropertyKey(l),m]));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 uuu=class extends LO{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[QJs]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>Jj.api.v1.SubpackageId(HNr(r)))}};var lKs=class extends LO{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[ZZv]}convert(){return this.sdkMethodName}};var fKs=class extends LO{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[kZv]}convert(){return this.isWebhook}};var dKs=class extends LO{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[dkv]??[],...this.input[pkv]??[]],this.codeSamples.forEach(t=>{[...Object.values(Jj.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 sya=Gi(gK());function AYf(e,t){return Zx(e)?dge(e,t,void 0):e}function Qkv(e,t){return e.replace(/{(\w+)}/g,(r,n)=>t[n]!=null&&typeof t[n]=="string"||typeof t[n]=="number"||typeof t[n]=="boolean"?`${t[n]}`:r)}var vpe="",OGr=class extends LO{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,n,i,a){super(t),this.path=r,this.responseStatusCode=n,this.name=i,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,n])=>{let i=this.resolvedRequestInput?.value[r];switch(n.multipartType){case"file":return t&&(U5i(i)||typeof i=="string");case"files":return t&&Array.isArray(i)&&i.every(a=>U5i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new sya.UnreachableCaseError(n.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=AYf(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=AYf(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 sya.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(uKs)){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 sya.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,n])=>{let i=this.resolvedRequestInput?.value?.[r];switch(n.multipartType){case"file":return U5i(i)?[r,{type:"filenameWithData",filename:i.filename,data:Jj.FileId(i.data)}]:[r,{type:"filename",value:i}];case"files":{if(Array.isArray(i)){if(i.every(a=>U5i(a)))return[r,{type:"filenamesWithData",value:i.map(a=>({filename:a.filename,data:Jj.FileId(a.data)}))}];if(i.every(a=>typeof a=="string"))return[r,{type:"filenames",value:i}]}return}case"property":return[r,{type:"json",value:i}];case void 0:return;default:new sya.UnreachableCaseError(n.multipartType);return}}).filter(mA))};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 sya.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 sya.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let n=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([o,c])=>[o,c.example({includeOptionals:!1,override:o})]));n=Object.keys(n).length>0?n:void 0;let i=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(mA));i=Object.keys(i).length>0?i: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(mA));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&i==null&&n==null))return{path:Qkv(this.path,n??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?mGr(this.name):this.summary!=null?mGr(this.summary):void 0,description:this.convertDescription(),pathParameters:n,queryParameters:i,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function Lkv(e,t){return Zx(e)?dge(e,t,void 0):e}var eeb=Gi(gK());var Ukv="#/components/schemas/";function nlo(e){if(e.$ref.startsWith(Ukv))return e.$ref.replace(Ukv,"")}function eEi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function V5i(e){return typeof e.type=="string"&&e.type==="array"}function Vkv(e){return e.type==="boolean"}function Wkv(e){return e.type==="integer"}function W5i(e){return!Array.isArray(e.type)&&!V5i(e)}function Hkv(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||W5i(t)||V5i(t))}function Gkv(e){return"nullable"in e&&typeof e.nullable=="boolean"}function Jkv(e){return e.type==="null"}function Kkv(e){return e.type==="number"}function PYf(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function $kv(e){return e.type==="string"}var pKs=class extends Oze{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new LU({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 e5(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 _Ks=class extends hte{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 Uvt({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 hKs=class extends Oze{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 LU({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(mA)}convert(){if(this.typeNodes==null)return;let n=this.typeNodes.map(i=>e5(i.convert())?.map(o=>({displayName:i.name,shape:o,description:i.description,availability:i.availability?.convert()}))).filter(mA).reduce((i,a)=>i.flatMap(o=>a.length>0?a.map(c=>[...o,c]):[[...o]]),[[]]).map(i=>({type:"undiscriminatedUnion",variants:i}));return this.nullable?n.map(eEi).filter(mA):n}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function yKs(e){return e!=null&&e.length>0?e:[void 0]}var ilo=class extends Oze{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 LU({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 LU({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(Zx(t))return nlo(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([n,i])=>[n,new LU({input:i,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",n],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(mA))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return rlo(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}}}]:e5(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(mA)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(n=>yKs(r).map(i=>(this.extends==null||this.extends.length===0)&&n.length===0&&i!=null?{type:"alias",value:i}:{type:"object",extends:this.extends.map(a=>Jj.TypeId(a)),properties:n,extraProperties:i}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(n=>{let i=yte(n,this.context.document);i!=null&&(r={...r,...Object.fromEntries(Object.entries(i.properties??{}).map(([a,o])=>[a,new LU({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((n,i)=>{let a=r?.[i];return n[i]=a?.example({includeOptionals:t,override:i}),n},{}):Object.entries(r).reduce((n,[i,a])=>(n[i]=a?.example({includeOptionals:t,override:i}),n),{}))}};var vKs=class extends Oze{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=>yte(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>yte(t,this.context.document)?.type!=="null"?new LU({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(mA);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(([n,i])=>{let a=yte({$ref:i},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${i}`,path:[...this.accessPath,"discriminator","mapping",n]});return}r[n]=new LU({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",n],pathId:n,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let i=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(mA);return this.isNullable&&i!=null?i.map(eEi).filter(mA):i}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:Jj.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([i,a])=>e5(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:i,displayName:a.name??mGr(i),availability:a.availability?.convert(),description:a.description,...c}}).filter(mA)).filter(mA)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(i=>e5(i.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?mGr(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:i.name??(o.type==="alias"&&o.value.type==="id"?mGr(o.value.id):c),shape:o,description:i.description,availability:i.availability?.convert()}}).filter(mA)).filter(mA)}:void 0,n=this.isNullable?eEi(r):r;return n!=null?[n]: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 bKs=class extends hte{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 H5i=class extends hte{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,n)=>{if(t){if(Zx(r)){let i=yte(r,this.context.document);r=typeof i=="string"?i:typeof i?.default=="string"?i?.default:typeof i?.example=="string"?i.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${n}]`]}),t=!1;return}return r}}).filter(mA),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 Ykv=Gi(gK());function fFM(e){return bYf.includes(e)}var gKs=class extends hte{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&&(fFM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${bYf.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 Ykv.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 mKs=class extends hte{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return eEi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var Xkv=Gi(gK());function dFM(e){return vYf.includes(e)}var OKs=class extends hte{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&&(dFM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${vYf.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 Xkv.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 Zkv=Gi(gK());function pFM(e){return gYf.includes(e)}var AKs=class extends hte{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 Zkv.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&&(pFM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${gYf.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new H5i({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 kkv=Gi(gK());var PKs=class extends hte{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,kkv.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var cya=class extends Oze{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=nlo(this.input);let t=yte(this.input,this.context.document);t?.enum!=null&&W5i(t)&&(this.maybeEnumConverterNode=new H5i({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:Jj.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=yte(this.input,this.context.document);if(r!=null)return new LU({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var LU=class e extends Oze{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 Uvt({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),W5i(this.input)&&Gkv(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),Zx(this.input)){let t=nlo(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 cya({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 _Ks({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(Hkv(this.input))this.typeShapeNode=new hKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(W5i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new vKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(PYf(this.input)&&this.input.allOf!=null)this.typeShapeNode=new ilo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(W5i(this.input)&&this.input.enum!=null)this.typeShapeNode=new H5i({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":PYf(this.input)&&(this.typeShapeNode=new ilo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":V5i(this.input)&&(this.typeShapeNode=new pKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":Vkv(this.input)&&(this.typeShapeNode=new bKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":Wkv(this.input)&&(this.typeShapeNode=new gKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":Kkv(this.input)&&(this.typeShapeNode=new OKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":$kv(this.input)&&(this.typeShapeNode=new AKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":Jkv(this.input)&&(this.typeShapeNode=new mKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new eeb.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 ilo({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 PKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!Zx(this.input)&&(!V5i(this.input)&&this.input==null||V5i(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=e5(t)?.map(n=>this.nullable?eEi(n):n).filter(mA);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function G5i(e){if(e!=null)return rlo(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(mA))}var AGr=class extends hte{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;Zx(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 Uvt({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new LU({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let n=Lkv(this.input,this.context.document);this.inputExample=n?.example??Object.values(n?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function teb(e,t){return Zx(e)?dge(e,t,void 0):e}var wYf=Gi(gK());function wKs(e){let{uniqueId:t,type:r,contextTypes:n,description:i,availability:a}=e;n[Jj.TypeId(t)]={name:t,shape:r,description:i,availability:a}}var reb=Gi(Ckl(),1),alo=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,n,i,a,o){this.type=t,this.subtype=r,this.essence=n,this.parameters=i,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=reb.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 _FM(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var jKs=class extends LO{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 LU({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),_FM(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],n)=>{let i;if(Zx(r)?i=VJs(r.$ref,this.context.document):i=r,i!=null)return[t,new elo({input:i,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${n}`]})]}).filter(mA)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let n=r.convert();if(n!=null)return[Jj.api.latest.AuthSchemeId(t),n]}).filter(mA)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let n=r.name??t,i=e5(r.convert());return i==null?[t,void 0]:[Jj.TypeId(t),{name:n,shape:i[0],description:r.description,availability:void 0}]}).filter(([t,r])=>mA(r))):void 0}}};var EKs=class extends LU{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=yte(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${Zx(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=yte(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 SKs=class extends LO{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 n=yte(this.input.schema,this.context.document);this.availability=new Uvt({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=Zx(this.input.schema)?new cya({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 i=alo.parse(t);i?.containsJSON()?(this.contentType="json",this.schema=this.schema??new LU({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):i?.isOctetStream()?(this.contentType="bytes",this.isOptional=n?.required==null):i?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=n?.required,this.fields=Object.fromEntries(Object.entries(n?.properties??{}).map(([a,o])=>{if(o!=null)return[a,new EKs({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(mA))):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?{[vpe]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[vpe]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:e5(t)?.map(n=>{let i=n.type;switch(i){case"object":case"alias":return n;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=HNr([this.method,this.path,this.contentType,"request"].join("_"));return wKs({uniqueId:a,type:n,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Jj.TypeId(a),default:n.type==="enum"&&n.default!=null?{type:"enum",value:n.default}:void 0}}}case void 0:return;default:new wYf.UnreachableCaseError(i);return}}).filter(mA)}convert(){if(this.schema instanceof cya)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(([n,i])=>{switch(i.multipartType){case"file":return[{type:i.multipartType,key:Jj.PropertyKey(n),isOptional:this.requiredFields?.includes(n)==null,contentType:i.contentType,description:i.description,availability:i.availability?.convert()}];case"files":return[{type:i.multipartType,key:Jj.PropertyKey(n),isOptional:this.requiredFields?.includes(n)==null,contentType:i.contentType,description:i.description,availability:i.availability?.convert()}];case"property":{let a=e5(i.convert()),o=i.multipartType;return a?.map(c=>({type:o,key:Jj.PropertyKey(n),contentType:i.contentType,exploded:void 0,valueShape:c,description:i.description,availability:i.availability?.convert()}))}case void 0:return[];default:return new wYf.UnreachableCaseError(i.multipartType),[]}}).filter(mA).reduce((n,i)=>n.flatMap(a=>i.length>0?i.map(o=>[...a,o]):[[...a]]),[[]]).map(n=>({type:"formData",fields:n,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var DKs=class extends LO{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let n=teb(this.input,this.context.document);if(n==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(n.content).forEach(([i,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[i]=new SKs({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:i,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>e5(r.convert())?.map(i=>({description:this.description,contentType:t,body:i}))).filter(mA)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>e5(t.convert())?.map(n=>{if(!(n.type!=="alias"&&n.type!=="object"))return{description:this.description,shape:n}})).filter(mA)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var neb={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 ieb(e,t){if(Zx(e)){let r=dge(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var CKs=Gi(gK());var aeb="application/json";var oeb="application/octet-stream";function ueb(e,t){return e===t||t===vpe||e===vpe}var suu=class extends LO{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,n,i,a,o,c,f){super(t),this.streamingFormat=n,this.path=i,this.method=a,this.statusCode=o,this.requests=c,this.shapes=f,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,n){for(let i of t)for(let[a,o]of Object.entries(i?.examples??{}))for(let[c,f]of Object.entries(r))for(let s of f)ueb(c,a)&&(n.add(c),this.examples?.push(new OGr({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,L5i(a,c),{requestBody:i,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let n=0;for(let i of t){let a=0;for(let[o,c]of r){if(a===n){let[f,s,u]=i??[void 0,void 0,void 0];this.examples?.push(...c.map(l=>new OGr({input:{requestExample:u,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,L5i(s,o),{requestBody:f,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}n++}if(t.length>r.length)for(let i of t.slice(r.length)){let[a,o]=r[r.length-1]??[void 0,void 0],[c,f,s]=i??[void 0,void 0,void 0];this.examples?.push(...(o??[void 0]).map(u=>new OGr({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:f!=null&&f!==""?["examples",f]:"examples"},this.path,this.statusCode,L5i(f,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[i,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 OGr({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,L5i(a,c),{requestBody:i,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,n,i){let a=t[vpe];if(a!=null)for(let o of a)this.examples?.push(new OGr({input:{requestExample:i,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:n!=null&&n!==""?["examples",n]:"examples"},this.path,this.statusCode,L5i(n,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 n of t)if(Object.keys(n.examples??{}).length===0)this.pushResponseExample(r,n,void 0,void 0);else for(let[i,a]of Object.entries(n.examples??{}))this.pushResponseExample(r,n,i,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=alo.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=aeb,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 LU({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=oeb,this.contentSubtype=yte(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 LU({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=tKs(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[vpe]??=[],r[vpe]=[{value:this.input.example}]);let n=yte(this.input.schema,this.context.document);if(n!=null&&(n.examples!=null&&Object.keys(r).length===0&&(r=tKs(n.examples,c=>[c])),n.example!=null&&Object.keys(r).length===0&&(r[vpe]??=[],r[vpe]?.push({value:n.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[vpe]??=[],r[vpe]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let i=new Set;this.matchRequestResponseExamplesByName(this.requests,r,i);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([f])=>!i.has(f)&&f!==vpe).map(([f,s])=>[c,f,s]));let o=Object.entries(r).filter(([c,f])=>!i.has(c)&&mA(f)&&c!==vpe);Object.keys(r).every(c=>c===vpe)||this.matchExamplesByIndex(a,o),!i.has(vpe)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return e5(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new CKs.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return e5(this.schema?.convert())?.map(r=>{let n=r.type;switch(n){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let i=HNr([this.method,this.path,this.statusCode,"response"].join("_"));return wKs({uniqueId:i,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:Jj.TypeId(i),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new CKs.UnreachableCaseError(n);return}}).filter(mA)}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 CKs.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var cuu=class extends LO{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,n,i,a,o){super(t),this.path=r,this.method=n,this.statusCode=i,this.requests=a,this.shapes=o,this.safeParse()}parse(t){this.description=this.input.description;let r=ieb(this.input,this.context.document);if(r==null){this.context.errors.error({message:Zx(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([n,i])=>{this.headers??={},this.headers[n]=new AGr({input:i,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:n})}),r.content==null?(this.responses??=[],this.responses.push(new suu({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(([n,i])=>{this.responses??=[],this.responses.push(new suu({input:i,context:this.context,accessPath:this.accessPath,pathId:["content",n]},n,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(mA)}};var IKs=class extends LO{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,n,i,a){super(t),this.path=r,this.method=n,this.requests=i,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,n])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new cuu({input:{...t,...n},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new cuu({input:n,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 n=r.convert();if(n!=null)return yKs(G5i(r.headers)).flatMap(i=>n?.map(a=>({headers:i,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(o=>(o.examples??[]).map(c=>c.convert()).filter(mA))})))}).filter(mA)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(n=>{let i=n.schema,a=e5(i?.convert());if(i!=null)return a?.map(o=>({statusCode:parseInt(t),shape:o,description:r.description??i.description,availability:i.availability?.convert(),name:i.name??neb[parseInt(t)]??"UNKNOWN ERROR",examples:n.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(mA)})).filter(mA)})).filter(mA)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var J5i=class extends LO{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,n){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new OGr({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,L5i(n,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 Uvt({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=Q5i(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new fKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((n,i)=>{if(Zx(n)){let a=oKs(n,this.context.document);if(a!=null)n=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${n.$ref}`,path:[...this.accessPath,`parameters[${i}]`]});return}}n.in==="path"?n.schema!=null&&(this.pathParameters??={},this.pathParameters[n.name]=new AGr({input:n,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${i}`],parameterName:n.name})):n.in==="query"?n.schema!=null&&(this.queryParameters??={},this.queryParameters[n.name]=new AGr({input:n,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${i}`],parameterName:n.name})):n.in==="header"&&n.schema!=null&&(this.requestHeaders??={},this.requestHeaders[n.name]=new AGr({input:n,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${i}`],parameterName:n.name}))});for(let n of this.extractPathParameterIds()??[])this.pathParameters?.[n]==null&&this.context.errors.warning({message:`Path parameter not defined: ${n}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new dKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new DKs({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 IKs({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 n=this.requests?.requestBodiesByContentType;n==null||Object.keys(n).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(n).forEach(i=>{if(Object.keys(i.examples??{}).length===0){let a=i.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},i,void 0)}else Object.entries(i.examples??{}).forEach(([a,o])=>{this.pushEmptyResponseExample(o,i,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(n=>Number(n)>=200&&Number(n)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new tlo({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new uuu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(n=>n.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((n,i)=>new uuu({input:{[QJs]:n},context:this.context,accessPath:this.accessPath,pathId:["tags",`${i}`]})));let r=new lKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(n=>rKs({namespace:e5(n?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(mA),this.xFernExamplesNode=new cKs({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(mA)}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((i,a)=>(i.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?i.push({type:"pathParameter",value:Jj.PropertyKey(a.slice(1,-1).trim())}):i.push({type:"literal",value:a}),i),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},n=this.emptyResponseExamples?.map(u=>u.convert()).filter(mA),i=Tkv(this.xFernExamplesNode?.convert(),[...n??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:Bkv(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:Jj.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(m=>m.value.toString())??[],queryParameters:G5i(this.queryParameters)?.flat(),headers:G5i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(mA)}}).filter(mA);let a=this.servers?.map(u=>u.convert()).filter(mA),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(mA);return this.endpointIds.map((u,l)=>({id:Jj.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(m=>Jj.api.v1.SubpackageId(m)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(m=>Jj.api.latest.AuthSchemeId(m)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:G5i(this.pathParameters)?.flat(),queryParameters:G5i(this.queryParameters)?.flat(),requestHeaders:G5i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(m=>m.response),errors:r,examples:i,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var olo=class extends LO{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:n,isWebhook:i}){this.description=this.input.description;let a=Q5i(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 J5i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:o,method:"GET",basePath:n,isWebhook:i})),this.input.post!=null&&(this.post=new J5i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:o,method:"POST",basePath:n,isWebhook:i})),this.input.put!=null&&(this.put=new J5i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:o,method:"PUT",basePath:n,isWebhook:!1})),this.input.patch!=null&&(this.patch=new J5i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:o,method:"PATCH",basePath:n,isWebhook:!1})),this.input.delete!=null&&(this.delete=new J5i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:o,method:"DELETE",basePath:n,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(mA)}};function MKs(e){return"payloads"in e}var BKs=class extends LO{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:n}){this.paths=Object.entries(this.input).map(([i,a])=>{if(a!=null)return new olo({input:a,context:this.context,accessPath:this.accessPath,pathId:i,servers:Q5i(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:n,isWebhook:void 0})}).filter(mA)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(n=>{let i=n.convert();i?.forEach(a=>{MKs(a)?r[Jj.WebhookId(a.id)]=a:t[Jj.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var TKs=class extends LO{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[XZv]?.map(r=>{let{header:n,...i}=r;return(i.optional!=null&&!i.optional||oKs(i,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(n)),[n,new AGr({input:i,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:n})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return rlo(this.globalHeaders,this.requiredProperties)?.flat()}};function seb(e,t){if(Zx(e)){let r=dge(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var qKs=class extends LO{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:n}){this.webhooks=Object.entries(this.input??{}).map(([i,a])=>{let o=seb(a,this.context.document);if(o!=null)return new olo({input:o,context:this.context,accessPath:this.accessPath,pathId:i,servers:t,globalAuth:r,basePath:n,isWebhook:!0})}).filter(mA)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(n=>{MKs(n)&&(t[Jj.WebhookId(n.id)]=n)}),t),{})}};var RKs=class extends LO{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=Q5i(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new tlo({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new aKs({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 BKs({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 qKs({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 jKs({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new TKs({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=yit(),{webhookEndpoints:r,endpoints:n}=this.paths?.convert()??{},i={...this.webhooks?.convert()??{},...r??{}},a=JZv({endpoints:n,webhookEndpoints:i}),{types:o,auths:c}=this.components?.convert()??{};return{id:Jj.ApiDefinitionId(t),endpoints:n??{},websockets:{},webhooks:i,types:{...o,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};async function jYf(e,t){if(e instanceof rHr){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof tY))return;let r=new $Rr(e.absoluteFilePath),n=await Mvt({context:t,specs:e.specs}),i=await r.loadDocuments({context:t,specs:n}),a;for(let o of i){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new xJs,generatedTypes:{}},f=new RKs({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=Hkl(a,f.convert())}return a}var Plb=Gi(DYf(),1),wlb=Gi(A$s(),1),jlb=require("fs/promises"),Elb=Gi(require("http"),1),Slb=Gi(require("path"),1);var sab=require("events"),S$s=Gi(require("fs"),1),gya=Gi(require("path"),1);var Wib=Gi(require("os"),1),Hib=300,eLi=20,Tuu=1e7,Gib=Wib.default.platform();var B8M=Gib==="darwin",JXf=Gib==="win32",tLi=B8M||JXf,Jib=3e3,Kib=2e4,KXf=1250;var EGr;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(EGr||(EGr={}));var bya;(function(e){e.CHANGE="change",e.RENAME="rename"})(bya||(bya={}));var quu;(function(e){e.CHANGE="change",e.ERROR="error"})(quu||(quu={}));var zS;(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"})(zS||(zS={}));var UIe;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(UIe||(UIe={}));var T8M=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,f=0,s=0,u=()=>{let q=Date.now(),V=q-f,$=q-s,re=V>=t||$>=a;return[q,re]},l=q=>{if(s=q,!o)return;let V=o;o=void 0,e.apply(void 0,V)},m=()=>{z(0)},A=()=>{c&&(m(),l(Date.now()))},P=q=>{if(s=q,n)return l(q)},C=q=>{if(i&&o)return l(q);o=void 0},M=()=>{c=void 0;let[q,V]=u();return V?C(q):T(q)},T=q=>{let V=q-f,$=q-s,re=t-V,X=a-$,k=Math.min(re,X);return z(k)},z=q=>{c&&clearTimeout(c),!(q<=0)&&(c=setTimeout(M,q))},U=(...q)=>{let[V,$]=u(),re=!!c;if(o=q,f=V,($||!c)&&z(t),$)return re?l(V):P(V)};return U.cancel=m,U.flush=A,U},P$s=T8M;var ZXf=Gi(require("fs"),1),j$s=Gi(require("path"),1);var d6=Gi(require("fs"),1),pge=require("util");var rEi=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},SGr=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var $Xf=Gi(require("process"),1),$ib=$Xf.default.getuid?!$Xf.default.getuid():!1,Yib=1e4,jze=()=>{};var Ruu={isChangeErrorOk:e=>{if(!Ruu.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!$ib&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!Ruu.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(!Ruu.isNodeError(e))throw e;if(!Ruu.isChangeErrorOk(e))throw e}},vte=Ruu;var YXf=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=Yib,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(n),n=()=>t(r);this.add(n)}),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()}}}}},Xib=new YXf;var nEi=(e,t)=>function(n){return function i(...a){return Xib.schedule().then(o=>{let c=s=>(o(),s),f=s=>{if(o(),Date.now()>=n)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(m=>setTimeout(m,u)).then(()=>i.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,f)})}},iEi=(e,t)=>function(n){return function i(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>n)throw o;if(t(o))return i.apply(void 0,a);throw o}}};var q8M={attempt:{chmod:rEi((0,pge.promisify)(d6.default.chmod),vte.onChangeError),chown:rEi((0,pge.promisify)(d6.default.chown),vte.onChangeError),close:rEi((0,pge.promisify)(d6.default.close),jze),fsync:rEi((0,pge.promisify)(d6.default.fsync),jze),mkdir:rEi((0,pge.promisify)(d6.default.mkdir),jze),realpath:rEi((0,pge.promisify)(d6.default.realpath),jze),stat:rEi((0,pge.promisify)(d6.default.stat),jze),unlink:rEi((0,pge.promisify)(d6.default.unlink),jze),chmodSync:SGr(d6.default.chmodSync,vte.onChangeError),chownSync:SGr(d6.default.chownSync,vte.onChangeError),closeSync:SGr(d6.default.closeSync,jze),existsSync:SGr(d6.default.existsSync,jze),fsyncSync:SGr(d6.default.fsync,jze),mkdirSync:SGr(d6.default.mkdirSync,jze),realpathSync:SGr(d6.default.realpathSync,jze),statSync:SGr(d6.default.statSync,jze),unlinkSync:SGr(d6.default.unlinkSync,jze)},retry:{close:nEi((0,pge.promisify)(d6.default.close),vte.isRetriableError),fsync:nEi((0,pge.promisify)(d6.default.fsync),vte.isRetriableError),open:nEi((0,pge.promisify)(d6.default.open),vte.isRetriableError),readFile:nEi((0,pge.promisify)(d6.default.readFile),vte.isRetriableError),rename:nEi((0,pge.promisify)(d6.default.rename),vte.isRetriableError),stat:nEi((0,pge.promisify)(d6.default.stat),vte.isRetriableError),write:nEi((0,pge.promisify)(d6.default.write),vte.isRetriableError),writeFile:nEi((0,pge.promisify)(d6.default.writeFile),vte.isRetriableError),closeSync:iEi(d6.default.closeSync,vte.isRetriableError),fsyncSync:iEi(d6.default.fsyncSync,vte.isRetriableError),openSync:iEi(d6.default.openSync,vte.isRetriableError),readFileSync:iEi(d6.default.readFileSync,vte.isRetriableError),renameSync:iEi(d6.default.renameSync,vte.isRetriableError),statSync:iEi(d6.default.statSync,vte.isRetriableError),writeSync:iEi(d6.default.writeSync,vte.isRetriableError),writeFileSync:iEi(d6.default.writeFileSync,vte.isRetriableError)}},Zib=q8M;var w$s=Gi(require("fs"),1),Nuu=Gi(require("path"),1);var XXf=()=>{};var R8M=()=>{let e=XXf,t=XXf,r=!1,n=!1;return{promise:new Promise((f,s)=>{e=u=>(r=!0,f(u)),t=u=>(n=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},kib=R8M;var N8M=()=>{let{promise:e,resolve:t,isPending:r}=kib(),n=0,i=()=>{n+=1},a=()=>{n-=1,!n&&t()};return(()=>{i(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:i,decrement:a}},eab=N8M;var tab={then:e=>{e()}};var rab=e=>Array.isArray(e)?e:[e],nab=e=>typeof e=="function";var F8M=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,a=t?.ignore??[],o=rab(a).map(ze=>nab(ze)?ze:Me=>ze.test(Me)),c=ze=>o.some(Me=>Me(ze)),f=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],l=new Set,m={},A=[],P=new Set,C={},M=[],T=new Set,z={},U={},q=new Set,V={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},$={directories:u,directoriesNames:l,directoriesNamesToPaths:m,files:A,filesNames:P,filesNamesToPaths:C,symlinks:M,symlinksNames:T,symlinksNamesToPaths:z,map:U},{promise:re,increment:X,decrement:k}=eab(),ne=0,Oe=(ze,Me,$t,rt)=>{q.has(Me)||ne>=i||(ne+=1,ze.directories.push(Me),ze.directoriesNames.add($t),u.push(Me),l.add($t),m.propertyIsEnumerable($t)||(m[$t]=[]),m[$t].push(Me),q.add(Me),!(rt>=n)&&(ne>=i||Se(Me,rt+1)))},ve=(ze,Me,$t)=>{q.has(Me)||ne>=i||(ne+=1,ze.files.push(Me),ze.filesNames.add($t),A.push(Me),P.add($t),C.propertyIsEnumerable($t)||(C[$t]=[]),C[$t].push(Me),q.add(Me))},me=(ze,Me,$t,rt)=>{q.has(Me)||ne>=i||(ne+=1,ze.symlinks.push(Me),ze.symlinksNames.add($t),M.push(Me),T.add($t),z.propertyIsEnumerable($t)||(z[$t]=[]),z[$t].push(Me),q.add(Me),r&&(rt>=n||ne>=i||jt(Me,rt+1)))},be=(ze,Me,$t,rt,nr)=>{f.aborted||c(Me)||(rt.isDirectory()?Oe(ze,Me,$t,nr):rt.isFile()?ve(ze,Me,$t):rt.isSymbolicLink()&&me(ze,Me,$t,nr))},Ie=(ze,Me,$t,rt)=>{if(f.aborted)return;let nr=Me===Nuu.default.sep?"":Nuu.default.sep,Ft=$t.name,Xe=`${Me}${nr}${Ft}`;c(Xe)||($t.isDirectory()?Oe(ze,Xe,Ft,rt):$t.isFile()?ve(ze,Xe,Ft):$t.isSymbolicLink()&&me(ze,Xe,Ft,rt))},Be=(ze,Me,$t,rt)=>{for(let nr=0,Ft=$t.length;nr<Ft;nr++)Ie(ze,Me,$t[nr],rt)},Se=(ze,Me)=>{f.aborted||Me>n||ne>=i||(X(),w$s.default.readdir(ze,{withFileTypes:!0},($t,rt)=>{if($t||f.aborted||!rt.length)return k();(s(rt)||tab).then(()=>{let Ft=U[ze]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Be(Ft,ze,rt,Me),k()})}))},jt=(ze,Me)=>{X(),w$s.default.realpath(ze,($t,rt)=>{if($t||f.aborted)return k();w$s.default.stat(rt,(nr,Ft)=>{if(nr||f.aborted)return k();let Xe=Nuu.default.basename(rt),pt=U[ze]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};be(pt,rt,Xe,Ft,Me),k()})})};return(async(ze,Me=1)=>(ze=Nuu.default.normalize(ze),q.add(ze),Se(ze,Me),await re,f.aborted?V:$))(e)},iab=F8M;var DGr={lang:{debounce:P$s,attempt:e=>{try{return e()}catch(t){return DGr.lang.castError(t)}},castArray:e=>DGr.lang.isArray(e)?e:[e],castError:e=>DGr.lang.isError(e)?e:DGr.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(DGr.lang.isNaN(e))return DGr.lang.isNaN(t);if(DGr.lang.isPrimitive(e)||DGr.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(j$s.default.sep).length-1),getRealPath:(e,t)=>{try{return t?ZXf.default.realpathSync.native(e):ZXf.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===j$s.default.sep&&t.length-e.length>j$s.default.sep.length,poll:(e,t=Kib)=>Zib.retry.stat(t)(e,{bigint:!0}).catch(DGr.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await iab(e,{depth:r,limit:n,ignore:t,signal:i});return[o.directories,o.files]}}}},SB=DGr;var E$s=Gi(require("path"),1);var kXf=class{constructor(t,r,n){this.base=n,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||SB.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=Hib){return(()=>{let r=this.watcher._readyWait,n=[],i=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=SB.lang.debounce(()=>{this.watcher.isClosed()||(r=a(n,i),n=[],i=new Set)},t);return async(c,f="",s=!1)=>{s?await this.eventsPopulate([f],n,!0):i.add(f),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[a,o]=i,c=r[o];return a===c||a===zS.CHANGE&&c===zS.ADD||(r[o]=a,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let a=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,i]),o===zS.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):o===zS.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let a=this.options.recursive?this.options.depth??eLi:Math.min(1,this.options.depth??eLi),o=this.options.limit??Tuu,[c,f]=await SB.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],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let a of this.watcher._poller.stats.keys())SB.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(zS.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!tLi&&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(zS.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(zS.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(E$s.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(zS.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(E$s.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(zS.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===zS.ADD?this.onTargetAdd(n):r===zS.ADD_DIR?this.onTargetAddDir(n):r===zS.CHANGE?this.onTargetChange(n):r===zS.UNLINK?this.onTargetUnlink(n):r===zS.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=bya.CHANGE,r){if(this.watcher.isClosed())return;let n=E$s.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){JXf&&t.code==="EPERM"?this.onWatcherChange(bya.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(quu.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(quu.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(bya.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&tLi&&this.options.native!==!1?this.options.depth??eLi:Math.min(1,this.options.depth??eLi),n=this.options.limit??Tuu,[i,a]=await SB.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...i,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(bya.CHANGE,c,t)}))}}},aab=kXf;var VIe={interval:100,intervalId:void 0,fns:new Map,init:()=>{VIe.intervalId||(VIe.intervalId=setInterval(VIe.resolve,VIe.interval))},reset:()=>{VIe.intervalId&&(clearInterval(VIe.intervalId),delete VIe.intervalId)},add:(e,t)=>{VIe.fns.set(e,Date.now()+t),VIe.init()},remove:e=>{VIe.fns.delete(e)},resolve:()=>{if(!VIe.fns.size)return VIe.reset();let e=Date.now();for(let[t,r]of VIe.fns)r>=e||(VIe.remove(t),t())}},Fuu=VIe;var xuu=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=KXf){let{ino:n,targetPath:i,events:a,locks:o}=t,c=()=>{let l=this._watcher._poller.paths.find(n||-1,m=>m!==i);if(l&&l!==i){if(SB.fs.getRealPath(i,!0)===l)return;this._watcher.event(a.rename,l,i)}else this._watcher.event(a.add,i)};if(!n)return c();let f=()=>{o.add.delete(n),Fuu.remove(s)},s=()=>{f(),c()};Fuu.add(s,r);let u=()=>{let l=o.unlink.get(n);if(!l)return;f();let m=l();i===m?a.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(a.change,i):this._watcher.event(a.rename,m,i)};o.add.set(n,u),u()}getLockUnlink(t,r=KXf){let{ino:n,targetPath:i,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,i)};if(!n)return c();let f=()=>{o.unlink.delete(n),Fuu.remove(s)},s=()=>{f(),c()};Fuu.add(s,r);let u=()=>(f(),i);o.unlink.set(n,u),o.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,zS.ADD,EGr.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,zS.ADD_DIR,EGr.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,zS.UNLINK,EGr.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,zS.UNLINK_DIR,EGr.DIR);return this.getLockUnlink({ino:n,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}}};xuu.DIR_EVENTS={add:zS.ADD_DIR,rename:zS.RENAME_DIR,unlink:zS.UNLINK_DIR};xuu.FILE_EVENTS={add:zS.ADD,change:zS.CHANGE,rename:zS.RENAME,unlink:zS.UNLINK};var oab=xuu;var eZf=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(SB.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(SB.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(SB.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(SB.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return SB.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);SB.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},tZf=eZf;var rZf=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}},uab=rZf;var nZf=class{constructor(){this.inos={},this.paths=new tZf,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let a=i[t];if(a&&!(n&&a[1]!==n))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await SB.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new uab(n)}reset(){this.inos={},this.paths=new tZf,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,zS.ADD,i),[zS.ADD];if(i.isDirectory())return this.updateIno(t,zS.ADD_DIR,i),[zS.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,zS.UNLINK,n),[zS.UNLINK];if(n.isDirectory())return this.updateIno(t,zS.UNLINK_DIR,n),[zS.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,zS.CHANGE,i),[zS.CHANGE]);if(i.isDirectory())return this.updateIno(t,zS.UNLINK,n),this.updateIno(t,zS.ADD_DIR,i),[zS.UNLINK,zS.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,zS.UNLINK_DIR,n),this.updateIno(t,zS.ADD,i),[zS.UNLINK_DIR,zS.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,zS.UNLINK_DIR,n),this.updateIno(t,zS.ADD_DIR,i),[zS.UNLINK_DIR,zS.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=n.isFile()?EGr.FILE:EGr.DIR;i[t]=[n.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},iZf=nZf;var aZf=class e extends sab.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(UIe.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(UIe.CLOSE,i)),this._readyWait=new Promise(i=>this.on(UIe.READY,i)),this._locker=new oab(this),this._roots=new Set,this._poller=new iZf,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(SB.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(UIe.CLOSE))}error(t){if(this.isClosed())return!1;let r=SB.lang.castError(t);return this.emit(UIe.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(UIe.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(UIe.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&SB.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&SB.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let a of[...i])r&&a.filePath!==r||this.watcherClose(a);if(n)for(let a in this._watchers)SB.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let i in this._watchers)this.watchersClose(i,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,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let a=new aab(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 n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=SB.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(c=>c.handler===n&&(!c.filePath||c.filePath===i)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=gya.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??eLi))&&u.handler===n&&(!u.filePath||u.filePath===i)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&tLi&&u.options.native!==!1)))return!0;if(!tLi)break;let s=gya.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,n,i,a){if(this.isClosed())return;t=SB.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,n,i))try{let f=!r.recursive||tLi&&r.native!==!1?r:{...r,recursive:!1},u={watcher:S$s.default.watch(c,f),handler:n,options:r,folderPath:c,filePath:i},l=o=await this.watcherAdd(u,a);if(this._roots.has(i||c)){let A={...r,ignoreInitial:!0,recursive:!1},P=gya.default.dirname(c),C=c;await this.watchDirectories([P],A,n,C,l)}}catch(f){this.error(f)}return o}async watchDirectory(t,r,n,i,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||tLi&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,a));{r={...r,recursive:!0};let o=r.depth??eLi,c=r.limit??Tuu,[f]=await SB.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,n,i,a);if(f.length){let u=SB.fs.getDepth(t);for(let l of f){let m=SB.fs.getDepth(l),A=Math.max(0,o-(m-u)),P={...r,depth:A};await this.watchDirectories([l],P,n,i,a||s)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},a=(s,u)=>{u===t&&(f(),n())},o=new e(a),c=()=>{this._subwatchers.add(i),this.on(UIe.CLOSE,f),o.watchFile(t,r,a)},f=()=>{this._subwatchers.delete(i),this.removeListener(UIe.CLOSE,f),o.close()};return c()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=gya.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,a=new iZf,o=await this.watchPolling(t,r,async()=>{i||!(await a.update(t,r.pollingTimeout)).length||i||(i=!0,o(),n())})}async watchPolling(t,r,n){if(this.isClosed())return SB.lang.noop;if(this.pollerExists(t,r))return SB.lang.noop;let i={...r,interval:r.pollingInterval??Jib},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(UIe.CLOSE,c),S$s.default.watchFile(t,i,n)},c=()=>{this._pollers.delete(a),this.removeListener(UIe.CLOSE,c),S$s.default.unwatchFile(t,n)};return SB.lang.attempt(o),()=>SB.lang.attempt(c)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=SB.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,f)=>f===o||!SB.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,n)));else for(let a of t)await this.watchPath(a,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=gya.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await SB.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let a=gya.default.dirname(t);return(await SB.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=SB.lang.noop){if(SB.lang.isFunction(t))return this.watch([],{},t);if(SB.lang.isUndefined(t))return this.watch([],r,n);if(SB.lang.isFunction(r))return this.watch(t,{},r);if(SB.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=SB.lang.castArray(t);i.forEach(a=>this._roots.add(a)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==SB.lang.noop&&this.on(UIe.ALL,n),r.readdirMap=void 0,this.ready())}},D$s=aZf;TRs();var ulb=Gi(hYs(),1),HIe=require("fs/promises"),slb=require("os"),clb=Gi(TCe(),1),llb=Gi(olb(),1),BYs=process.platform==="win32",hLM="etag",yLM="preview",vLM="app-preview",bLM="bundle",gLM=".next",mLM="standalone",OLM=".fern",ALM="packages/fern-docs/bundle/.next/server/instrumentation.js",PLM=".npmrc",wLM=".pnpmfile.cjs",jLM="pnpm-workspace.yaml",ELM='Cannot find matching keyid: {"signatures":';function SLM(){return kl(L_.of((0,slb.homedir)()),ds.of(OLM))}function TYs({app:e=!1}){return kl(SLM(),ds.of(e?vLM:yLM))}function lLi({app:e=!1}){return kl(TYs({app:e}),ds.of(e?gLM:bLM))}function ssu({app:e=!1}){return kl(lLi({app:e}),ds.of(mLM))}function DLM({app:e=!1}){return kl(ssu({app:e}),ds.of(ALM))}function CLM({app:e=!1}){return kl(ssu({app:e}),ds.of(jLM))}function ILM({app:e=!1}){return kl(ssu({app:e}),ds.of(wLM))}function MLM({app:e=!1}){return kl(ssu({app:e}),ds.of(PLM))}function jya(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function BLM({app:e=!1}){return kl(TYs({app:e}),ds.of(hLM))}var TLM=`packages:
|
|
3015
3015
|
- "packages/**"
|
|
3016
3016
|
- "!**/dist"
|
|
3017
3017
|
`,qLM=`module.exports = {
|