fern-api 3.15.0 → 3.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +4 -4
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1147,7 +1147,7 @@ ${eUp.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&G6s(th
1147
1147
  `+B7i.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?B7i.default.cyan(cUp(t,this.opt.mask)):B7i.default.italic(B7i.default.dim("[hidden]")):this.opt.mask?cUp(t,this.opt.mask):B7i.default.italic(B7i.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 Wmo=ue(_1(),1);var c4p=ue(E9s(),1),Lmo=require("child_process"),$1n=require("fs"),Umo=ue(require("path"),1),l4p=ue(require("os"),1),f4p=require("crypto"),lGs=ue(u4p(),1);var Nmo=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var zga=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var Fmo=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var Qmo=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function Vmo(e="",t,r){let i=new fGs(e,r);i.runAsync((n,a)=>{if(n)setImmediate(t,n,void 0);else try{i.cleanup(),setImmediate(t,void 0,a)}catch(o){setImmediate(t,o,void 0)}})}function s4p(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function zvS(e){let t=[],r="";for(let i=0;i<e.length;i++){let n=e.charAt(i);i>0&&n===" "&&e[i-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${n}`}return r.length>0&&t.push(r),t}var fGs=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=zvS(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??l4p.default.tmpdir(),r=(0,f4p.randomUUID)(),i=s4p(this.fileOptions.prefix),n=s4p(this.fileOptions.postfix),a=`${i}${r}${n}`,o=Umo.default.resolve(t,a),c=Umo.default.resolve(t)+Umo.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,$1n.writeFileSync)(this.tempFile,this.text,f)}catch(t){throw new Nmo(t)}}readTemporaryFile(){try{let t=(0,$1n.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,c4p.detect)(t)??"utf8";lGs.default.encodingExists(r)||(r="utf8"),this.text=lGs.default.decode(t,r)}}catch(t){throw new Fmo(t)}}removeTemporaryFile(){try{(0,$1n.unlinkSync)(this.tempFile)}catch(t){throw new Qmo(t)}}launchEditor(){try{let t=(0,Lmo.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new zga(t)}}launchEditorAsync(t){try{(0,Lmo.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new zga(r)}}};var d4p=ue(Y_e(),1);var Nga=class extends h1{_run(t){this.done=t,this.editorResult=new d4p.Subject;let r=CQ(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let i=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,n=this.handleSubmitEvents(this.editorResult);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,i?this.render():this.startExternalEditor(),this}render(t){let r="",i=this.getQuestion();i+=this.status==="answered"?Wmo.default.dim("Received"):Wmo.default.dim("Press <enter> to launch your preferred editor."),t&&(r=Wmo.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),Vmo(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 b4p=require("stream");var h4p=ue(require("readline"),1),y4p=ue(_4p(),1),T7i=class{constructor(t){this.rl||=h4p.default.createInterface(FvS(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 FvS(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let n=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw n.isTtyError=!0,n}let r=new y4p.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var Fga=class extends T7i{constructor(t={}){super(t),this.log=new b4p.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return Aga(this.rl,this.bottomBar.split(`
1148
1148
  `).length),this}updateBottomBar(t){return Aga(this.rl,1),this.rl.output.unmute(),this.clean(),this.bottomBar=t,this.render(),this.rl.output.mute(),this}writeLog(t){return this.rl.output.unmute(),this.clean(),this.rl.output.write(this.enforceLF(t.toString())),this.render(),this.rl.output.mute(),this}enforceLF(t){return/[\n\r]$/.test(t)?t:t+`
1149
1149
  `}write(t){let r=t.split(/\n/);this.height=r.length,this.rl.setPrompt(r.at(-1)),this.rl.output.rows===0&&this.rl.output.columns===0&&fmo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var fO=ue(Y_e(),1),O4p=ue(Vva(),1);var xmo=ue(Y_e(),1),v4p=ue(Vva(),1),Gmo=function(e,t,r){return typeof e[t]!="function"?(0,xmo.of)(e):(0,xmo.from)((0,v4p.default)(e[t])(r).then(i=>(e[t]=i,e)))};var g4p={set:(e,t="",r)=>{let i=e;t.split(".").forEach((n,a,o)=>{n==="__proto__"||n==="constructor"||(a===o.length-1?i[n]=r:(!(n in i)||typeof i[n]!="object")&&(i[n]={}),i=i[n])})},get:(e,t="",r)=>{let i=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((o,c)=>o!=null?o[c]:o,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},Y1n=class extends T7i{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let i;return Array.isArray(t)?i=(0,fO.from)(t):(0,fO.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,fO.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,fO.from)([t]),this.process=i.pipe((0,fO.concatMap)(this.processQuestion.bind(this)),(0,fO.publish)()),this.process.connect(),this.process.pipe((0,fO.reduce)((n,a)=>(g4p.set(n,a.name,a.answer),n),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,fO.defer)(()=>(0,fO.of)(t).pipe((0,fO.concatMap)(this.setDefaultType.bind(this)),(0,fO.concatMap)(this.filterIfRunnable.bind(this)),(0,fO.concatMap)(()=>Gmo(t,"message",this.answers)),(0,fO.concatMap)(()=>Gmo(t,"default",this.answers)),(0,fO.concatMap)(()=>Gmo(t,"choices",this.answers)),(0,fO.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,fO.defer)(()=>(0,fO.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,fO.defer)(()=>(0,fO.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&g4p.get(this.answers,t.name)!==void 0)return fO.EMPTY;if(t.when===!1)return fO.EMPTY;if(typeof t.when!="function")return(0,fO.of)(t);let{answers:r}=this;return(0,fO.defer)(()=>(0,fO.from)((0,O4p.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,fO.filter)(i=>i!=null)))}};function A4p(e){let t=function(r,i){let n;try{n=new Y1n(t.prompts,e)}catch(o){return Promise.reject(o)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",Pga),this.registerPrompt("input",D7i),this.registerPrompt("number",jga),this.registerPrompt("confirm",wga),this.registerPrompt("rawlist",Ega),this.registerPrompt("expand",Sga),this.registerPrompt("checkbox",Mga),this.registerPrompt("password",Dga),this.registerPrompt("editor",Nga)},t.restoreDefaultPrompts(),t}var pGs=A4p();function UvS(e,t){pGs.registerPrompt(e,t)}function LvS(){pGs.restoreDefaultPrompts()}var VvS={prompt:pGs,ui:{BottomBar:Fga,Prompt:Y1n},createPromptModule:A4p,registerPrompt:UvS,restoreDefaultPrompts:LvS,Separator:PH},Hmo=VvS;var cTn=require("path"),e3p=require("fs"),t3p=require("readline"),wLp="posthog-node";function hAS(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"]}={}){return a=>{if(!(n==="*"||n.includes(a.level)))return a;a.tags||(a.tags={});let c=a.tags[d0o.POSTHOG_ID_TAG];if(c===void 0)return a;let f=e.options.host??"https://us.i.posthog.com",s=new URL(`/project/${e.apiKey}/person/${c}`,f).toString();a.tags["PostHog Person URL"]=s;let u=a.exception?.values||[],l=u.map(_=>({..._,stacktrace:_.stacktrace?{..._.stacktrace,type:"raw",frames:(_.stacktrace.frames||[]).map(h=>({...h,platform:"node:javascript"}))}:void 0})),p={$exception_message:u[0]?.value||a.message,$exception_type:u[0]?.type,$exception_personURL:s,$exception_level:a.level,$exception_list:l,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:u[0]?.value||a.message,$sentry_exception_type:u[0]?.type,$sentry_tags:a.tags};return t&&r&&(p.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),e.capture({event:"$exception",distinctId:c,properties:p}),a}}var d0o=class{constructor(t,r,i,n){this.name=wLp,this.name=wLp,this.setupOnce=function(a,o){let c=o()?.getClient()?.getDsn()?.projectId;a(hAS(t,{organization:r,projectId:c,prefix:i,severityAllowList:n}))}}};d0o.POSTHOG_ID_TAG="posthog_distinct_id";var u0o="0123456789abcdef",p0o=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=u0o.charAt(this.bytes[r]>>>4),t+=u0o.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+=u0o.charAt(this.bytes[r]>>>4),t+=u0o.charAt(this.bytes[r]&15);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},XGs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??yAS()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else if(t+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return p0o.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,p0o.ofInner(t)}},yAS=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),ELp,ZGs=()=>bAS().toString(),bAS=()=>(ELp||(ELp=new XGs)).generate();function vAS(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t())},{_posthogErrorHandler:!0})}function gAS(e,t){global.process.on("uncaughtException",vAS(e,t))}function OAS(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var s0o,SLp,c0o;function AAS(e){let t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};let r=Object.keys(t);return c0o&&r.length===SLp||(SLp=r.length,c0o=r.reduce((i,n)=>{s0o||(s0o={});let a=s0o[n];if(a)i[a[0]]=a[1];else{let o=e(n);for(let c=o.length-1;c>=0;c--){let s=o[c]?.filename,u=t[n];if(s&&u){i[s]=u,s0o[n]=[s,u];break}}}return i},{})),c0o}function mAS(e){return typeof Event<"u"&&r3p(e,Event)}function PAS(e){return i3p(e,"Object")}function o7s(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return r3p(e,Error)}}function r3p(e,t){try{return e instanceof t}catch{return!1}}function jAS(e){return i3p(e,"ErrorEvent")}function i3p(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function wAS(e,t,r,i){let a=i&&i.mechanism||{handled:!0,type:"generic"},o=n3p(a,r,i);return{$exception_list:await Promise.all(o.map(async s=>{let u=await CAS(e,t,s);return u.value=u.value||"",u.type=u.type||"Error",u.mechanism=a,u}))}}function n3p(e,t,r){let i=EAS(e,t,r);return i.cause?[i,...n3p(e,i.cause,r)]:[i]}function EAS(e,t,r){if(o7s(t))return t;if(e.synthetic=!0,PAS(t)){let n=SAS(t);if(n)return n;let a=MAS(t),o=r?.syntheticException||new Error(a);return o.message=a,o}let i=r?.syntheticException||new Error(t);return i.message=`${t}`,i}function SAS(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(o7s(r))return r}}function MAS(e){if("name"in e&&typeof e.name=="string"){let i=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(i+=` with message '${e.message}'`),i}else if("message"in e&&typeof e.message=="string")return e.message;let t=BAS(e);if(jAS(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;let r=DAS(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function DAS(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function BAS(e,t=40){let r=Object.keys(IAS(e));r.sort();let i=r[0];if(!i)return"[object has no keys]";if(i.length>=t)return MLp(i,t);for(let n=r.length;n>0;n--){let a=r.slice(0,n).join(", ");if(!(a.length>t))return n===r.length?a:MLp(a,t)}return""}function MLp(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function IAS(e){return o7s(e)?{message:e.message,name:e.name,stack:e.stack,...DLp(e)}:mAS(e)?{type:e.type,target:BLp(e.target),currentTarget:BLp(e.currentTarget),...DLp(e)}:e}function DLp(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 BLp(e){try{return Object.prototype.toString.call(e)}catch{return"<unknown>"}}async function CAS(e,t,r){let i={type:r.name||r.constructor.name,value:r.message},n=qAS(e,r);for(let a of t)n=await a(n);return n.length&&(i.stacktrace={frames:n,type:"raw"}),i}function qAS(e,t){return TAS(e(t.stack||"",1),e)}function TAS(e,t){let r=AAS(t);return e.forEach(i=>{i.filename&&(i.chunk_id=r[i.filename])}),e}var RAS=2e3,oTn=class e{static async captureException(t,r,i,n,a){let o={...a};n||(o.$process_person_profile=!1);let c=await wAS(this.stackParser,this.frameModifiers,r,i);t.capture({event:"$exception",distinctId:n||ZGs(),properties:{...c,...o}})}constructor(t,r){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(gAS(this.onException.bind(this),this.onFatalError.bind(this)),OAS(this.onException.bind(this)))}onException(t,r){e.captureException(this.client,t,r)}async onFatalError(){await this.client.shutdown(RAS)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}};function zAS(e=process.argv[1]?(0,cTn.dirname)(process.argv[1]):process.cwd(),t=cTn.sep==="\\"){let r=t?ILp(e):e;return i=>{if(!i)return;let n=t?ILp(i):i,{dir:a,base:o,ext:c}=cTn.posix.parse(n);(c===".js"||c===".mjs"||c===".cjs")&&(o=o.slice(0,c.length*-1));let f=decodeURIComponent(o);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${f}`;if(a.startsWith(r)){let u=a.slice(r.length+1).replace(/\//g,".");return u?`${u}:${f}`:f}return f}}function ILp(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var _0o=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)}}},f0o=new _0o(25),a3p=new _0o(20),u7s=7,NAS=1e3,FAS=1e4;async function QAS(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||WAS(o)||xAS(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(a3p.get(n))continue;let a=t[n];if(!a)continue;a.sort((f,s)=>f-s);let o=HAS(a);if(o.every(f=>GAS(n,f)))continue;let c=KAS(f0o,n,{});i.push(UAS(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&LAS(e,f0o),f0o.reduce(),e}function UAS(e,t,r){return new Promise(i=>{let n=(0,e3p.createReadStream)(e),a=(0,t3p.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,f=0,s=t[f];if(s===void 0){o();return}let u=s[0],l=s[1];function p(){a3p.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=JAS(_,0),c>=l)){if(f===t.length-1){a.close(),a.removeAllListeners();return}f++;let h=t[f];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],l=h[1]}})})}function LAS(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;VAS(r.lineno,r,i)}}function VAS(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=o3p(e);n<e;n++){let a=r[n];if(a===void 0){CLp(t);return}t.pre_context.push(a)}if(r[e]===void 0){CLp(t);return}t.context_line=r[e];let i=u3p(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function CLp(e){delete e.pre_context,delete e.context_line,delete e.post_context}function WAS(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function xAS(e){return e.lineno!==void 0&&e.lineno>FAS||e.colno!==void 0&&e.colno>NAS}function GAS(e,t){let r=f0o.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function HAS(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=qLp(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+u7s:(n.push(i),i=qLp(a)),t++}return n}function qLp(e){return[o3p(e),u3p(e)]}function o3p(e){return Math.max(1,e-u7s)}function u3p(e){return e+u7s}function KAS(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function JAS(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}var $AS="4.18.0",MH;(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"})(MH||(MH={}));var TLp;(function(e){e.Left="left",e.Right="right",e.Center="center"})(TLp||(TLp={}));var RLp;(function(e){e.Button="button",e.Tab="tab",e.Selector="selector"})(RLp||(RLp={}));var zLp;(function(e){e.Popover="popover",e.API="api",e.Widget="widget"})(zLp||(zLp={}));var NLp;(function(e){e.Html="html",e.Text="text"})(NLp||(NLp={}));var FLp;(function(e){e.Number="number",e.Emoji="emoji"})(FLp||(FLp={}));var QLp;(function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"})(QLp||(QLp={}));var ULp;(function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"})(ULp||(ULp={}));var LLp;(function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"})(LLp||(LLp={}));var VLp;(function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"})(VLp||(VLp={}));var YAS=e=>{if("flags"in e){let t=ZAS(e.flags),r=kAS(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}else{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,s3p(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,XAS(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function XAS(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 ZAS=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,s7s(r)]).filter(([,t])=>t!==void 0)),kAS=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map(r=>{let i=t[r].metadata?.payload;return[r,i?s3p(i):void 0]}))},s7s=e=>e===void 0?void 0:e.variant??e.enabled,s3p=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},emS=1,tmS=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"]),rmS="utf8";function imS(e,t){if(!e||typeof e!="string"||nmS(e))throw new Error(t)}function nmS(e){return e.trim().length===0}function amS(e){return e?.replace(/\/+$/,"")}async function omS(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function WLp(){return new Date().getTime()}function $Gs(){return new Date().toISOString()}function h0o(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function umS(){return typeof fetch<"u"?fetch:typeof globalThis.fetch<"u"?globalThis.fetch:void 0}function smS(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 cmS(e,t=0,r){let i=smS(e);return r?.has(i)?!1:parseInt(i,16)/4294967295<t}function xLp(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var Jga=String.fromCharCode,GLp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l0o={};function lmS(e,t){if(!l0o[e]){l0o[e]={};for(let r=0;r<e.length;r++)l0o[e][e.charAt(r)]=r}return l0o[e][t]}var nTn={compressToBase64:function(e){if(e==null)return"";let t=nTn._compress(e,6,function(r){return GLp.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:nTn._decompress(e.length,32,function(t){return lmS(GLp,e.charAt(t))})},compress:function(e){return nTn._compress(e,16,function(t){return Jga(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],o,c,f="",s="",u="",l=2,p=3,_=2,h=0,y=0,b;for(b=0;b<e.length;b+=1)if(f=e.charAt(b),Object.prototype.hasOwnProperty.call(i,f)||(i[f]=p++,n[f]=!0),s=u+f,Object.prototype.hasOwnProperty.call(i,s))u=s;else{if(Object.prototype.hasOwnProperty.call(n,u)){if(u.charCodeAt(0)<256){for(o=0;o<_;o++)h=h<<1,y==t-1?(y=0,a.push(r(h)),h=0):y++;for(c=u.charCodeAt(0),o=0;o<8;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1}else{for(c=1,o=0;o<_;o++)h=h<<1|c,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=0;for(c=u.charCodeAt(0),o=0;o<16;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1}l--,l==0&&(l=Math.pow(2,_),_++),delete n[u]}else for(c=i[u],o=0;o<_;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1;l--,l==0&&(l=Math.pow(2,_),_++),i[s]=p++,u=String(f)}if(u!==""){if(Object.prototype.hasOwnProperty.call(n,u)){if(u.charCodeAt(0)<256){for(o=0;o<_;o++)h=h<<1,y==t-1?(y=0,a.push(r(h)),h=0):y++;for(c=u.charCodeAt(0),o=0;o<8;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1}else{for(c=1,o=0;o<_;o++)h=h<<1|c,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=0;for(c=u.charCodeAt(0),o=0;o<16;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1}l--,l==0&&(l=Math.pow(2,_),_++),delete n[u]}else for(c=i[u],o=0;o<_;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1;l--,l==0&&(l=Math.pow(2,_),_++)}for(c=2,o=0;o<_;o++)h=h<<1|c&1,y==t-1?(y=0,a.push(r(h)),h=0):y++,c=c>>1;for(;;)if(h=h<<1,y==t-1){a.push(r(h));break}else y++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:nTn._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let i=[],n=[],a={val:r(0),position:t,index:1},o=4,c=4,f=3,s="",u,l,p,_,h,y,b;for(u=0;u<3;u+=1)i[u]=u;for(p=0,h=Math.pow(2,2),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;switch(p){case 0:for(p=0,h=Math.pow(2,8),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;b=Jga(p);break;case 1:for(p=0,h=Math.pow(2,16),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;b=Jga(p);break;case 2:return""}for(i[3]=b,l=b,n.push(b);;){if(a.index>e)return"";for(p=0,h=Math.pow(2,f),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;switch(b=p){case 0:for(p=0,h=Math.pow(2,8),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;i[c++]=Jga(p),b=c-1,o--;break;case 1:for(p=0,h=Math.pow(2,16),y=1;y!=h;)_=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),p|=(_>0?1:0)*y,y<<=1;i[c++]=Jga(p),b=c-1,o--;break;case 2:return n.join("")}if(o==0&&(o=Math.pow(2,f),f++),i[b])s=i[b];else if(b===c)s=l+l.charAt(0);else return null;n.push(s),i[c++]=l+s.charAt(0),o--,l=s,o==0&&(o=Math.pow(2,f),f++)}}},kGs=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}},uTn=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()}},$ga=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function HLp(e){if(e instanceof uTn){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 YGs(e){return typeof e=="object"&&(e instanceof uTn||e instanceof $ga)}function KLp(e){return typeof e=="object"&&e instanceof uTn&&e.status===413}var e7s;(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(e7s||(e7s={}));var t7s=class{constructor(t,r){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new kGs,this._isInitialized=!1,imS(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=amS(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:YGs},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(MH.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(MH.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(MH.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>console.log("PostHog Debug",i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=ZGs();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(t,r,i){let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",n,i)}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}async captureStatelessImmediate(t,r,i,n){let a=this.buildPayload({distinct_id:t,event:r,properties:i});await this.sendImmediate("capture",a,n)}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}async aliasStatelessImmediate(t,r,i,n){let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",a,n)}groupIdentifyStateless(t,r,i,n,a,o){this.wrap(()=>{let c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...o||{}}});this.enqueue("capture",c,n)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(n=>n.json()).catch(n=>{this.logMsgIfDebug(()=>console.error("Remote config could not be loaded",n)),this._events.emit("error",n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let c=cmS(this.apiKey,emS,tmS)?`${this.host}/flags/?v=2`:`${this.host}/decide/?v=4`,f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.logMsgIfDebug(()=>console.log("PostHog Debug","Decide URL",c)),this.fetchWithRetry(c,f,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(s=>s.json()).then(s=>YAS(s)).catch(s=>{this._events.emit("error",s)})}async getFeatureFlagStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,i,n,a,o);if(c===void 0)return{response:void 0,requestId:void 0};let f=s7s(c.response);return f===void 0&&(f=!1),{response:f,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,i,n,a,o,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,i,n,a,o,[t]);if(!c)return;let f=c[t];return f===void 0?null:f}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)).payloads}async getFeatureFlagsStateless(t,r={},i={},n={},a,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,o);return c?{flags:c.featureFlags,payloads:c.featureFlagPayloads,requestId:c.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c={};(a??this.disableGeoip)&&(c.geoip_disable=!0),o&&(c.flag_keys_to_evaluate=o);let f=await this.getDecide(t,r,i,n,c);if(f!==void 0)return f.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),f.quotaLimited?.includes(e7s.FeatureFlags)?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:f?.requestId}):f}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this.logMsgIfDebug(()=>console.log("PostHog Debug","Loading surveys is disabled.")),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},n=(await this.fetchWithRetry(t,r).then(a=>{if(a.status!==200||!a.json){let o=`Surveys API could not be loaded: ${a.status}`,c=new Error(o);this.logMsgIfDebug(()=>console.error(c)),this._events.emit("error",new Error(o));return}return a.json()}).catch(a=>{this.logMsgIfDebug(()=>console.error("Surveys API could not be loaded",a)),this._events.emit("error",a)}))?.surveys;return n&&this.logMsgIfDebug(()=>console.log("PostHog Debug","Surveys fetched from API: ",JSON.stringify(n))),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(MH.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(MH.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(MH.Props,this.props)})}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n=this.prepareMessage(t,r,i),a=this.getPersistedProperty(MH.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),a.push({message:n}),this.setPersistedProperty(MH.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=h0o(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,i){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized||await this._initPromise,this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n={api_key:this.apiKey,batch:[this.prepareMessage(t,r,i)],sent_at:$Gs()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),o=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${WLp()}&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(nTn.compressToBase64(a))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:a};try{await this.fetchWithRetry(o,c)}catch(f){this._events.emit("error",f)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:$Gs(),uuid:i?.uuid?i.uuid:ZGs()};return(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await HLp(t)})}async flush(){let t=xLp([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),xLp([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(MH.Queue)||[];if(!t.length)return;let r=[],i=t.length;for(;t.length>0&&r.length<i;){let n=t.slice(0,this.maxBatchSize),a=n.map(p=>p.message),o=()=>{let _=(this.getPersistedProperty(MH.Queue)||[]).slice(n.length);this.setPersistedProperty(MH.Queue,_),t=_},c={api_key:this.apiKey,batch:a,sent_at:$Gs()};this.historicalMigration&&(c.historical_migration=!0);let f=JSON.stringify(c),s=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${WLp()}&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(nTn.compressToBase64(f))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:f},l={retryCheck:p=>KLp(p)?!1:YGs(p)};try{await this.fetchWithRetry(s,u,l)}catch(p){if(KLp(p)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this.logMsgIfDebug(()=>console.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`));continue}throw p instanceof $ga||o(),this._events.emit("error",p),p}o(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){var a;(a=AbortSignal).timeout??(a.timeout=function(s){let u=new AbortController;return setTimeout(()=>u.abort(),s),u.signal});let o=r.body?r.body:"",c=-1;try{c=Buffer.byteLength(o,rmS)}catch{c=new TextEncoder().encode(o).length}return await omS(async()=>{let f=null;try{f=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(u){throw new $ga(u)}if(!(r.mode==="no-cors")&&(f.status<200||f.status>=400))throw new uTn(f,c);return f},{...this._retryOptions,...i})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await Promise.all(Object.values(this.pendingPromises));!((this.getPersistedProperty(MH.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!YGs(n))throw n;await HLp(n)}};return Promise.race([new Promise((n,a)=>{h0o(()=>{this.logMsgIfDebug(()=>console.error("Timed out while shutting down PostHog")),r=!0,a("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),i()])}async shutdown(t=3e4){return this.shutdownPromise?this.logMsgIfDebug(()=>console.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup")):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}},r7s=umS();if(!r7s){let e=jLp();r7s=async(t,r)=>{let i=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:i.status,text:async()=>i.data,json:async()=>i.data}}}var c3p=r7s,y0o=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()}},l3p=new y0o(async()=>{try{return await import("crypto")}catch{return}});async function fmS(){return await l3p.getValue()}var dmS=new y0o(async()=>{if(typeof globalThis.crypto?.subtle<"u")return globalThis.crypto.subtle;try{let e=await l3p.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function pmS(){return await dmS.getValue()}async function _mS(e){let t=await fmS();if(t)return t.createHash("sha1").update(e).digest("hex");let r=await pmS();if(r){let i=await r.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}throw new Error("No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API")}var hmS=60*1e3,ymS=1152921504606847e3,bmS=["is_not"],aTn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},y1=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},i7s=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:o,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||c3p,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;for(let f of this.featureFlags)if(t===f.key){c=f;break}if(c!==void 0)try{o=await this.computeFlagLocally(c,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(f){f instanceof y1?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${f}`)):f instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${f}`))}return o}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},o={},c=this.featureFlags.length==0;return await Promise.all(this.featureFlags.map(async f=>{try{let s=await this.computeFlagLocally(f,t,r,i,n);a[f.key]=s;let u=await this.computeFeatureFlagPayloadLocally(f.key,s);u&&(o[f.key]=u)}catch(s){s instanceof y1||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${s}`)),c=!0}})),{response:a,payloads:o,fallbackToDecide:c}}async computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new y1("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 y1("Flag has unknown group type index");if(!(f in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[f];return await this.matchFeatureFlagProperties(t,i[f],s)}else return await this.matchFeatureFlagProperties(t,r,n)}async matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],o=!1,c,f=[...a].sort((s,u)=>{let l=!!s.variant,p=!!u.variant;return l&&p?0:l?-1:p?1:0});for(let s of f)try{if(await this.isConditionMatch(t,r,s,i)){let u=s.variant,l=n.multivariate?.variants||[];u&&l.some(p=>p.key===u)?c=u:c=await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof y1)o=!0;else throw u}if(c!==void 0)return c;if(o)throw new y1("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n){let a=i.rollout_percentage,o=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((i.properties||[]).length>0){for(let c of i.properties){let f=c.type,s=!1;if(f==="cohort"?s=d3p(c,n,this.cohorts,this.debugMode):s=f3p(c,n,o),!s)return!1}if(a==null)return!0}return!(a!=null&&await JLp(t.key,r)>a/100)}async getMatchingVariant(t,r){let i=await JLp(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(hmS,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 aTn(`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 aTn(`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 aTn(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r)){this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));return}this.featureFlags=r.flags??[],this.featureFlagsByKey=this.featureFlags.reduce((i,n)=>(i[n.key]=n,i),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||{},this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof aTn&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET"){return{method:t,headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions(),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=h0o(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}_requestRemoteConfigPayload(t){let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config/`,i=this.getPersonalApiKeyRequestOptions(),n=null;if(this.timeout&&typeof this.timeout=="number"){let a=new AbortController;n=h0o(()=>{a.abort()},this.timeout),i.signal=a.signal}try{return this.fetch(r,i)}finally{clearTimeout(n)}}};async function JLp(e,t,r=""){let i=await _mS(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/ymS}function f3p(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new y1("Operator is_not_set is not supported")}else throw new y1(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!bmS.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(l=>String(l).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function f(s,u,l){if(l==="gt")return s>u;if(l==="gte")return s>=u;if(l==="lt")return s<u;if(l==="lte")return s<=u;throw new Error(`Invalid operator: ${l}`)}switch(a){case"exact":return c(n,o);case"is_not":return!c(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return $Lp(String(n))&&String(o).match(String(n))!==null;case"not_regex":return $Lp(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&o!=null?typeof o=="string"?f(o,String(n),a):f(o,s,a):f(String(o),String(n),a)}case"is_date_after":case"is_date_before":{let s=vmS(String(n));if(s==null&&(s=YLp(n)),s==null)throw new y1(`Invalid date: ${n}`);let u=YLp(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new y1(`Unknown operator: ${a}`)}}function d3p(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new y1("can't match cohort without a given cohort property value");let a=r[n];return p3p(a,t,r,i)}function p3p(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let f=p3p(c,t,r,i);if(n==="AND"){if(!f)return!1}else if(f)return!0}catch(f){if(f instanceof y1)i&&console.debug(`Failed to compute property ${c} locally: ${f}`),o=!0;else throw f}if(o)throw new y1("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let c of a)try{let f;c.type==="cohort"?f=d3p(c,t,r,i):f=f3p(c,t);let s=c.negation||!1;if(n==="AND"){if(!f&&!s||f&&s)return!1}else if(f&&!s||!f&&s)return!0}catch(f){if(f instanceof y1)i&&console.debug(`Failed to compute property ${c} locally: ${f}`),o=!0;else throw f}if(o)throw new y1("can't match cohort without a given cohort property value");return n==="AND"}}function $Lp(e){try{return new RegExp(e),!0}catch{return!1}}function YLp(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 y1(`${e} is in an invalid date format`)}else throw new y1(`The date provided ${e} must be a string, number, or date object`)}function vmS(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-n*7);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else if(a=="y")i.setUTCFullYear(i.getUTCFullYear()-n);else return null;return i}else return null}var n7s=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},gmS=100,XLp=30*1e3,OmS=50*1e3,a7s=class extends t7s{constructor(t,r={}){if(super(t,r),this._memoryStorage=new n7s,this.options=r,this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,gmS):XLp,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 i7s({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders()})}this.errorTracking=new oTn(this,r),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||OmS}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):c3p(t,r)}getLibraryVersion(){return $AS}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:f,uuid:s}=t,u=_=>{super.captureStateless(r,i,_,{timestamp:c,disableGeoip:f,uuid:s})},l=async(_,h,y)=>(await super.getFeatureFlagsStateless(_,h,void 0,void 0,y)).flags,p=Promise.resolve().then(async()=>{if(o)return await l(r,a,f);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let _={};for(let[h,y]of Object.entries(a||{}))_[h]=String(y);return await this.getAllFlags(r,{groups:_,disableGeoip:f,onlyEvaluateLocally:!0})}return{}}).then(_=>{let h={};if(_)for(let[b,v]of Object.entries(_))h[`$feature/${b}`]=v;let y=Object.keys(_||{}).filter(b=>_?.[b]!==!1).sort();return y.length>0&&(h.$active_feature_flags=y),h}).catch(()=>({})).then(_=>{u({..._,...n,$groups:a})});this.addPendingPromise(p)}async captureImmediate(t){typeof t=="string"&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:f,uuid:s}=t,u=_=>super.captureStatelessImmediate(r,i,_,{timestamp:c,disableGeoip:f,uuid:s}),l=async(_,h,y)=>(await super.getFeatureFlagsStateless(_,h,void 0,void 0,y)).flags;await Promise.resolve().then(async()=>{if(o)return await l(r,a,f);if(i==="$feature_flag_called")return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let _={};for(let[h,y]of Object.entries(a||{}))_[h]=String(y);return await this.getAllFlags(r,{groups:_,disableGeoip:f,onlyEvaluateLocally:!0})}return{}}).then(_=>{let h={};if(_)for(let[b,v]of Object.entries(_))h[`$feature/${b}`]=v;let y=Object.keys(_||{}).filter(b=>_?.[b]!==!1).sort();return y.length>0&&(h.$active_feature_flags=y),h}).catch(()=>({})).then(_=>{u({..._,...n,$groups:a})})}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;super.identifyStateless(t,{$set:a,$set_once:n},{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set_once;delete r?.$set_once;let a=r?.$set||r;await super.identifyStatelessImmediate(t,{$set:a,$set_once:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=XLp){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:o,sendFeatureFlagEvents:c,personProperties:f,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,f,s);f=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,f,s),p=l!==void 0,_,h;if(!p&&!o){let b=await super.getFeatureFlagDetailStateless(t,r,n,f,s,a);if(b===void 0)return;h=b.response,l=s7s(h),_=b?.requestId}let y=`${t}_${l}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(y))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(y):this.distinctIdHasSentFlagCalls[r]=[y],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,$feature_flag_id:h?.metadata?.id,$feature_flag_version:h?.metadata?.version,$feature_flag_reason:h?.reason?.description??h?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:l,$feature_flag_request_id:_},groups:n,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,sendFeatureFlagEvents:f,personProperties:s,groupProperties:u}=n||{},l=this.addLocalPersonAndGroupProperties(r,a,s,u);s=l.allPersonProperties,u=l.allGroupProperties;let p;return this.featureFlagsPoller!==void 0&&(i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0,sendFeatureFlagEvents:!1})),i&&(p=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i))),c==null&&(c=!1),f==null&&(f=!0),c==null&&(c=!1),!(p!==void 0)&&!c&&(p=await super.getFeatureFlagPayloadStateless(t,r,a,s,u,o)),p}async getRemoteConfigPayload(t){return(await this.featureFlagsPoller?._requestRemoteConfigPayload(t))?.json()}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n}=r||{},{onlyEvaluateLocally:a,personProperties:o,groupProperties:c}=r||{},f=this.addLocalPersonAndGroupProperties(t,i,o,c);o=f.allPersonProperties,c=f.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,o,c),u={},l={},p=!0;if(s&&(u=s.response,l=s.payloads,p=s.fallbackToDecide),p&&!a){let _=await super.getFeatureFlagsAndPayloadsStateless(t,i,o,c,n);u={...u,..._.flags||{}},l={...l,..._.payloads||{}}}return{featureFlags:u,featureFlagPayloads:l}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(),super._shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,i){let n=new Error("PostHog syntheticException");oTn.captureException(this,t,{syntheticException:n},r,i)}},ZLp=/\(error: (.*)\)/,_3p=50,h3p="?";function AmS(e){let t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return i=>{let n=i.match(r);if(n){let a,o,c,f,s;if(n[1]){c=n[1];let p=c.lastIndexOf(".");if(c[p-1]==="."&&p--,p>0){a=c.slice(0,p),o=c.slice(p+1);let _=a.indexOf(".Module");_>0&&(c=c.slice(_+1),a=a.slice(0,_))}f=void 0}o&&(f=a,s=o),o==="<anonymous>"&&(s=void 0,c=void 0),c===void 0&&(s=s||h3p,c=f?`${f}.${s}`:s);let u=n[2]?.startsWith("file://")?n[2].slice(7):n[2],l=n[5]==="native";return u?.match(/\/[A-Z]:/)&&(u=u.slice(1)),!u&&n[5]&&!l&&(u=n[5]),{filename:u?decodeURI(u):void 0,module:e?e(u):void 0,function:c,lineno:kLp(n[3]),colno:kLp(n[4]),in_app:mmS(u||"",l),platform:"node:javascript"}}if(i.match(t))return{filename:i,platform:"node:javascript"}}}function mmS(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 kLp(e){return parseInt(e||"",10)||void 0}function PmS(e){return[90,AmS(e)]}function jmS(e){let r=[PmS(e)].sort((i,n)=>i[0]-n[0]).map(i=>i[1]);return(i,n=0)=>{let a=[],o=i.split(`
1150
- `);for(let c=n;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let s=ZLp.test(f)?f.replace(ZLp,"$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>=_3p)break}}return wmS(a)}}function wmS(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,_3p).map(r=>({...r,filename:r.filename||EmS(t).filename,function:r.function||h3p}))}function EmS(e){return e[e.length-1]||{}}oTn.stackParser=jmS(zAS());oTn.frameModifiers=[QAS];var sTn=class extends a7s{getLibraryId(){return"posthog-node"}};var b0o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new sTn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.15.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var Yga=class{async sendEvent(){}async identify(){}async flush(){}};var lTn=require("fs/promises"),g3p=require("os"),O3p=require("path");var y3p=ue(require("crypto")),g0o=new Uint8Array(256),v0o=g0o.length;function c7s(){return v0o>g0o.length-16&&(y3p.default.randomFillSync(g0o),v0o=0),g0o.slice(v0o,v0o+=16)}var TQ=[];for(let e=0;e<256;++e)TQ.push((e+256).toString(16).slice(1));function b3p(e,t=0){return TQ[e[t+0]]+TQ[e[t+1]]+TQ[e[t+2]]+TQ[e[t+3]]+"-"+TQ[e[t+4]]+TQ[e[t+5]]+"-"+TQ[e[t+6]]+TQ[e[t+7]]+"-"+TQ[e[t+8]]+TQ[e[t+9]]+"-"+TQ[e[t+10]]+TQ[e[t+11]]+TQ[e[t+12]]+TQ[e[t+13]]+TQ[e[t+14]]+TQ[e[t+15]]}var v3p=ue(require("crypto")),l7s={randomUUID:v3p.default.randomUUID};function SmS(e,t,r){if(l7s.randomUUID&&!t&&!e)return l7s.randomUUID();e=e||{};let i=e.random||(e.rng||c7s)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return b3p(i)}var Z_e=SmS;var MmS="id",DmS=".fern",Xga=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new sTn(r),this.userId=t==null?void 0:I8s(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:"3.15.0",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Nt(Fr.of((0,g3p.homedir)()),Ze.of(DmS),Ze.of(MmS));await qi(t)||(await(0,lTn.mkdir)((0,O3p.dirname)(t),{recursive:!0}),await(0,lTn.writeFile)(t,Z_e())),this.persistedDistinctId=(await(0,lTn.readFile)(t)).toString()}return this.persistedDistinctId}};var f7s;async function fTn(){return f7s==null&&(f7s=await BmS()),f7s}async function BmS(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new Yga;let r=await zyo();return r!=null?new Xga({token:r,posthogApiKey:e}):await _qn()!=null?new b0o({posthogApiKey:e}):new Xga({token:void 0,posthogApiKey:e})}catch{return new Yga}}function Zga(e,t){return function(){return e.apply(t,arguments)}}var{toString:ImS}=Object.prototype,{getPrototypeOf:p7s}=Object,{iterator:A0o,toStringTag:m3p}=Symbol,m0o=(e=>t=>{let r=ImS.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),RNt=e=>(e=e.toLowerCase(),t=>m0o(t)===e),P0o=e=>t=>typeof t===e,{isArray:pTn}=Array,dTn=P0o("undefined");function kga(e){return e!==null&&!dTn(e)&&e.constructor!==null&&!dTn(e.constructor)&&DH(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var P3p=RNt("ArrayBuffer");function CmS(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&P3p(e.buffer),t}var qmS=P0o("string"),DH=P0o("function"),j3p=P0o("number"),eOa=e=>e!==null&&typeof e=="object",TmS=e=>e===!0||e===!1,O0o=e=>{if(m0o(e)!=="object")return!1;let t=p7s(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(m3p in e)&&!(A0o in e)},RmS=e=>{if(!eOa(e)||kga(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},zmS=RNt("Date"),NmS=RNt("File"),FmS=RNt("Blob"),QmS=RNt("FileList"),UmS=e=>eOa(e)&&DH(e.pipe),LmS=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||DH(e.append)&&((t=m0o(e))==="formdata"||t==="object"&&DH(e.toString)&&e.toString()==="[object FormData]"))},VmS=RNt("URLSearchParams"),[WmS,xmS,GmS,HmS]=["ReadableStream","Request","Response","Headers"].map(RNt),KmS=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function tOa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),pTn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(kga(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(i=0;i<o;i++)c=a[i],t.call(null,e[c],c,e)}}function w3p(e,t){if(kga(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var U7i=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,E3p=e=>!dTn(e)&&e!==U7i;function d7s(){let{caseless:e,skipUndefined:t}=E3p(this)&&this||{},r={},i=(n,a)=>{let o=e&&w3p(r,a)||a;O0o(r[o])&&O0o(n)?r[o]=d7s(r[o],n):O0o(n)?r[o]=d7s({},n):pTn(n)?r[o]=n.slice():(!t||!dTn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&tOa(arguments[n],i);return r}var JmS=(e,t,r,{allOwnKeys:i}={})=>(tOa(t,(n,a)=>{r&&DH(n)?e[a]=Zga(n,r):e[a]=n},{allOwnKeys:i}),e),$mS=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),YmS=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},XmS=(e,t,r,i)=>{let n,a,o,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)o=n[a],(!i||i(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&p7s(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},ZmS=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},kmS=e=>{if(!e)return null;if(pTn(e))return e;let t=e.length;if(!j3p(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},e0S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&p7s(Uint8Array)),t0S=(e,t)=>{let i=(e&&e[A0o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},r0S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},i0S=RNt("HTMLFormElement"),n0S=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),A3p=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),a0S=RNt("RegExp"),S3p=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};tOa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},o0S=e=>{S3p(e,(t,r)=>{if(DH(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(DH(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},u0S=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return pTn(e)?i(e):i(String(e).split(t)),r},s0S=()=>{},c0S=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function l0S(e){return!!(e&&DH(e.append)&&e[m3p]==="FormData"&&e[A0o])}var f0S=e=>{let t=new Array(10),r=(i,n)=>{if(eOa(i)){if(t.indexOf(i)>=0)return;if(kga(i))return i;if(!("toJSON"in i)){t[n]=i;let a=pTn(i)?[]:{};return tOa(i,(o,c)=>{let f=r(o,n+1);!dTn(f)&&(a[c]=f)}),t[n]=void 0,a}}return i};return r(e,0)},d0S=RNt("AsyncFunction"),p0S=e=>e&&(eOa(e)||DH(e))&&DH(e.then)&&DH(e.catch),M3p=((e,t)=>e?setImmediate:t?((r,i)=>(U7i.addEventListener("message",({source:n,data:a})=>{n===U7i&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),U7i.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",DH(U7i.postMessage)),_0S=typeof queueMicrotask<"u"?queueMicrotask.bind(U7i):typeof process<"u"&&process.nextTick||M3p,h0S=e=>e!=null&&DH(e[A0o]),er={isArray:pTn,isArrayBuffer:P3p,isBuffer:kga,isFormData:LmS,isArrayBufferView:CmS,isString:qmS,isNumber:j3p,isBoolean:TmS,isObject:eOa,isPlainObject:O0o,isEmptyObject:RmS,isReadableStream:WmS,isRequest:xmS,isResponse:GmS,isHeaders:HmS,isUndefined:dTn,isDate:zmS,isFile:NmS,isBlob:FmS,isRegExp:a0S,isFunction:DH,isStream:UmS,isURLSearchParams:VmS,isTypedArray:e0S,isFileList:QmS,forEach:tOa,merge:d7s,extend:JmS,trim:KmS,stripBOM:$mS,inherits:YmS,toFlatObject:XmS,kindOf:m0o,kindOfTest:RNt,endsWith:ZmS,toArray:kmS,forEachEntry:t0S,matchAll:r0S,isHTMLForm:i0S,hasOwnProperty:A3p,hasOwnProp:A3p,reduceDescriptors:S3p,freezeMethods:o0S,toObjectSet:u0S,toCamelCase:n0S,noop:s0S,toFiniteNumber:c0S,findKey:w3p,global:U7i,isContextDefined:E3p,isSpecCompliantForm:l0S,toJSONObject:f0S,isAsyncFn:d0S,isThenable:p0S,setImmediate:M3p,asap:_0S,isIterable:h0S};function _Tn(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}er.inherits(_Tn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:er.toJSONObject(this.config),code:this.code,status:this.status}}});var D3p=_Tn.prototype,B3p={};["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=>{B3p[e]={value:e}});Object.defineProperties(_Tn,B3p);Object.defineProperty(D3p,"isAxiosError",{value:!0});_Tn.from=(e,t,r,i,n,a)=>{let o=Object.create(D3p);er.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",f=t==null&&e?e.code:t;return _Tn.call(o,c,f,r,i,n),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var ha=_Tn;var I3p=ue(jGi(),1),j0o=I3p.default;function _7s(e){return er.isPlainObject(e)||er.isArray(e)}function q3p(e){return er.endsWith(e,"[]")?e.slice(0,-2):e}function C3p(e,t,r){return e?e.concat(t).map(function(n,a){return n=q3p(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function y0S(e){return er.isArray(e)&&!e.some(_7s)}var b0S=er.toFlatObject(er,{},null,function(t){return/^is[A-Z]/.test(t)});function v0S(e,t,r){if(!er.isObject(e))throw new TypeError("target must be an object");t=t||new(j0o||FormData),r=er.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!er.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&er.isSpecCompliantForm(t);if(!er.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(er.isDate(h))return h.toISOString();if(er.isBoolean(h))return h.toString();if(!f&&er.isBlob(h))throw new ha("Blob is not supported. Use a Buffer instead.");return er.isArrayBuffer(h)||er.isTypedArray(h)?f&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,b){let v=h;if(h&&!b&&typeof h=="object"){if(er.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(er.isArray(h)&&y0S(h)||(er.isFileList(h)||er.endsWith(y,"[]"))&&(v=er.toArray(h)))return y=q3p(y),v.forEach(function(A,g){!(er.isUndefined(A)||A===null)&&t.append(o===!0?C3p([y],g,a):o===null?y:y+"[]",s(A))}),!1}return _7s(h)?!0:(t.append(C3p(b,y,a),s(h)),!1)}let l=[],p=Object.assign(b0S,{defaultVisitor:u,convertValue:s,isVisitable:_7s});function _(h,y){if(!er.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),er.forEach(h,function(v,O){(!(er.isUndefined(v)||v===null)&&n.call(t,v,er.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),l.pop()}}if(!er.isObject(e))throw new TypeError("data must be an object");return _(e),t}var IBi=v0S;function T3p(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function R3p(e,t){this._pairs=[],e&&IBi(e,this,t)}var z3p=R3p.prototype;z3p.append=function(t,r){this._pairs.push([t,r])};z3p.toString=function(t){let r=t?function(i){return t.call(this,i,T3p)}:T3p;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var N3p=R3p;function g0S(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function L7i(e,t,r){if(!t)return e;let i=r&&r.encode||g0S;er.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=er.isURLSearchParams(t)?t.toString():new N3p(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var h7s=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){er.forEach(this.handlers,function(i){i!==null&&t(i)})}},y7s=h7s;var hTn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var L3p=ue(require("crypto"),1);var F3p=ue(require("url"),1),Q3p=F3p.default.URLSearchParams;var b7s="abcdefghijklmnopqrstuvwxyz",U3p="0123456789",V3p={DIGIT:U3p,ALPHA:b7s,ALPHA_DIGIT:b7s+b7s.toUpperCase()+U3p},O0S=(e=16,t=V3p.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);L3p.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},W3p={isNode:!0,classes:{URLSearchParams:Q3p,FormData:j0o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:V3p,generateString:O0S,protocols:["http","https","file","data"]};var O7s={};Yt(O7s,{hasBrowserEnv:()=>g7s,hasStandardBrowserEnv:()=>A0S,hasStandardBrowserWebWorkerEnv:()=>m0S,navigator:()=>v7s,origin:()=>P0S});var g7s=typeof window<"u"&&typeof document<"u",v7s=typeof navigator=="object"&&navigator||void 0,A0S=g7s&&(!v7s||["ReactNative","NativeScript","NS"].indexOf(v7s.product)<0),m0S=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",P0S=g7s&&window.location.href||"http://localhost";var OA={...O7s,...W3p};function A7s(e,t){return IBi(e,new OA.classes.URLSearchParams,{visitor:function(r,i,n,a){return OA.isNode&&er.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function j0S(e){return er.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function w0S(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function E0S(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),f=a>=r.length;return o=!o&&er.isArray(n)?n.length:o,f?(er.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!er.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&er.isArray(n[o])&&(n[o]=w0S(n[o])),!c)}if(er.isFormData(e)&&er.isFunction(e.entries)){let r={};return er.forEachEntry(e,(i,n)=>{t(j0S(i),n,r,0)}),r}return null}var w0o=E0S;function S0S(e,t,r){if(er.isString(e))try{return(t||JSON.parse)(e),er.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var m7s={transitional:hTn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=er.isObject(t);if(a&&er.isHTMLForm(t)&&(t=new FormData(t)),er.isFormData(t))return n?JSON.stringify(w0o(t)):t;if(er.isArrayBuffer(t)||er.isBuffer(t)||er.isStream(t)||er.isFile(t)||er.isBlob(t)||er.isReadableStream(t))return t;if(er.isArrayBufferView(t))return t.buffer;if(er.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return A7s(t,this.formSerializer).toString();if((c=er.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return IBi(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),S0S(t)):t}],transformResponse:[function(t){let r=this.transitional||m7s.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(er.isResponse(t)||er.isReadableStream(t))return t;if(t&&er.isString(t)&&(i&&!this.responseType||n)){let o=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?ha.from(c,ha.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:OA.classes.FormData,Blob:OA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};er.forEach(["delete","get","head","post","put","patch"],e=>{m7s.headers[e]={}});var yTn=m7s;var M0S=er.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),x3p=e=>{let t={},r,i,n;return e&&e.split(`
1150
+ `);for(let c=n;c<o.length;c++){let f=o[c];if(f.length>1024)continue;let s=ZLp.test(f)?f.replace(ZLp,"$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>=_3p)break}}return wmS(a)}}function wmS(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,_3p).map(r=>({...r,filename:r.filename||EmS(t).filename,function:r.function||h3p}))}function EmS(e){return e[e.length-1]||{}}oTn.stackParser=jmS(zAS());oTn.frameModifiers=[QAS];var sTn=class extends a7s{getLibraryId(){return"posthog-node"}};var b0o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new sTn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.15.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var Yga=class{async sendEvent(){}async identify(){}async flush(){}};var lTn=require("fs/promises"),g3p=require("os"),O3p=require("path");var y3p=ue(require("crypto")),g0o=new Uint8Array(256),v0o=g0o.length;function c7s(){return v0o>g0o.length-16&&(y3p.default.randomFillSync(g0o),v0o=0),g0o.slice(v0o,v0o+=16)}var TQ=[];for(let e=0;e<256;++e)TQ.push((e+256).toString(16).slice(1));function b3p(e,t=0){return TQ[e[t+0]]+TQ[e[t+1]]+TQ[e[t+2]]+TQ[e[t+3]]+"-"+TQ[e[t+4]]+TQ[e[t+5]]+"-"+TQ[e[t+6]]+TQ[e[t+7]]+"-"+TQ[e[t+8]]+TQ[e[t+9]]+"-"+TQ[e[t+10]]+TQ[e[t+11]]+TQ[e[t+12]]+TQ[e[t+13]]+TQ[e[t+14]]+TQ[e[t+15]]}var v3p=ue(require("crypto")),l7s={randomUUID:v3p.default.randomUUID};function SmS(e,t,r){if(l7s.randomUUID&&!t&&!e)return l7s.randomUUID();e=e||{};let i=e.random||(e.rng||c7s)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return b3p(i)}var Z_e=SmS;var MmS="id",DmS=".fern",Xga=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new sTn(r),this.userId=t==null?void 0:I8s(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:"3.15.1",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Nt(Fr.of((0,g3p.homedir)()),Ze.of(DmS),Ze.of(MmS));await qi(t)||(await(0,lTn.mkdir)((0,O3p.dirname)(t),{recursive:!0}),await(0,lTn.writeFile)(t,Z_e())),this.persistedDistinctId=(await(0,lTn.readFile)(t)).toString()}return this.persistedDistinctId}};var f7s;async function fTn(){return f7s==null&&(f7s=await BmS()),f7s}async function BmS(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new Yga;let r=await zyo();return r!=null?new Xga({token:r,posthogApiKey:e}):await _qn()!=null?new b0o({posthogApiKey:e}):new Xga({token:void 0,posthogApiKey:e})}catch{return new Yga}}function Zga(e,t){return function(){return e.apply(t,arguments)}}var{toString:ImS}=Object.prototype,{getPrototypeOf:p7s}=Object,{iterator:A0o,toStringTag:m3p}=Symbol,m0o=(e=>t=>{let r=ImS.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),RNt=e=>(e=e.toLowerCase(),t=>m0o(t)===e),P0o=e=>t=>typeof t===e,{isArray:pTn}=Array,dTn=P0o("undefined");function kga(e){return e!==null&&!dTn(e)&&e.constructor!==null&&!dTn(e.constructor)&&DH(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var P3p=RNt("ArrayBuffer");function CmS(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&P3p(e.buffer),t}var qmS=P0o("string"),DH=P0o("function"),j3p=P0o("number"),eOa=e=>e!==null&&typeof e=="object",TmS=e=>e===!0||e===!1,O0o=e=>{if(m0o(e)!=="object")return!1;let t=p7s(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(m3p in e)&&!(A0o in e)},RmS=e=>{if(!eOa(e)||kga(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},zmS=RNt("Date"),NmS=RNt("File"),FmS=RNt("Blob"),QmS=RNt("FileList"),UmS=e=>eOa(e)&&DH(e.pipe),LmS=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||DH(e.append)&&((t=m0o(e))==="formdata"||t==="object"&&DH(e.toString)&&e.toString()==="[object FormData]"))},VmS=RNt("URLSearchParams"),[WmS,xmS,GmS,HmS]=["ReadableStream","Request","Response","Headers"].map(RNt),KmS=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function tOa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),pTn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(kga(e))return;let a=r?Object.getOwnPropertyNames(e):Object.keys(e),o=a.length,c;for(i=0;i<o;i++)c=a[i],t.call(null,e[c],c,e)}}function w3p(e,t){if(kga(e))return null;t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var U7i=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,E3p=e=>!dTn(e)&&e!==U7i;function d7s(){let{caseless:e,skipUndefined:t}=E3p(this)&&this||{},r={},i=(n,a)=>{let o=e&&w3p(r,a)||a;O0o(r[o])&&O0o(n)?r[o]=d7s(r[o],n):O0o(n)?r[o]=d7s({},n):pTn(n)?r[o]=n.slice():(!t||!dTn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&tOa(arguments[n],i);return r}var JmS=(e,t,r,{allOwnKeys:i}={})=>(tOa(t,(n,a)=>{r&&DH(n)?e[a]=Zga(n,r):e[a]=n},{allOwnKeys:i}),e),$mS=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),YmS=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},XmS=(e,t,r,i)=>{let n,a,o,c={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)o=n[a],(!i||i(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=r!==!1&&p7s(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},ZmS=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},kmS=e=>{if(!e)return null;if(pTn(e))return e;let t=e.length;if(!j3p(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},e0S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&p7s(Uint8Array)),t0S=(e,t)=>{let i=(e&&e[A0o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},r0S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},i0S=RNt("HTMLFormElement"),n0S=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),A3p=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),a0S=RNt("RegExp"),S3p=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};tOa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},o0S=e=>{S3p(e,(t,r)=>{if(DH(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(DH(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},u0S=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return pTn(e)?i(e):i(String(e).split(t)),r},s0S=()=>{},c0S=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function l0S(e){return!!(e&&DH(e.append)&&e[m3p]==="FormData"&&e[A0o])}var f0S=e=>{let t=new Array(10),r=(i,n)=>{if(eOa(i)){if(t.indexOf(i)>=0)return;if(kga(i))return i;if(!("toJSON"in i)){t[n]=i;let a=pTn(i)?[]:{};return tOa(i,(o,c)=>{let f=r(o,n+1);!dTn(f)&&(a[c]=f)}),t[n]=void 0,a}}return i};return r(e,0)},d0S=RNt("AsyncFunction"),p0S=e=>e&&(eOa(e)||DH(e))&&DH(e.then)&&DH(e.catch),M3p=((e,t)=>e?setImmediate:t?((r,i)=>(U7i.addEventListener("message",({source:n,data:a})=>{n===U7i&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),U7i.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",DH(U7i.postMessage)),_0S=typeof queueMicrotask<"u"?queueMicrotask.bind(U7i):typeof process<"u"&&process.nextTick||M3p,h0S=e=>e!=null&&DH(e[A0o]),er={isArray:pTn,isArrayBuffer:P3p,isBuffer:kga,isFormData:LmS,isArrayBufferView:CmS,isString:qmS,isNumber:j3p,isBoolean:TmS,isObject:eOa,isPlainObject:O0o,isEmptyObject:RmS,isReadableStream:WmS,isRequest:xmS,isResponse:GmS,isHeaders:HmS,isUndefined:dTn,isDate:zmS,isFile:NmS,isBlob:FmS,isRegExp:a0S,isFunction:DH,isStream:UmS,isURLSearchParams:VmS,isTypedArray:e0S,isFileList:QmS,forEach:tOa,merge:d7s,extend:JmS,trim:KmS,stripBOM:$mS,inherits:YmS,toFlatObject:XmS,kindOf:m0o,kindOfTest:RNt,endsWith:ZmS,toArray:kmS,forEachEntry:t0S,matchAll:r0S,isHTMLForm:i0S,hasOwnProperty:A3p,hasOwnProp:A3p,reduceDescriptors:S3p,freezeMethods:o0S,toObjectSet:u0S,toCamelCase:n0S,noop:s0S,toFiniteNumber:c0S,findKey:w3p,global:U7i,isContextDefined:E3p,isSpecCompliantForm:l0S,toJSONObject:f0S,isAsyncFn:d0S,isThenable:p0S,setImmediate:M3p,asap:_0S,isIterable:h0S};function _Tn(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}er.inherits(_Tn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:er.toJSONObject(this.config),code:this.code,status:this.status}}});var D3p=_Tn.prototype,B3p={};["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=>{B3p[e]={value:e}});Object.defineProperties(_Tn,B3p);Object.defineProperty(D3p,"isAxiosError",{value:!0});_Tn.from=(e,t,r,i,n,a)=>{let o=Object.create(D3p);er.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",f=t==null&&e?e.code:t;return _Tn.call(o,c,f,r,i,n),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",a&&Object.assign(o,a),o};var ha=_Tn;var I3p=ue(jGi(),1),j0o=I3p.default;function _7s(e){return er.isPlainObject(e)||er.isArray(e)}function q3p(e){return er.endsWith(e,"[]")?e.slice(0,-2):e}function C3p(e,t,r){return e?e.concat(t).map(function(n,a){return n=q3p(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function y0S(e){return er.isArray(e)&&!e.some(_7s)}var b0S=er.toFlatObject(er,{},null,function(t){return/^is[A-Z]/.test(t)});function v0S(e,t,r){if(!er.isObject(e))throw new TypeError("target must be an object");t=t||new(j0o||FormData),r=er.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!er.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&er.isSpecCompliantForm(t);if(!er.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(er.isDate(h))return h.toISOString();if(er.isBoolean(h))return h.toString();if(!f&&er.isBlob(h))throw new ha("Blob is not supported. Use a Buffer instead.");return er.isArrayBuffer(h)||er.isTypedArray(h)?f&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,y,b){let v=h;if(h&&!b&&typeof h=="object"){if(er.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(er.isArray(h)&&y0S(h)||(er.isFileList(h)||er.endsWith(y,"[]"))&&(v=er.toArray(h)))return y=q3p(y),v.forEach(function(A,g){!(er.isUndefined(A)||A===null)&&t.append(o===!0?C3p([y],g,a):o===null?y:y+"[]",s(A))}),!1}return _7s(h)?!0:(t.append(C3p(b,y,a),s(h)),!1)}let l=[],p=Object.assign(b0S,{defaultVisitor:u,convertValue:s,isVisitable:_7s});function _(h,y){if(!er.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),er.forEach(h,function(v,O){(!(er.isUndefined(v)||v===null)&&n.call(t,v,er.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),l.pop()}}if(!er.isObject(e))throw new TypeError("data must be an object");return _(e),t}var IBi=v0S;function T3p(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function R3p(e,t){this._pairs=[],e&&IBi(e,this,t)}var z3p=R3p.prototype;z3p.append=function(t,r){this._pairs.push([t,r])};z3p.toString=function(t){let r=t?function(i){return t.call(this,i,T3p)}:T3p;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var N3p=R3p;function g0S(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function L7i(e,t,r){if(!t)return e;let i=r&&r.encode||g0S;er.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=er.isURLSearchParams(t)?t.toString():new N3p(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var h7s=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){er.forEach(this.handlers,function(i){i!==null&&t(i)})}},y7s=h7s;var hTn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var L3p=ue(require("crypto"),1);var F3p=ue(require("url"),1),Q3p=F3p.default.URLSearchParams;var b7s="abcdefghijklmnopqrstuvwxyz",U3p="0123456789",V3p={DIGIT:U3p,ALPHA:b7s,ALPHA_DIGIT:b7s+b7s.toUpperCase()+U3p},O0S=(e=16,t=V3p.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);L3p.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},W3p={isNode:!0,classes:{URLSearchParams:Q3p,FormData:j0o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:V3p,generateString:O0S,protocols:["http","https","file","data"]};var O7s={};Yt(O7s,{hasBrowserEnv:()=>g7s,hasStandardBrowserEnv:()=>A0S,hasStandardBrowserWebWorkerEnv:()=>m0S,navigator:()=>v7s,origin:()=>P0S});var g7s=typeof window<"u"&&typeof document<"u",v7s=typeof navigator=="object"&&navigator||void 0,A0S=g7s&&(!v7s||["ReactNative","NativeScript","NS"].indexOf(v7s.product)<0),m0S=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",P0S=g7s&&window.location.href||"http://localhost";var OA={...O7s,...W3p};function A7s(e,t){return IBi(e,new OA.classes.URLSearchParams,{visitor:function(r,i,n,a){return OA.isNode&&er.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function j0S(e){return er.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function w0S(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function E0S(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),f=a>=r.length;return o=!o&&er.isArray(n)?n.length:o,f?(er.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!er.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&er.isArray(n[o])&&(n[o]=w0S(n[o])),!c)}if(er.isFormData(e)&&er.isFunction(e.entries)){let r={};return er.forEachEntry(e,(i,n)=>{t(j0S(i),n,r,0)}),r}return null}var w0o=E0S;function S0S(e,t,r){if(er.isString(e))try{return(t||JSON.parse)(e),er.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var m7s={transitional:hTn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=er.isObject(t);if(a&&er.isHTMLForm(t)&&(t=new FormData(t)),er.isFormData(t))return n?JSON.stringify(w0o(t)):t;if(er.isArrayBuffer(t)||er.isBuffer(t)||er.isStream(t)||er.isFile(t)||er.isBlob(t)||er.isReadableStream(t))return t;if(er.isArrayBufferView(t))return t.buffer;if(er.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return A7s(t,this.formSerializer).toString();if((c=er.isFileList(t))||i.indexOf("multipart/form-data")>-1){let f=this.env&&this.env.FormData;return IBi(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),S0S(t)):t}],transformResponse:[function(t){let r=this.transitional||m7s.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(er.isResponse(t)||er.isReadableStream(t))return t;if(t&&er.isString(t)&&(i&&!this.responseType||n)){let o=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t,this.parseReviver)}catch(c){if(o)throw c.name==="SyntaxError"?ha.from(c,ha.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:OA.classes.FormData,Blob:OA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};er.forEach(["delete","get","head","post","put","patch"],e=>{m7s.headers[e]={}});var yTn=m7s;var M0S=er.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),x3p=e=>{let t={},r,i,n;return e&&e.split(`
1151
1151
  `).forEach(function(o){n=o.indexOf(":"),r=o.substring(0,n).trim().toLowerCase(),i=o.substring(n+1).trim(),!(!r||t[r]&&M0S[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var G3p=Symbol("internals");function rOa(e){return e&&String(e).trim().toLowerCase()}function E0o(e){return e===!1||e==null?e:er.isArray(e)?e.map(E0o):String(e)}function D0S(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}var B0S=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function P7s(e,t,r,i,n){if(er.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!er.isString(t)){if(er.isString(i))return t.indexOf(i)!==-1;if(er.isRegExp(i))return i.test(t)}}function I0S(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function C0S(e,t){let r=er.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,o){return this[i].call(this,t,n,a,o)},configurable:!0})})}var bTn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(c,f,s){let u=rOa(f);if(!u)throw new Error("header name must be a non-empty string");let l=er.findKey(n,u);(!l||n[l]===void 0||s===!0||s===void 0&&n[l]!==!1)&&(n[l||f]=E0o(c))}let o=(c,f)=>er.forEach(c,(s,u)=>a(s,u,f));if(er.isPlainObject(t)||t instanceof this.constructor)o(t,r);else if(er.isString(t)&&(t=t.trim())&&!B0S(t))o(x3p(t),r);else if(er.isObject(t)&&er.isIterable(t)){let c={},f,s;for(let u of t){if(!er.isArray(u))throw TypeError("Object iterator must return a key-value pair");c[s=u[0]]=(f=c[s])?er.isArray(f)?[...f,u[1]]:[f,u[1]]:u[1]}o(c,r)}else t!=null&&a(r,t,i);return this}get(t,r){if(t=rOa(t),t){let i=er.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return D0S(n);if(er.isFunction(r))return r.call(this,n,i);if(er.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=rOa(t),t){let i=er.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||P7s(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(o){if(o=rOa(o),o){let c=er.findKey(i,o);c&&(!r||P7s(i,i[c],c,r))&&(delete i[c],n=!0)}}return er.isArray(t)?t.forEach(a):a(t),n}clear(t){let r=Object.keys(this),i=r.length,n=!1;for(;i--;){let a=r[i];(!t||P7s(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return er.forEach(this,(n,a)=>{let o=er.findKey(i,a);if(o){r[o]=E0o(n),delete r[a];return}let c=t?I0S(a):String(a).trim();c!==a&&delete r[a],r[c]=E0o(n),i[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return er.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&er.isArray(i)?i.join(", "):i)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
1152
1152
  `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let i=new this(t);return r.forEach(n=>i.set(n)),i}static accessor(t){let i=(this[G3p]=this[G3p]={accessors:{}}).accessors,n=this.prototype;function a(o){let c=rOa(o);i[c]||(C0S(n,o),i[c]=!0)}return er.isArray(t)?t.forEach(a):a(t),this}};bTn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);er.reduceDescriptors(bTn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});er.freezeMethods(bTn);var QS=bTn;function iOa(e,t){let r=this||yTn,i=t||r,n=QS.from(i.headers),a=i.data;return er.forEach(e,function(c){a=c.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function nOa(e){return!!(e&&e.__CANCEL__)}function H3p(e,t,r){ha.call(this,e??"canceled",ha.ERR_CANCELED,t,r),this.name="CanceledError"}er.inherits(H3p,ha,{__CANCEL__:!0});var k_e=H3p;function t6t(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new ha("Request failed with status code "+r.status,[ha.ERR_BAD_REQUEST,ha.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function j7s(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function w7s(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function V7i(e,t,r){let i=!j7s(t);return e&&(i||r==!1)?w7s(e,t):t}var s8p=ue(Kmo(),1),c8p=ue(require("http"),1),l8p=ue(require("https"),1),f8p=ue(require("util"),1),d8p=ue(EGs(),1),Nbi=ue(require("zlib"),1);var W7i="1.12.2";function aOa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var q0S=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function E7s(e,t,r){let i=r&&r.Blob||OA.classes.Blob,n=aOa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=q0S.exec(e);if(!a)throw new ha("Invalid URL",ha.ERR_INVALID_URL);let o=a[1],c=a[2],f=a[3],s=Buffer.from(decodeURIComponent(f),c?"base64":"utf8");if(t){if(!i)throw new ha("Blob is not supported",ha.ERR_NOT_SUPPORT);return new i([s],{type:o})}return s}throw new ha("Unsupported protocol "+n,ha.ERR_NOT_SUPPORT)}var G7i=ue(require("stream"),1);var K3p=ue(require("stream"),1);var S7s=Symbol("internals"),M7s=class extends K3p.default.Transform{constructor(t){t=er.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!er.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[S7s]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",i=>{i==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[S7s];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[S7s],a=n.maxRate,o=this.readableHighWaterMark,c=n.timeWindow,f=1e3/c,s=a/f,u=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,l=(_,h)=>{let y=Buffer.byteLength(_);n.bytesSeen+=y,n.bytes+=y,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(_)?process.nextTick(h):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(h)}},p=(_,h)=>{let y=Buffer.byteLength(_),b=null,v=o,O,A=0;if(a){let g=Date.now();(!n.ts||(A=g-n.ts)>=c)&&(n.ts=g,O=s-n.bytes,n.bytes=O<0?-O:0,A=0),O=s-n.bytes}if(a){if(O<=0)return setTimeout(()=>{h(null,_)},c-A);O<v&&(v=O)}v&&y>v&&y-v>u&&(b=_.subarray(v),_=_.subarray(0,v)),l(_,b?()=>{process.nextTick(h,null,b)}:h)};p(t,function _(h,y){if(h)return i(h);y?p(y,_):i(null)})}},D7s=M7s;var p8p=require("events");var $3p=ue(require("util"),1),Y3p=require("stream");var{asyncIterator:J3p}=Symbol,T0S=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[J3p]?yield*e[J3p]():yield e},S0o=T0S;var R0S=OA.ALPHABET.ALPHA_DIGIT+"-_",oOa=typeof TextEncoder=="function"?new TextEncoder:new $3p.default.TextEncoder,x7i=`\r
1153
1153
  `,z0S=oOa.encode(x7i),N0S=2,B7s=class{constructor(t,r){let{escapeName:i}=this.constructor,n=er.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${x7i}`;n?r=oOa.encode(String(r).replace(/\r?\n|\r\n?/g,x7i)):a+=`Content-Type: ${r.type||"application/octet-stream"}${x7i}`,this.headers=oOa.encode(a+x7i),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+N0S,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;er.isTypedArray(t)?yield t:yield*S0o(t),yield z0S}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},F0S=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+OA.generateString(n,R0S)}=r||{};if(!er.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let o=oOa.encode("--"+a+x7i),c=oOa.encode("--"+a+"--"+x7i),f=c.byteLength,s=Array.from(e.entries()).map(([l,p])=>{let _=new B7s(l,p);return f+=_.size,_});f+=o.byteLength*s.length,f=er.toFiniteNumber(f);let u={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(f)&&(u["Content-Length"]=f),t&&t(u),Y3p.Readable.from((async function*(){for(let l of s)yield o,yield*l.encode();yield c})())},X3p=F0S;var Z3p=ue(require("stream"),1),I7s=class extends Z3p.default.Transform{__transform(t,r,i){this.push(t),i()}_transform(t,r,i){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let n=Buffer.alloc(2);n[0]=120,n[1]=156,this.push(n,r)}this.__transform(t,r,i)}},k3p=I7s;var Q0S=(e,t)=>er.isAsyncFn(e)?function(...r){let i=r.pop();e.apply(this,r).then(n=>{try{t?i(null,...t(n)):i(null,n)}catch(a){i(a)}},i)}:e,e8p=Q0S;function U0S(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,o;return t=t!==void 0?t:1e3,function(f){let s=Date.now(),u=i[a];o||(o=s),r[n]=f,i[n]=s;let l=a,p=0;for(;l!==n;)p+=r[l++],l=l%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-o<t)return;let _=u&&s-u;return _?Math.round(p*1e3/_):void 0}}var t8p=U0S;function L0S(e,t){let r=0,i=1e3/t,n,a,o=(s,u=Date.now())=>{r=u,n=null,a&&(clearTimeout(a),a=null),e(...s)};return[(...s)=>{let u=Date.now(),l=u-r;l>=i?o(s,u):(n=s,a||(a=setTimeout(()=>{a=null,o(n)},i-l)))},()=>n&&o(n)]}var r8p=L0S;var zbi=(e,t,r=3)=>{let i=0,n=t8p(50,250);return r8p(a=>{let o=a.loaded,c=a.lengthComputable?a.total:void 0,f=o-i,s=n(f),u=o<=c;i=o;let l={loaded:o,total:c,progress:c?o/c:void 0,bytes:f,rate:s||void 0,estimated:s&&c&&u?(c-o)/s:void 0,event:a,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(l)},r)},vTn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},gTn=e=>(...t)=>er.asap(()=>e(...t));function C7s(e){if(!e||typeof e!="string"||!e.startsWith("data:"))return 0;let t=e.indexOf(",");if(t<0)return 0;let r=e.slice(5,t),i=e.slice(t+1);if(/;base64/i.test(r)){let a=i.length,o=i.length;for(let p=0;p<o;p++)if(i.charCodeAt(p)===37&&p+2<o){let _=i.charCodeAt(p+1),h=i.charCodeAt(p+2);(_>=48&&_<=57||_>=65&&_<=70||_>=97&&_<=102)&&(h>=48&&h<=57||h>=65&&h<=70||h>=97&&h<=102)&&(a-=2,p+=2)}let c=0,f=o-1,s=p=>p>=2&&i.charCodeAt(p-2)===37&&i.charCodeAt(p-1)===51&&(i.charCodeAt(p)===68||i.charCodeAt(p)===100);f>=0&&(i.charCodeAt(f)===61?(c++,f--):s(f)&&(c++,f-=3)),c===1&&f>=0&&(i.charCodeAt(f)===61||s(f))&&c++;let l=Math.floor(a/4)*3-(c||0);return l>0?l:0}return Buffer.byteLength(i,"utf8")}var i8p={flush:Nbi.default.constants.Z_SYNC_FLUSH,finishFlush:Nbi.default.constants.Z_SYNC_FLUSH},V0S={flush:Nbi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:Nbi.default.constants.BROTLI_OPERATION_FLUSH},n8p=er.isFunction(Nbi.default.createBrotliDecompress),{http:W0S,https:x0S}=d8p.default,G0S=/https:?/,a8p=OA.protocols.map(e=>e+":"),o8p=(e,[t,r])=>(e.on("end",r).on("error",r),t);function H0S(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function _8p(e,t,r){let i=t;if(!i&&i!==!1){let n=s8p.default.getProxyForUrl(r);n&&(i=new URL(n))}if(i){if(i.username&&(i.auth=(i.username||"")+":"+(i.password||"")),i.auth){(i.auth.username||i.auth.password)&&(i.auth=(i.auth.username||"")+":"+(i.auth.password||""));let a=Buffer.from(i.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let n=i.hostname||i.host;e.hostname=n,e.host=n,e.port=i.port,e.path=r,i.protocol&&(e.protocol=i.protocol.includes(":")?i.protocol:`${i.protocol}:`)}e.beforeRedirects.proxy=function(a){_8p(a,t,a.href)}}var K0S=typeof process<"u"&&er.kindOf(process)==="process",J0S=e=>new Promise((t,r)=>{let i,n,a=(f,s)=>{n||(n=!0,i&&i(f,s))},o=f=>{a(f),t(f)},c=f=>{a(f,!0),r(f)};e(o,c,f=>i=f).catch(c)}),$0S=({address:e,family:t})=>{if(!er.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},u8p=(e,t)=>$0S(er.isObject(e)?e:{address:e,family:t}),h8p=K0S&&function(t){return J0S(async function(i,n,a){let{data:o,lookup:c,family:f}=t,{responseType:s,responseEncoding:u}=t,l=t.method.toUpperCase(),p,_=!1,h;if(c){let K=e8p(c,fe=>er.isArray(fe)?fe:[fe]);c=(fe,pe,L)=>{K(fe,pe,(G,Re,le)=>{if(G)return L(G);let Ie=er.isArray(Re)?Re.map(Ke=>u8p(Ke)):[u8p(Re,le)];pe.all?L(G,Ie):L(G,Ie[0].address,Ie[0].family)})}}let y=new p8p.EventEmitter,b=()=>{t.cancelToken&&t.cancelToken.unsubscribe(v),t.signal&&t.signal.removeEventListener("abort",v),y.removeAllListeners()};a((K,fe)=>{p=!0,fe&&(_=!0,b())});function v(K){y.emit("abort",!K||K.type?new k_e(null,t,h):K)}y.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(v),t.signal&&(t.signal.aborted?v():t.signal.addEventListener("abort",v)));let O=V7i(t.baseURL,t.url,t.allowAbsoluteUrls),A=new URL(O,OA.hasBrowserEnv?OA.origin:void 0),g=A.protocol||a8p[0];if(g==="data:"){if(t.maxContentLength>-1){let fe=String(t.url||O||"");if(C7s(fe)>t.maxContentLength)return n(new ha("maxContentLength size of "+t.maxContentLength+" exceeded",ha.ERR_BAD_RESPONSE,t))}let K;if(l!=="GET")return t6t(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{K=E7s(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(fe){throw ha.from(fe,ha.ERR_BAD_REQUEST,t)}return s==="text"?(K=K.toString(u),(!u||u==="utf8")&&(K=er.stripBOM(K))):s==="stream"&&(K=G7i.default.Readable.from(K)),t6t(i,n,{data:K,status:200,statusText:"OK",headers:new QS,config:t})}if(a8p.indexOf(g)===-1)return n(new ha("Unsupported protocol "+g,ha.ERR_BAD_REQUEST,t));let m=QS.from(t.headers).normalize();m.set("User-Agent","axios/"+W7i,!1);let{onUploadProgress:j,onDownloadProgress:M}=t,E=t.maxRate,D,B;if(er.isSpecCompliantForm(o)){let K=m.getContentType(/boundary=([-_\w\d]{10,70})/i);o=X3p(o,fe=>{m.set(fe)},{tag:`axios-${W7i}-boundary`,boundary:K&&K[1]||void 0})}else if(er.isFormData(o)&&er.isFunction(o.getHeaders)){if(m.set(o.getHeaders()),!m.hasContentLength())try{let K=await f8p.default.promisify(o.getLength).call(o);Number.isFinite(K)&&K>=0&&m.setContentLength(K)}catch{}}else if(er.isBlob(o)||er.isFile(o))o.size&&m.setContentType(o.type||"application/octet-stream"),m.setContentLength(o.size||0),o=G7i.default.Readable.from(S0o(o));else if(o&&!er.isStream(o)){if(!Buffer.isBuffer(o))if(er.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else if(er.isString(o))o=Buffer.from(o,"utf-8");else return n(new ha("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",ha.ERR_BAD_REQUEST,t));if(m.setContentLength(o.length,!1),t.maxBodyLength>-1&&o.length>t.maxBodyLength)return n(new ha("Request body larger than maxBodyLength limit",ha.ERR_BAD_REQUEST,t))}let F=er.toFiniteNumber(m.getContentLength());er.isArray(E)?(D=E[0],B=E[1]):D=B=E,o&&(j||D)&&(er.isStream(o)||(o=G7i.default.Readable.from(o,{objectMode:!1})),o=G7i.default.pipeline([o,new D7s({maxRate:er.toFiniteNumber(D)})],er.noop),j&&o.on("progress",o8p(o,vTn(F,zbi(gTn(j),!1,3)))));let N;if(t.auth){let K=t.auth.username||"",fe=t.auth.password||"";N=K+":"+fe}if(!N&&A.username){let K=A.username,fe=A.password;N=K+":"+fe}N&&m.delete("authorization");let R;try{R=L7i(A.pathname+A.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(K){let fe=new Error(K.message);return fe.config=t,fe.url=t.url,fe.exists=!0,n(fe)}m.set("Accept-Encoding","gzip, compress, deflate"+(n8p?", br":""),!1);let z={path:R,method:l,headers:m.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:N,protocol:g,family:f,beforeRedirect:H0S,beforeRedirects:{}};!er.isUndefined(c)&&(z.lookup=c),t.socketPath?z.socketPath=t.socketPath:(z.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,z.port=A.port,_8p(z,t.proxy,g+"//"+A.hostname+(A.port?":"+A.port:"")+z.path));let U,W=G0S.test(z.protocol);if(z.agent=W?t.httpsAgent:t.httpAgent,t.transport?U=t.transport:t.maxRedirects===0?U=W?l8p.default:c8p.default:(t.maxRedirects&&(z.maxRedirects=t.maxRedirects),t.beforeRedirect&&(z.beforeRedirects.config=t.beforeRedirect),U=W?x0S:W0S),t.maxBodyLength>-1?z.maxBodyLength=t.maxBodyLength:z.maxBodyLength=1/0,t.insecureHTTPParser&&(z.insecureHTTPParser=t.insecureHTTPParser),h=U.request(z,function(fe){if(h.destroyed)return;let pe=[fe],L=+fe.headers["content-length"];if(M||B){let Ke=new D7s({maxRate:er.toFiniteNumber(B)});M&&Ke.on("progress",o8p(Ke,vTn(L,zbi(gTn(M),!0,3)))),pe.push(Ke)}let G=fe,Re=fe.req||h;if(t.decompress!==!1&&fe.headers["content-encoding"])switch((l==="HEAD"||fe.statusCode===204)&&delete fe.headers["content-encoding"],(fe.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":pe.push(Nbi.default.createUnzip(i8p)),delete fe.headers["content-encoding"];break;case"deflate":pe.push(new k3p),pe.push(Nbi.default.createUnzip(i8p)),delete fe.headers["content-encoding"];break;case"br":n8p&&(pe.push(Nbi.default.createBrotliDecompress(V0S)),delete fe.headers["content-encoding"])}G=pe.length>1?G7i.default.pipeline(pe,er.noop):pe[0];let le=G7i.default.finished(G,()=>{le(),b()}),Ie={status:fe.statusCode,statusText:fe.statusMessage,headers:new QS(fe.headers),config:t,request:Re};if(s==="stream")Ie.data=G,t6t(i,n,Ie);else{let Ke=[],se=0;G.on("data",function(Je){Ke.push(Je),se+=Je.length,t.maxContentLength>-1&&se>t.maxContentLength&&(_=!0,G.destroy(),n(new ha("maxContentLength size of "+t.maxContentLength+" exceeded",ha.ERR_BAD_RESPONSE,t,Re)))}),G.on("aborted",function(){if(_)return;let Je=new ha("stream has been aborted",ha.ERR_BAD_RESPONSE,t,Re);G.destroy(Je),n(Je)}),G.on("error",function(Je){h.destroyed||n(ha.from(Je,null,t,Re))}),G.on("end",function(){try{let Je=Ke.length===1?Ke[0]:Buffer.concat(Ke);s!=="arraybuffer"&&(Je=Je.toString(u),(!u||u==="utf8")&&(Je=er.stripBOM(Je))),Ie.data=Je}catch(Je){return n(ha.from(Je,null,t,Ie.request,Ie))}t6t(i,n,Ie)})}y.once("abort",Ke=>{G.destroyed||(G.emit("error",Ke),G.destroy())})}),y.once("abort",K=>{n(K),h.destroy(K)}),h.on("error",function(fe){n(ha.from(fe,null,t,h))}),h.on("socket",function(fe){fe.setKeepAlive(!0,1e3*60)}),t.timeout){let K=parseInt(t.timeout,10);if(Number.isNaN(K)){n(new ha("error trying to parse `config.timeout` to int",ha.ERR_BAD_OPTION_VALUE,t,h));return}h.setTimeout(K,function(){if(p)return;let pe=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",L=t.transitional||hTn;t.timeoutErrorMessage&&(pe=t.timeoutErrorMessage),n(new ha(pe,L.clarifyTimeoutError?ha.ETIMEDOUT:ha.ECONNABORTED,t,h)),v()})}if(er.isStream(o)){let K=!1,fe=!1;o.on("end",()=>{K=!0}),o.once("error",pe=>{fe=!0,h.destroy(pe)}),o.on("close",()=>{!K&&!fe&&v(new k_e("Request stream has been aborted",t,h))}),o.pipe(h)}else h.end(o)})};var y8p=OA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,OA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(OA.origin),OA.navigator&&/(msie|trident)/i.test(OA.navigator.userAgent)):()=>!0;var b8p=OA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let o=[e+"="+encodeURIComponent(t)];er.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),er.isString(i)&&o.push("path="+i),er.isString(n)&&o.push("domain="+n),a===!0&&o.push("secure"),document.cookie=o.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var v8p=e=>e instanceof QS?{...e}:e;function zNt(e,t){t=t||{};let r={};function i(s,u,l,p){return er.isPlainObject(s)&&er.isPlainObject(u)?er.merge.call({caseless:p},s,u):er.isPlainObject(u)?er.merge({},u):er.isArray(u)?u.slice():u}function n(s,u,l,p){if(er.isUndefined(u)){if(!er.isUndefined(s))return i(void 0,s,l,p)}else return i(s,u,l,p)}function a(s,u){if(!er.isUndefined(u))return i(void 0,u)}function o(s,u){if(er.isUndefined(u)){if(!er.isUndefined(s))return i(void 0,s)}else return i(void 0,u)}function c(s,u,l){if(l in t)return i(s,u);if(l in e)return i(void 0,s)}let f={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:c,headers:(s,u,l)=>n(v8p(s),v8p(u),l,!0)};return er.forEach(Object.keys({...e,...t}),function(u){let l=f[u]||n,p=l(e[u],t[u],u);er.isUndefined(p)&&l!==c||(r[u]=p)}),r}var M0o=e=>{let t=zNt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=QS.from(o),t.url=L7i(V7i(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),er.isFormData(r)){if(OA.hasStandardBrowserEnv||OA.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(er.isFunction(r.getHeaders)){let f=r.getHeaders(),s=["content-type","content-length"];Object.entries(f).forEach(([u,l])=>{s.includes(u.toLowerCase())&&o.set(u,l)})}}if(OA.hasStandardBrowserEnv&&(i&&er.isFunction(i)&&(i=i(t)),i||i!==!1&&y8p(t.url))){let f=n&&a&&b8p.read(a);f&&o.set(n,f)}return t};var Y0S=typeof XMLHttpRequest<"u",g8p=Y0S&&function(e){return new Promise(function(r,i){let n=M0o(e),a=n.data,o=QS.from(n.headers).normalize(),{responseType:c,onUploadProgress:f,onDownloadProgress:s}=n,u,l,p,_,h;function y(){_&&_(),h&&h(),n.cancelToken&&n.cancelToken.unsubscribe(u),n.signal&&n.signal.removeEventListener("abort",u)}let b=new XMLHttpRequest;b.open(n.method.toUpperCase(),n.url,!0),b.timeout=n.timeout;function v(){if(!b)return;let A=QS.from("getAllResponseHeaders"in b&&b.getAllResponseHeaders()),m={data:!c||c==="text"||c==="json"?b.responseText:b.response,status:b.status,statusText:b.statusText,headers:A,config:e,request:b};t6t(function(M){r(M),y()},function(M){i(M),y()},m),b=null}"onloadend"in b?b.onloadend=v:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(v)},b.onabort=function(){b&&(i(new ha("Request aborted",ha.ECONNABORTED,e,b)),b=null)},b.onerror=function(g){let m=g&&g.message?g.message:"Network Error",j=new ha(m,ha.ERR_NETWORK,e,b);j.event=g||null,i(j),b=null},b.ontimeout=function(){let g=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",m=n.transitional||hTn;n.timeoutErrorMessage&&(g=n.timeoutErrorMessage),i(new ha(g,m.clarifyTimeoutError?ha.ETIMEDOUT:ha.ECONNABORTED,e,b)),b=null},a===void 0&&o.setContentType(null),"setRequestHeader"in b&&er.forEach(o.toJSON(),function(g,m){b.setRequestHeader(m,g)}),er.isUndefined(n.withCredentials)||(b.withCredentials=!!n.withCredentials),c&&c!=="json"&&(b.responseType=n.responseType),s&&([p,h]=zbi(s,!0),b.addEventListener("progress",p)),f&&b.upload&&([l,_]=zbi(f),b.upload.addEventListener("progress",l),b.upload.addEventListener("loadend",_)),(n.cancelToken||n.signal)&&(u=A=>{b&&(i(!A||A.type?new k_e(null,e,b):A),b.abort(),b=null)},n.cancelToken&&n.cancelToken.subscribe(u),n.signal&&(n.signal.aborted?u():n.signal.addEventListener("abort",u)));let O=aOa(n.url);if(O&&OA.protocols.indexOf(O)===-1){i(new ha("Unsupported protocol "+O+":",ha.ERR_BAD_REQUEST,e));return}b.send(a||null)})};var X0S=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,c();let u=s instanceof Error?s:this.reason;i.abort(u instanceof ha?u:new k_e(u instanceof Error?u.message:u))}},o=t&&setTimeout(()=>{o=null,a(new ha(`timeout ${t} of ms exceeded`,ha.ETIMEDOUT))},t),c=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:f}=i;return f.unsubscribe=()=>er.asap(c),f}},O8p=X0S;var Z0S=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let i=0,n;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},k0S=async function*(e,t){for await(let r of ePS(e))yield*Z0S(r,t)},ePS=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:i}=await t.read();if(r)break;yield i}}finally{await t.cancel()}},q7s=(e,t,r,i)=>{let n=k0S(e,t),a=0,o,c=f=>{o||(o=!0,i&&i(f))};return new ReadableStream({async pull(f){try{let{done:s,value:u}=await n.next();if(s){c(),f.close();return}let l=u.byteLength;if(r){let p=a+=l;r(p)}f.enqueue(new Uint8Array(u))}catch(s){throw c(s),s}},cancel(f){return c(f),n.return()}},{highWaterMark:2})};var A8p=64*1024,{isFunction:D0o}=er,tPS=(({Request:e,Response:t})=>({Request:e,Response:t}))(er.global),{ReadableStream:m8p,TextEncoder:P8p}=er.global,j8p=(e,...t)=>{try{return!!e(...t)}catch{return!1}},rPS=e=>{e=er.merge.call({skipUndefined:!0},tPS,e);let{fetch:t,Request:r,Response:i}=e,n=t?D0o(t):typeof fetch=="function",a=D0o(r),o=D0o(i);if(!n)return!1;let c=n&&D0o(m8p),f=n&&(typeof P8p=="function"?(h=>y=>h.encode(y))(new P8p):async h=>new Uint8Array(await new r(h).arrayBuffer())),s=a&&c&&j8p(()=>{let h=!1,y=new r(OA.origin,{body:new m8p,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!y}),u=o&&c&&j8p(()=>er.isReadableStream(new i("").body)),l={stream:u&&(h=>h.body)};n&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!l[h]&&(l[h]=(y,b)=>{let v=y&&y[h];if(v)return v.call(y);throw new ha(`Response type '${h}' is not supported`,ha.ERR_NOT_SUPPORT,b)})});let p=async h=>{if(h==null)return 0;if(er.isBlob(h))return h.size;if(er.isSpecCompliantForm(h))return(await new r(OA.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(er.isArrayBufferView(h)||er.isArrayBuffer(h))return h.byteLength;if(er.isURLSearchParams(h)&&(h=h+""),er.isString(h))return(await f(h)).byteLength},_=async(h,y)=>{let b=er.toFiniteNumber(h.getContentLength());return b??p(y)};return async h=>{let{url:y,method:b,data:v,signal:O,cancelToken:A,timeout:g,onDownloadProgress:m,onUploadProgress:j,responseType:M,headers:E,withCredentials:D="same-origin",fetchOptions:B}=M0o(h),F=t||fetch;M=M?(M+"").toLowerCase():"text";let N=O8p([O,A&&A.toAbortSignal()],g),R=null,z=N&&N.unsubscribe&&(()=>{N.unsubscribe()}),U;try{if(j&&s&&b!=="get"&&b!=="head"&&(U=await _(E,v))!==0){let G=new r(y,{method:"POST",body:v,duplex:"half"}),Re;if(er.isFormData(v)&&(Re=G.headers.get("content-type"))&&E.setContentType(Re),G.body){let[le,Ie]=vTn(U,zbi(gTn(j)));v=q7s(G.body,A8p,le,Ie)}}er.isString(D)||(D=D?"include":"omit");let W=a&&"credentials"in r.prototype,K={...B,signal:N,method:b.toUpperCase(),headers:E.normalize().toJSON(),body:v,duplex:"half",credentials:W?D:void 0};R=a&&new r(y,K);let fe=await(a?F(R,B):F(y,K)),pe=u&&(M==="stream"||M==="response");if(u&&(m||pe&&z)){let G={};["status","statusText","headers"].forEach(Ke=>{G[Ke]=fe[Ke]});let Re=er.toFiniteNumber(fe.headers.get("content-length")),[le,Ie]=m&&vTn(Re,zbi(gTn(m),!0))||[];fe=new i(q7s(fe.body,A8p,le,()=>{Ie&&Ie(),z&&z()}),G)}M=M||"text";let L=await l[er.findKey(l,M)||"text"](fe,h);return!pe&&z&&z(),await new Promise((G,Re)=>{t6t(G,Re,{data:L,headers:QS.from(fe.headers),status:fe.status,statusText:fe.statusText,config:h,request:R})})}catch(W){throw z&&z(),W&&W.name==="TypeError"&&/Load failed|fetch/i.test(W.message)?Object.assign(new ha("Network Error",ha.ERR_NETWORK,h,R),{cause:W.cause||W}):ha.from(W,W&&W.code,h,R)}}},iPS=new Map,T7s=e=>{let t=e?e.env:{},{fetch:r,Request:i,Response:n}=t,a=[i,n,r],o=a.length,c=o,f,s,u=iPS;for(;c--;)f=a[c],s=u.get(f),s===void 0&&u.set(f,s=c?new Map:rPS(t)),u=s;return s},Bv5=T7s();var R7s={http:h8p,xhr:g8p,fetch:{get:T7s}};er.forEach(R7s,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var w8p=e=>`- ${e}`,aPS=e=>er.isFunction(e)||e===null||e===!1,B0o={getAdapter:(e,t)=>{e=er.isArray(e)?e:[e];let{length:r}=e,i,n,a={};for(let o=0;o<r;o++){i=e[o];let c;if(n=i,!aPS(i)&&(n=R7s[(c=String(i)).toLowerCase()],n===void 0))throw new ha(`Unknown adapter '${c}'`);if(n&&(er.isFunction(n)||(n=n.get(t))))break;a[c||"#"+o]=n}if(!n){let o=Object.entries(a).map(([f,s])=>`adapter ${f} `+(s===!1?"is not supported by the environment":"is not available in the build")),c=r?o.length>1?`since :
@@ -1391,7 +1391,7 @@ ${g}${O}${m}${lQn}`});function OQo({message:e,error:t,logger:r,logLevel:i=Js.Err
1391
1391
  Run ${Ut.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1392
1392
  Run ${Ut.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),TBi(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function buc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!bf_(e))return;let n=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let o=a.sort((c,f)=>c.generatorName.localeCompare(f.generatorName)||c.currentVersion.localeCompare(f.currentVersion));for(let c of o)n+=`
1393
1393
  ${await GXS(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Ut.dim(c.currentVersion)+Ut.reset(" \u2192 ")+Ut.green(c.latestVersion);return n+=`
1394
- `,i?TBi(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function GXS(e){let r=await new yf_.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 HXS({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await gf_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=CMi(u.name,l),_=await lNt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:l});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await gf_({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=CMi(s.name,u),p=await lNt({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][f][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function gf_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await K_e({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(!(c==null||c.groups==null)){for(let f of c.groups)if(!(n!=null&&f.groupName!==n))for(let s of f.generators)i!=null&&s.name!==i||await r(a.workspaceName,f.groupName,s,o)}})}))}function Of_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let f=XH(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:f,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function jQo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await HXS({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[f,s]of Object.entries(c.versions))o.push(...Of_(s,f,t.logger));else o.push(...Of_(c.versions,void 0,t.logger))}return o}var OPa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var _Qn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var vuc=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),Af_=typeof globalThis.AbortController=="function",mf_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Pf_=typeof globalThis.ReadableStream=="function",jf_=typeof globalThis.FormData=="function",wQo=["get","post","put","patch","head","delete"],KXS=()=>{};KXS();var wf_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},EQo=2147483647,Ef_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,SQo=Symbol("stop"),Sf_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Mf_={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 JXS=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Ef_,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},Df_=(e,t,r)=>{let i,n=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),i){n+=i.byteLength;let c=t===0?0:n/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,n),transferredBytes:n},i)}i=a},flush(){i&&(n+=i.byteLength,r?.({percent:1,totalBytes:Math.max(t,n),transferredBytes:n},i))}}))},Bf_=(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(Df_(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},If_=(e,t,r)=>{if(!e.body)return e;let i=JXS(r??e.body);return new Request(e,{duplex:"half",body:Df_(e.body,i,t)})};var hQn=e=>e!==null&&typeof e=="object";var APa=(...e)=>{for(let t of e)if((!hQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Auc({},...e)},guc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,o]of n.entries())i&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function MQo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Auc(e[r]??[],t[r]??[])}var Ouc=(e={},t={})=>({beforeRequest:MQo(e,t,"beforeRequest"),beforeRetry:MQo(e,t,"beforeRetry"),afterResponse:MQo(e,t,"afterResponse"),beforeError:MQo(e,t,"beforeError")}),Auc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(hQn(n)){for(let[a,o]of Object.entries(n))hQn(o)&&a in t&&(o=Auc(t[a],o)),t={...t,[a]:o};hQn(n.hooks)&&(i=Ouc(i,n.hooks),t.hooks=i),hQn(n.headers)&&(r=guc(r,n.headers),t.headers=r)}return t};var qf_=e=>wQo.includes(e)?e.toUpperCase():e,$XS=["get","put","head","delete","options","trace"],YXS=[408,413,429,500,502,503,504],XXS=[413,429,503],Cf_={limit:2,methods:$XS,statusCodes:YXS,afterStatusCodes:XXS,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Tf_=(e={})=>{if(typeof e=="number")return{...Cf_,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{...Cf_,...e}};async function muc(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new _Qn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function Puc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var Rf_=(e,t)=>{let r={};for(let i in t)!(i in Mf_)&&!(i in Sf_)&&!(i in e)&&(r[i]=t[i]);return r},zf_=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 mPa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>EQo)throw new RangeError(`The \`timeout\` option cannot be greater than ${EQo}`);await Promise.resolve();let c=await i._fetch();for(let f of i._options.hooks.afterResponse){let s=await f(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let f=new OPa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)f=await s(f);throw f}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Pf_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return Bf_(c.clone(),i._options.onDownloadProgress)}return c},o=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{let c=i._originalRequest,f=[];c&&!c.bodyUsed&&f.push(c.body?.cancel()),i.request.bodyUsed||f.push(i.request.body?.cancel()),await Promise.all(f)});for(let[c,f]of Object.entries(wf_))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||f);let s=await o;if(c==="json"){if(s.status===204)return"";let u=await s.text();return u===""?"":r.parseJson?r.parseJson(u):JSON.parse(u)}return s[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:guc(this._input.headers,r.headers),hooks:Ouc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:qf_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:Tf_(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(Af_&&mf_){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(vuc&&(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),zf_(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(jf_&&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(!vuc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=If_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof _Qn)throw t;if(t instanceof OPa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),EQo);if(this._retryCount<1)throw r;await Puc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===SQo)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=Rf_(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):muc(this._originalRequest,t,this.abortController,this._options)}};var juc=e=>{let t=(r,i)=>mPa.create(r,APa(e,i));for(let r of wQo)t[r]=(i,n)=>mPa.create(i,APa(e,n,{method:r}));return t.create=r=>juc(APa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),juc(APa(e,r))),t.stop=SQo,t},ZXS=juc(),Nf_=ZXS;var od_=ue(ad_(),1);function Duc(e){let t=(0,od_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var ep_=ue(kd_(),1),tp_=ue(O_e(),1),Vuc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Wuc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function xuc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Duc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,ep_.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 Nf_(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new Vuc(e):l}if(t.allVersions)return s;let u=new Wuc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!l){let _=Object.keys(s.versions);if(r=tp_.default.maxSatisfying(_,r),!r)throw u}let{time:p}=s;if(s=s.versions[r],s.time=p,!s)throw u}return s}async function MPa(e,t){let{version:r}=await xuc(e.toLowerCase(),t);return r}async function SCi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:MPa(e.packageName,{version:t?"prerelease":"latest"})}var rp_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],UQo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Js.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new PQo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.15.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Ut.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new TE}failWithoutThrowing(t,r){this.didSucceed=!1,OQo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await fTn()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await vf_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1394
+ `,i?TBi(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function GXS(e){let r=await new yf_.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 HXS({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await gf_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(f,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=CMi(u.name,l),_=await lNt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:l});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await gf_({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=CMi(s.name,u),p=await lNt({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][f][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function gf_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await K_e({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(!(c==null||c.groups==null)){for(let f of c.groups)if(!(n!=null&&f.groupName!==n))for(let s of f.generators)i!=null&&s.name!==i||await r(a.workspaceName,f.groupName,s,o)}})}))}function Of_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let f=XH(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(f?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:f,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function jQo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await HXS({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[f,s]of Object.entries(c.versions))o.push(...Of_(s,f,t.logger));else o.push(...Of_(c.versions,void 0,t.logger))}return o}var OPa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText??"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var _Qn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var vuc=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),Af_=typeof globalThis.AbortController=="function",mf_=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Pf_=typeof globalThis.ReadableStream=="function",jf_=typeof globalThis.FormData=="function",wQo=["get","post","put","patch","head","delete"],KXS=()=>{};KXS();var wf_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},EQo=2147483647,Ef_=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,SQo=Symbol("stop"),Sf_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Mf_={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 JXS=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Ef_,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${r}"`).length,t+=typeof i=="string"?new TextEncoder().encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e=="string")return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},Df_=(e,t,r)=>{let i,n=0;return e.pipeThrough(new TransformStream({transform(a,o){if(o.enqueue(a),i){n+=i.byteLength;let c=t===0?0:n/t;c>=1&&(c=1-Number.EPSILON),r?.({percent:c,totalBytes:Math.max(t,n),transferredBytes:n},i)}i=a},flush(){i&&(n+=i.byteLength,r?.({percent:1,totalBytes:Math.max(t,n),transferredBytes:n},i))}}))},Bf_=(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(Df_(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},If_=(e,t,r)=>{if(!e.body)return e;let i=JXS(r??e.body);return new Request(e,{duplex:"half",body:Df_(e.body,i,t)})};var hQn=e=>e!==null&&typeof e=="object";var APa=(...e)=>{for(let t of e)if((!hQn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Auc({},...e)},guc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,o]of n.entries())i&&o==="undefined"||o===void 0?r.delete(a):r.set(a,o);return r};function MQo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Auc(e[r]??[],t[r]??[])}var Ouc=(e={},t={})=>({beforeRequest:MQo(e,t,"beforeRequest"),beforeRetry:MQo(e,t,"beforeRetry"),afterResponse:MQo(e,t,"afterResponse"),beforeError:MQo(e,t,"beforeError")}),Auc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(hQn(n)){for(let[a,o]of Object.entries(n))hQn(o)&&a in t&&(o=Auc(t[a],o)),t={...t,[a]:o};hQn(n.hooks)&&(i=Ouc(i,n.hooks),t.hooks=i),hQn(n.headers)&&(r=guc(r,n.headers),t.headers=r)}return t};var qf_=e=>wQo.includes(e)?e.toUpperCase():e,$XS=["get","put","head","delete","options","trace"],YXS=[408,413,429,500,502,503,504],XXS=[413,429,503],Cf_={limit:2,methods:$XS,statusCodes:YXS,afterStatusCodes:XXS,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Tf_=(e={})=>{if(typeof e=="number")return{...Cf_,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{...Cf_,...e}};async function muc(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new _Qn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function Puc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var Rf_=(e,t)=>{let r={};for(let i in t)!(i in Mf_)&&!(i in Sf_)&&!(i in e)&&(r[i]=t[i]);return r},zf_=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 mPa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>EQo)throw new RangeError(`The \`timeout\` option cannot be greater than ${EQo}`);await Promise.resolve();let c=await i._fetch();for(let f of i._options.hooks.afterResponse){let s=await f(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let f=new OPa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)f=await s(f);throw f}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Pf_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return Bf_(c.clone(),i._options.onDownloadProgress)}return c},o=(i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n()).finally(async()=>{let c=i._originalRequest,f=[];c&&!c.bodyUsed&&f.push(c.body?.cancel()),i.request.bodyUsed||f.push(i.request.body?.cancel()),await Promise.all(f)});for(let[c,f]of Object.entries(wf_))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||f);let s=await o;if(c==="json"){if(s.status===204)return"";let u=await s.text();return u===""?"":r.parseJson?r.parseJson(u):JSON.parse(u)}return s[c]()});return o}static#e(t){return t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof URLSearchParams)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t}request;abortController;_retryCount=0;_input;_options;_originalRequest;constructor(t,r={}){if(this._input=t,this._options={...r,headers:guc(this._input.headers,r.headers),hooks:Ouc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:qf_(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:Tf_(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(Af_&&mf_){let i=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=i?AbortSignal.any([i,this.abortController.signal]):this.abortController.signal}if(vuc&&(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),zf_(this._options.searchParams)){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(e.#e(this._options.searchParams)).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(jf_&&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(!vuc)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=If_(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof _Qn)throw t;if(t instanceof OPa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),EQo);if(this._retryCount<1)throw r;await Puc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===SQo)return;return this._retry(t)}}async _fetch(){for(let r of this._options.hooks.beforeRequest){let i=await r(this.request,this._options);if(i instanceof Request){this.request=i;break}if(i instanceof Response)return i}let t=Rf_(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):muc(this._originalRequest,t,this.abortController,this._options)}};var juc=e=>{let t=(r,i)=>mPa.create(r,APa(e,i));for(let r of wQo)t[r]=(i,n)=>mPa.create(i,APa(e,n,{method:r}));return t.create=r=>juc(APa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),juc(APa(e,r))),t.stop=SQo,t},ZXS=juc(),Nf_=ZXS;var od_=ue(ad_(),1);function Duc(e){let t=(0,od_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var ep_=ue(kd_(),1),tp_=ue(O_e(),1),Vuc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Wuc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function xuc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Duc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,ep_.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 Nf_(o,{headers:f,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new Vuc(e):l}if(t.allVersions)return s;let u=new Wuc(e,r);if(s["dist-tags"][r]){let{time:l}=s;s=s.versions[s["dist-tags"][r]],s.time=l}else if(r){let l=!!s.versions[r];if(i&&!l)for(let[_,h]of Object.entries(s.versions))h.deprecated&&delete s.versions[_];if(!l){let _=Object.keys(s.versions);if(r=tp_.default.maxSatisfying(_,r),!r)throw u}let{time:p}=s;if(s=s.versions[r],s.time=p,!s)throw u}return s}async function MPa(e,t){let{version:r}=await xuc(e.toLowerCase(),t);return r}async function SCi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:MPa(e.packageName,{version:t?"prerelease":"latest"})}var rp_=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],UQo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Js.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new PQo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.15.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Ut.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new TE}failWithoutThrowing(t,r){this.didSucceed=!1,OQo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await fTn()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await vf_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1395
1395
  `)||(r+=`
1396
1396
  `),this.stderr.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram({code:t}={}){process.exit(t??(this.didSucceed?0:1))}longestWorkspaceName;registerWorkspaces(t){let r=Xjs(t.map(i=>i.type==="docs"?"docs":i.workspaceName??"api"),i=>i.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new _Pa(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let i=this.addTaskWithInit(t).start(),n;try{n=await r(i)}catch(a){throw a.message.includes("globalThis")?(i.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),i.failWithoutThrowing()):i.failWithoutThrowing(void 0,a),new TE}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await fTn()).sendEvent(t)}logger=G8t((t,...r)=>this.log(t,...r));stderr=G8t((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=ip_(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?ip_(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=rp_[this.numTasks++%rp_.length],o=Ut.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===yj.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let i=t.filter(n=>eMi.indexOf(n.level)>=eMi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===Js.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 SCi({cliEnvironment:this.environment,includePreReleases:t}),i=XH(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await jQo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await auc({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Ut.yellow("?"),style:{answer:n=>Ut.cyan(n),message:n=>Ut.bold(n),highlight:n=>Ut.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
1397
1397
  Cancelled by user.`),new TE):i}}async getInput(t){return await tuc({message:t.message,default:t.default})}};function ip_(e){return`[${e}]:`}var pFt=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};function LQo(e,t,r,i){if(typeof r!="function")throw new Error("method for before hook must be a function");return i||(i={}),Array.isArray(t)?t.reverse().reduce((n,a)=>LQo.bind(null,e,a,n,i),r)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((n,a)=>a.hook.bind(null,n,i),r)():r(i))}function np_(e,t,r,i){let n=i;e.registry[r]||(e.registry[r]=[]),t==="before"&&(i=(a,o)=>Promise.resolve().then(n.bind(null,o)).then(a.bind(null,o))),t==="after"&&(i=(a,o)=>{let c;return Promise.resolve().then(a.bind(null,o)).then(f=>(c=f,n(c,o))).then(()=>c)}),t==="error"&&(i=(a,o)=>Promise.resolve().then(a.bind(null,o)).catch(c=>n(c,o))),e.registry[r].push({hook:i,orig:n})}function ap_(e,t,r){if(!e.registry[t])return;let i=e.registry[t].map(n=>n.orig).indexOf(r);i!==-1&&e.registry[t].splice(i,1)}var op_=Function.bind,up_=op_.bind(op_);function sp_(e,t,r){let i=up_(ap_,null).apply(null,r?[t,r]:[t]);e.api={remove:i},e.remove=i,["before","error","after","wrap"].forEach(n=>{let a=r?[t,n,r]:[t,n];e[n]=e.api[n]=up_(np_,null).apply(null,a)})}function n2S(){let e=Symbol("Singular"),t={registry:{}},r=LQo.bind(null,t,e);return sp_(r,t,e),r}function a2S(){let e={registry:{}},t=LQo.bind(null,e);return sp_(t,e),t}var cp_={Singular:n2S,Collection:a2S};var o2S="0.0.0-development",u2S=`octokit-endpoint.js/${o2S} ${BR()}`,s2S={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":u2S},mediaType:{format:""}};function c2S(e){return e?Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{}):{}}function l2S(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}function dp_(e,t){let r=Object.assign({},e);return Object.keys(t).forEach(i=>{l2S(t[i])?i in e?r[i]=dp_(e[i],t[i]):Object.assign(r,{[i]:t[i]}):Object.assign(r,{[i]:t[i]})}),r}function lp_(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function Huc(e,t,r){if(typeof t=="string"){let[n,a]=t.split(" ");r=Object.assign(a?{method:n,url:a}:{url:n},r)}else r=Object.assign({},t);r.headers=c2S(r.headers),lp_(r),lp_(r.headers);let i=dp_(e||{},r);return r.url==="/graphql"&&(e&&e.mediaType.previews?.length&&(i.mediaType.previews=e.mediaType.previews.filter(n=>!i.mediaType.previews.includes(n)).concat(i.mediaType.previews)),i.mediaType.previews=(i.mediaType.previews||[]).map(n=>n.replace(/-preview/,""))),i}function f2S(e,t){let r=/\?/.test(e)?"&":"?",i=Object.keys(t);return i.length===0?e:e+r+i.map(n=>n==="q"?"q="+t.q.split("+").map(encodeURIComponent).join("+"):`${n}=${encodeURIComponent(t[n])}`).join("&")}var d2S=/\{[^{}}]+\}/g;function p2S(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function _2S(e){let t=e.match(d2S);return t?t.map(p2S).reduce((r,i)=>r.concat(i),[]):[]}function fp_(e,t){let r={__proto__:null};for(let i of Object.keys(e))t.indexOf(i)===-1&&(r[i]=e[i]);return r}function pp_(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map(function(t){return/%[0-9A-Fa-f]/.test(t)||(t=encodeURI(t).replace(/%5B/g,"[").replace(/%5D/g,"]")),t}).join("")}function PQn(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}function DPa(e,t,r){return t=e==="+"||e==="#"?pp_(t):PQn(t),r?PQn(r)+"="+t:t}function mQn(e){return e!=null}function Guc(e){return e===";"||e==="&"||e==="?"}function h2S(e,t,r,i){var n=e[r],a=[];if(mQn(n)&&n!=="")if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")n=n.toString(),i&&i!=="*"&&(n=n.substring(0,parseInt(i,10))),a.push(DPa(t,n,Guc(t)?r:""));else if(i==="*")Array.isArray(n)?n.filter(mQn).forEach(function(o){a.push(DPa(t,o,Guc(t)?r:""))}):Object.keys(n).forEach(function(o){mQn(n[o])&&a.push(DPa(t,n[o],o))});else{let o=[];Array.isArray(n)?n.filter(mQn).forEach(function(c){o.push(DPa(t,c))}):Object.keys(n).forEach(function(c){mQn(n[c])&&(o.push(PQn(c)),o.push(DPa(t,n[c].toString())))}),Guc(t)?a.push(PQn(r)+"="+o.join(",")):o.length!==0&&a.push(o.join(","))}else t===";"?mQn(n)&&a.push(PQn(r)):n===""&&(t==="&"||t==="?")?a.push(PQn(r)+"="):n===""&&a.push("");return a}function y2S(e){return{expand:b2S.bind(null,e)}}function b2S(e,t){var r=["+","#",".","/",";","?","&"];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(i,n,a){if(n){let c="",f=[];if(r.indexOf(n.charAt(0))!==-1&&(c=n.charAt(0),n=n.substr(1)),n.split(/,/g).forEach(function(s){var u=/([^:\*]*)(?::(\d+)|(\*))?/.exec(s);f.push(h2S(t,c,u[1],u[2]||u[3]))}),c&&c!=="+"){var o=",";return c==="?"?o="&":c!=="#"&&(o=c),(f.length!==0?c:"")+f.join(o)}else return f.join(",")}else return pp_(a)}),e==="/"?e:e.replace(/\/$/,"")}function _p_(e){let t=e.method.toUpperCase(),r=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),i=Object.assign({},e.headers),n,a=fp_(e,["method","baseUrl","url","headers","request","mediaType"]),o=_2S(r);r=y2S(r).expand(a),/^http/.test(r)||(r=e.baseUrl+r);let c=Object.keys(e).filter(u=>o.includes(u)).concat("baseUrl"),f=fp_(a,c);if(!/application\/octet-stream/i.test(i.accept)&&(e.mediaType.format&&(i.accept=i.accept.split(/,/).map(u=>u.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`)).join(",")),r.endsWith("/graphql")&&e.mediaType.previews?.length)){let u=i.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g)||[];i.accept=u.concat(e.mediaType.previews).map(l=>{let p=e.mediaType.format?`.${e.mediaType.format}`:"+json";return`application/vnd.github.${l}-preview${p}`}).join(",")}return["GET","HEAD"].includes(t)?r=f2S(r,f):"data"in f?n=f.data:Object.keys(f).length&&(n=f),!i["content-type"]&&typeof n<"u"&&(i["content-type"]="application/json; charset=utf-8"),["PATCH","PUT"].includes(t)&&typeof n>"u"&&(n=""),Object.assign({method:t,url:r,headers:i},typeof n<"u"?{body:n}:null,e.request?{request:e.request}:null)}function v2S(e,t,r){return _p_(Huc(e,t,r))}function hp_(e,t){let r=Huc(e,t),i=v2S.bind(null,r);return Object.assign(i,{DEFAULTS:r,defaults:hp_.bind(null,r),merge:Huc.bind(null,r),parse:_p_})}var yp_=hp_(null,s2S);var mp_=ue(Op_(),1);var _Ft=class extends Error{name;status;request;response;constructor(t,r,i){super(t),this.name="HttpError",this.status=Number.parseInt(r),Number.isNaN(this.status)&&(this.status=0),"response"in i&&(this.response=i.response);let n=Object.assign({},i.request);i.request.headers.authorization&&(n.headers=Object.assign({},i.request.headers,{authorization:i.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),n.url=n.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=n}};var g2S="10.0.6",O2S={headers:{"user-agent":`octokit-request.js/${g2S} ${BR()}`}};function A2S(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}async function Ap_(e){let t=e.request?.fetch||globalThis.fetch;if(!t)throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");let r=e.request?.log||console,i=e.request?.parseSuccessResponseBody!==!1,n=A2S(e.body)||Array.isArray(e.body)?JSON.stringify(e.body):e.body,a=Object.fromEntries(Object.entries(e.headers).map(([l,p])=>[l,String(p)])),o;try{o=await t(e.url,{method:e.method,body:n,redirect:e.request?.redirect,headers:a,signal:e.request?.signal,...e.body&&{duplex:"half"}})}catch(l){let p="Unknown Error";if(l instanceof Error){if(l.name==="AbortError")throw l.status=500,l;p=l.message,l.name==="TypeError"&&"cause"in l&&(l.cause instanceof Error?p=l.cause.message:typeof l.cause=="string"&&(p=l.cause))}let _=new _Ft(p,500,{request:e});throw _.cause=l,_}let c=o.status,f=o.url,s={};for(let[l,p]of o.headers)s[l]=p;let u={url:f,status:c,headers:s,data:""};if("deprecation"in s){let l=s.link&&s.link.match(/<([^<>]+)>; rel="deprecation"/),p=l&&l.pop();r.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${s.sunset}${p?`. See ${p}`:""}`)}if(c===204||c===205)return u;if(e.method==="HEAD"){if(c<400)return u;throw new _Ft(o.statusText,c,{response:u,request:e})}if(c===304)throw u.data=await Kuc(o),new _Ft("Not modified",c,{response:u,request:e});if(c>=400)throw u.data=await Kuc(o),new _Ft(P2S(u.data),c,{response:u,request:e});return u.data=i?await Kuc(o):o.body,u}async function Kuc(e){let t=e.headers.get("content-type");if(!t)return e.text().catch(()=>"");let r=(0,mp_.safeParse)(t);if(m2S(r)){let i="";try{return i=await e.text(),JSON.parse(i)}catch{return i}}else return r.type.startsWith("text/")||r.parameters.charset?.toLowerCase()==="utf-8"?e.text().catch(()=>""):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function m2S(e){return e.type==="application/json"||e.type==="application/scim+json"}function P2S(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return"Unknown error";if("message"in e){let t="documentation_url"in e?` - ${e.documentation_url}`:"";return Array.isArray(e.errors)?`${e.message}: ${e.errors.map(r=>JSON.stringify(r)).join(", ")}${t}`:`${e.message}${t}`}return`Unknown error: ${JSON.stringify(e)}`}function Juc(e,t){let r=e.defaults(t);return Object.assign(function(n,a){let o=r.merge(n,a);if(!o.request||!o.request.hook)return Ap_(r.parse(o));let c=(f,s)=>Ap_(r.parse(r.merge(f,s)));return Object.assign(c,{endpoint:r,defaults:Juc.bind(null,r)}),o.request.hook(c,o)},{endpoint:r,defaults:Juc.bind(null,r)})}var VO=Juc(yp_,O2S);var j2S="0.0.0-development";function w2S(e){return`Request failed due to following response errors:
@@ -1765,7 +1765,7 @@ ${i.map(a=>` ${a}`).join(`,
1765
1765
  `)}
1766
1766
  ]`;case 1:return`${n} Did you mean ${r[0]}?`;case 2:return`${n} Did you mean ${r[0]} or ${r[1]}?`;default:return`${n} Did you mean ${r[0]}, ${r[1]}, or ${r[2]}?`}}function m9o(e){return`API section ${e} is specified multiple times, however will be only rendered once.`}function jNM(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function P9o({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)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),p=c.isResponseStream?c:u,_=c.isResponseStream?u:c,h={id:It.V1.NodeId(`${n}:${_.endpointId}+${p.endpointId}`),type:"endpointPair",stream:p,nonStream:_};a[l]=h}),a}function Rz_({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return P9o({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(o=>o.type==="apiPackage"?o.children.length>0:!0)}function mLn(e,t){if(t!=null)return nb(e.absoluteFilePath,t)}function zz_({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:o,resolveIconFileId:c}){let f=It.V1.PageId(mLn(e,t.absolutePath)),s=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??Rw(t.title)});return{id:i.get(f),type:"page",pageId:f,title:t.title,slug:s.get(),icon:c?c(t.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 j9o=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;markdownFilesToTags;workspace;hideChildren;parentAvailability;openApiTags;apiDefinitionId;#e;#t=new Set;#r=new Set;#i=new Set;#n=new Set;#a=new Set;#o=new Map;#s=[];#u;#c;#f;disableEndpointPairs;collectedFileIds=new Map;#p;constructor(t,r,i,n,a,o,c,f,s,u,l,p,_,h){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=o,this.markdownFilesToNoIndex=c,this.markdownFilesToTags=f,this.workspace=l,this.hideChildren=p,this.parentAvailability=_,this.openApiTags=h,this.#p=new Map,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=It.V1.ApiDefinitionId(r.id),this.#e=s1i.create(r,a),this.collectedFileIds=u,this.#f=s,this.#u=this.apiSection.overviewAbsolutePath!=null?It.V1.PageId(mLn(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let y=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#c=i.apply({fullSlug:y?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Rw(this.apiSection.title)});let b=this.apiSection.availability??this.parentAvailability;this.apiSection.navigation!=null&&(this.#s=this.#d(this.apiSection.navigation,this.#e.api.rootPackage,this.#c,b)),this.#s=this.#g(this.#s.map(v=>this.#A(v,b)),this.#m(this.#e.api.rootPackage,this.#c,b))}get(){let t=It.V1.followRedirects(this.#s),r=new q$i(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.workspace?.changelog?.files.map(i=>i.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.resolveIconFileId(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.#P(this.apiSection.playground),postmanCollectionUrl:this.apiSection.postman,authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}getTagDescriptionContent(){return this.#p}createTagDescriptionPageId(t){if(!this.apiSection.tagDescriptionPages||!this.openApiTags)return;let r=UFt(t)?t.name:void 0;if(!r)return;let i=this.openApiTags[r];if(!i||!i.description)return;let n=`tag-${r}.md`,a=Fr.of(`/${n}`),o=It.V1.PageId(n),c=`# ${I$i(i.id.replace(/[_-]/g," "))}
1767
1767
 
1768
- ${i.description}`;return this.#p.set(a,c),this.markdownFilesToNoIndex.set(a,!1),this.markdownFilesToTags.set(a,[r]),o}#d(t,r,i,n){r=this.#e.resolveSubpackage(r);let a=r!=null?s1i.getSubpackageId(r):void 0;return t.map(o=>Ivc(o)._visit({link:c=>({id:this.#f.get(c.url),type:"link",title:c.text,icon:this.resolveIconFileId(c.icon),url:It.Url(c.url),target:c.target}),page:c=>this.#l(c,i,n),package:c=>this.#_(c,i,n),section:c=>this.#y(c,i,n),item:({value:c})=>this.#h(c,a,i,n),endpoint:c=>this.#O(c,a,i,n)})).filter(Zu)}#l(t,r,i){return zz_({page:{...t,availability:t.availability??i},parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#f,hideChildren:this.hideChildren,resolveIconFileId:this.resolveIconFileId.bind(this)})}#_(t,r,i){let n=t.overviewAbsolutePath!=null?It.V1.PageId(mLn(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.availability??i,c=this.#e.getSubpackageByIdOrLocator(t.package);if(c!=null){let f=s1i.getSubpackageId(c),s=this.#f.get(n??`${this.apiDefinitionId}:${f}`);this.#a.has(f)&&this.taskContext.logger.warn(m9o(t.package)),this.#a.add(f),this.#o.set(s,[f]);let u=t.slug??(UFt(c)?c.urlSlug:this.apiSection.slug??Rw(this.apiSection.title)),l=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),p=this.#d(t.contents,c,l,o);return{id:s,type:"apiPackage",children:p,title:t.title??(UFt(c)?c.displayName??I$i(c.name):this.apiSection.title),slug:l.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(A9o(t.package,this.#e.subpackageLocators));let f=t.slug??Rw(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(n??`${this.apiDefinitionId}:${Rw(t.package)}`),type:"apiPackage",children:u,title:t.title??t.package,slug:s.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#y(t,r,i){let n=t.overviewAbsolutePath!=null?It.V1.PageId(mLn(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(n??a??r.get()),f=t.referencedSubpackages.map(_=>{let h=this.#e.getSubpackageByIdOrLocator(_),y=h!=null?s1i.getSubpackageId(h):void 0;if(y===void 0){this.taskContext.logger.error(A9o(_,this.#e.subpackageLocators));return}return{subpackageId:y,locator:_}}).filter(_=>_!=null).filter(Zu);this.#o.set(c,f.map(_=>_.subpackageId)),f.forEach(_=>{this.#a.has(_.subpackageId)&&this.taskContext.logger.error(m9o(_.locator)),this.#a.add(_.subpackageId)});let s=t.slug??Rw(t.title),u=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:s}),l=t.availability??i,p=this.#d(t.contents,void 0,u,l);return{id:c,type:"apiPackage",children:p,title:t.title,slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:l,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:o,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#h(t,r,i,n){t=t.trim();let a=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(Fo(t));if(a!=null){let o=s1i.getSubpackageId(a),c=this.#f.get(`${this.apiDefinitionId}:${o}`);this.#a.has(o)&&this.taskContext.logger.error(m9o(t)),this.#a.add(o),this.#o.set(c,[o]);let f=UFt(a)?a.urlSlug:"",s=i.apply({urlSlug:f});return{id:c,type:"apiPackage",children:[],title:UFt(a)?a.displayName??I$i(a.name):this.apiSection.title,slug:s.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:this.createTagDescriptionPageId(a),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}}return this.#O({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,i,n)}#O(t,r,i,n){let a=(r!=null?this.#e.subpackages.get(oQ.SubpackageId(r))?.endpoints.get(oQ.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: ${O9o(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?i.append(t.slug):i.apply(a);return{id:this.#f.get(`${this.apiDefinitionId}:${f}`),type:"endpoint",method:a.method,endpointId:f,apiDefinitionId:this.apiDefinitionId,availability:t.availability??It.V1.convertAvailability(a.availability)??n,isResponseStream:a.response?.type.type==="stream",title:t.title??a.name??f8(a.path.parts),slug:s.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,playground:this.#P(a.includeInApiExplorer===!1?{...t.playground,hidden:!0}:t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let o=(r!=null?this.#e.subpackages.get(oQ.SubpackageId(r))?.webSockets.get(oQ.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??f8(o.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(o)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:It.V1.convertAvailability(o.availability)??n,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let c=(r!=null?this.#e.subpackages.get(oQ.SubpackageId(r))?.webhooks.get(oQ.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(It.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.#i.has(f)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${f}`),this.#i.add(f),{id:this.#f.get(`${this.apiDefinitionId}:${f}`),type:"webhook",webhookId:f,method:c.method,title:t.title??c.name??(0,Nz_.default)("/",...c.path),slug:(t.slug!=null?i.append(t.slug):i.apply(c)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:n,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 Rz_({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>f8(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#A(t,r){return Tvc({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(i,n,a)=>this.#v(i,n,a),mergeAndFilterChildren:this.#g.bind(this)})}#m(t,r,i){let n=[];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: ${O9o(a.method,a.path.parts)}. Got undefined.`);return}if(this.#n.has(o))return;let c=r.apply(a);n.push({id:It.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"grpc",grpcId:o,title:a.name??f8(a.path.parts),method:a.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:i,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: ${O9o(a.method,a.path.parts)}. Got undefined.`);return}if(this.#t.has(o))return;let c=r.apply(a);n.push({id:It.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"endpoint",method:a.method,endpointId:o,apiDefinitionId:this.apiDefinitionId,availability:It.V1.convertAvailability(a.availability)??i,isResponseStream:a.response?.type.type==="stream",title:a.name??f8(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)||n.push({id:It.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webSocket",webSocketId:o,title:a.name??f8(a.path.parts),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:It.V1.convertAvailability(a.availability)??i,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.#i.has(o)||n.push({id:It.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webhook",webhookId:o,method:a.method,title:a.name??I$i(a.id),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:i,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=UFt(o)?r.apply(o):r,f=this.#v(a,c,i);f.length>0&&n.push({id:It.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"apiPackage",children:f,title:UFt(o)?o.displayName??I$i(o.name):this.apiSection.title,slug:c.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:this.createTagDescriptionPageId(o),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})}),n=this.mergeEndpointPairs(n),this.apiSection.alphabetized&&(n=n.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)})),n}#v(t,r,i){let n=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return n==null?(this.taskContext.logger.debug(A9o(t||"unknown",[])),[]):this.#m(n,r,i)}#P(t){return Ez_(t)}mergeEndpointPairs(t){return P9o({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>f8(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}getFileId(t){let r=this.collectedFileIds.get(t);return r??this.taskContext.failAndThrow("Failed to locate file after uploading: "+t)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}};var Fz_=ue(require("crypto"),1);function wNM(e){return Fz_.default.createHash("sha256").update(e).digest("hex")}var w9o=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),wNM(r===0?t:`${t}-${r}`)}#i(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return It.V1.NodeId(this.#i(t))}};function Qz_(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 E9o=class{selectors;constructor(t){this.selectors=t}matches(t,r){for(let i of this.selectors)if(this.pathMatches(t,i.path)&&(!i.method||i.method===r))return!0;return!1}pathMatches(t,r){if(t===r)return!0;let i=t.split("/").filter(a=>a.length>0),n=r.split("/").filter(a=>a.length>0);if(i.length!==n.length)return!1;for(let a=0;a<i.length;a++){let o=i[a],c=n[a];if(!o||!c)return!1;let f=o.startsWith("{")&&o.endsWith("}"),s=c.startsWith("{")&&c.endsWith("}");if(!(f&&s)&&o!==c)return!1}return!0}getMatchingPaths(t){let r=[];for(let[i,n]of Object.entries(t)){if(!n)continue;let a=["get","put","post","delete","options","head","patch","trace"];for(let o of a)if(n[o]&&this.matches(i,o)){r.includes(i)||r.push(i);break}}return r}};var S9o=class{document;schemas=new Set;parameters=new Set;responses=new Set;requestBodies=new Set;securitySchemes=new Set;headers=new Set;examples=new Set;links=new Set;callbacks=new Set;constructor(t){this.document=t}collectFromOperation(t){if(t.parameters)for(let r of t.parameters)this.collectParameter(r);if(t.requestBody&&this.collectFromRequestBody(t.requestBody),t.responses)for(let r of Object.values(t.responses))this.collectFromResponse(r);if(t.callbacks)for(let[r,i]of Object.entries(t.callbacks))if(this.isReference(i))this.callbacks.add(this.extractComponentName(i.$ref));else for(let n of Object.values(i))this.collectFromPathItem(n);if(t.security)for(let r of t.security)for(let i of Object.keys(r))this.securitySchemes.add(i)}collectFromPathItem(t){if(t.parameters)for(let i of t.parameters)this.collectParameter(i);let r=[t.get,t.put,t.post,t.delete,t.options,t.head,t.patch,t.trace];for(let i of r)i&&this.collectFromOperation(i)}collectParameter(t){if(this.isReference(t)){this.parameters.add(this.extractComponentName(t.$ref));let r=this.resolveParameter(t.$ref);r&&this.collectParameter(r)}else{if(t.schema&&this.collectFromSchema(t.schema),t.content)for(let r of Object.values(t.content))this.collectFromMediaType(r);if(t.examples)for(let[r,i]of Object.entries(t.examples))this.isReference(i)&&this.examples.add(this.extractComponentName(i.$ref))}}collectFromRequestBody(t){if(this.isReference(t)){this.requestBodies.add(this.extractComponentName(t.$ref));let r=this.resolveRequestBody(t.$ref);r&&this.collectFromRequestBody(r)}else if(t.content)for(let r of Object.values(t.content))this.collectFromMediaType(r)}collectFromResponse(t){if(this.isReference(t)){this.responses.add(this.extractComponentName(t.$ref));let r=this.resolveResponse(t.$ref);r&&this.collectFromResponse(r)}else{if(t.headers)for(let[r,i]of Object.entries(t.headers))this.isReference(i)?this.headers.add(this.extractComponentName(i.$ref)):i.schema&&this.collectFromSchema(i.schema);if(t.content)for(let r of Object.values(t.content))this.collectFromMediaType(r);if(t.links)for(let[r,i]of Object.entries(t.links))this.isReference(i)&&this.links.add(this.extractComponentName(i.$ref))}}collectFromMediaType(t){if(t.schema&&this.collectFromSchema(t.schema),t.examples)for(let[r,i]of Object.entries(t.examples))this.isReference(i)&&this.examples.add(this.extractComponentName(i.$ref))}collectFromSchema(t){if(this.isReference(t)){let r=this.extractComponentName(t.$ref);if(!this.schemas.has(r)){this.schemas.add(r);let i=this.resolveSchema(t.$ref);i&&this.collectFromSchema(i)}}else{if(t.properties)for(let r of Object.values(t.properties))this.collectFromSchema(r);if(t.additionalProperties&&typeof t.additionalProperties=="object"&&this.collectFromSchema(t.additionalProperties),"items"in t&&t.items)if(Array.isArray(t.items))for(let r of t.items)this.collectFromSchema(r);else this.collectFromSchema(t.items);if(t.allOf)for(let r of t.allOf)this.collectFromSchema(r);if(t.oneOf)for(let r of t.oneOf)this.collectFromSchema(r);if(t.anyOf)for(let r of t.anyOf)this.collectFromSchema(r);t.not&&this.collectFromSchema(t.not)}}resolveSchema(t){let r=this.extractComponentName(t);return this.document.components?.schemas?.[r]}resolveParameter(t){let r=this.extractComponentName(t);return this.document.components?.parameters?.[r]}resolveResponse(t){let r=this.extractComponentName(t);return this.document.components?.responses?.[r]}resolveRequestBody(t){let r=this.extractComponentName(t);return this.document.components?.requestBodies?.[r]}isReference(t){return t!=null&&typeof t=="object"&&"$ref"in t}extractComponentName(t){let r=t.split("/");return r[r.length-1]??t}getSchemas(){return this.schemas}getParameters(){return this.parameters}getResponses(){return this.responses}getRequestBodies(){return this.requestBodies}getSecuritySchemes(){return this.securitySchemes}getHeaders(){return this.headers}getExamples(){return this.examples}getLinks(){return this.links}getCallbacks(){return this.callbacks}};var QEa=class{matcher;document;constructor(t){this.matcher=new E9o(t.endpoints),this.document=JSON.parse(JSON.stringify(t.document))}prune(){let t=this.collectStatistics(),r=new S9o(this.document),i={},n=this.matcher.getMatchingPaths(this.document.paths);for(let c of n){let f=this.document.paths[c];if(!f)continue;let s={};f.summary&&(s.summary=f.summary),f.description&&(s.description=f.description),f.servers&&(s.servers=f.servers),f.parameters&&(s.parameters=f.parameters);let u=["get","put","post","delete","options","head","patch","trace"];for(let l of u){let p=f[l];p&&this.matcher.matches(c,l)&&(s[l]=p,r.collectFromOperation(p))}if(f.parameters)for(let l of f.parameters)r.collectParameter(l);i[c]=s}let a={openapi:this.document.openapi,info:this.document.info,paths:i};if(this.document.servers&&(a.servers=this.document.servers),this.document.externalDocs&&(a.externalDocs=this.document.externalDocs),this.document.tags){let c=new Set;for(let f of Object.values(i)){let s=["get","put","post","delete","options","head","patch","trace"];for(let u of s){let l=f?.[u];if(l?.tags)for(let p of l.tags)c.add(p)}}a.tags=this.document.tags.filter(f=>c.has(f.name))}if(this.document.security){a.security=this.document.security;for(let c of this.document.security)for(let f of Object.keys(c))r.getSecuritySchemes().add(f)}a.components=this.buildPrunedComponents(r);let o=this.collectPrunedStatistics(a);return{document:a,statistics:{originalEndpoints:t.originalEndpoints,prunedEndpoints:o.originalEndpoints,originalSchemas:t.originalSchemas,prunedSchemas:o.originalSchemas,originalParameters:t.originalParameters,prunedParameters:o.originalParameters,originalResponses:t.originalResponses,prunedResponses:o.originalResponses,originalRequestBodies:t.originalRequestBodies,prunedRequestBodies:o.originalRequestBodies,originalSecuritySchemes:t.originalSecuritySchemes,prunedSecuritySchemes:o.originalSecuritySchemes}}}buildPrunedComponents(t){if(!this.document.components)return;let r={};if(this.document.components.schemas&&t.getSchemas().size>0){r.schemas={};for(let i of t.getSchemas()){let n=this.document.components.schemas[i];n&&(r.schemas[i]=n)}}if(this.document.components.parameters&&t.getParameters().size>0){r.parameters={};for(let i of t.getParameters()){let n=this.document.components.parameters[i];n&&(r.parameters[i]=n)}}if(this.document.components.responses&&t.getResponses().size>0){r.responses={};for(let i of t.getResponses()){let n=this.document.components.responses[i];n&&(r.responses[i]=n)}}if(this.document.components.requestBodies&&t.getRequestBodies().size>0){r.requestBodies={};for(let i of t.getRequestBodies()){let n=this.document.components.requestBodies[i];n&&(r.requestBodies[i]=n)}}if(this.document.components.securitySchemes&&t.getSecuritySchemes().size>0){r.securitySchemes={};for(let i of t.getSecuritySchemes()){let n=this.document.components.securitySchemes[i];n&&(r.securitySchemes[i]=n)}}if(this.document.components.headers&&t.getHeaders().size>0){r.headers={};for(let i of t.getHeaders()){let n=this.document.components.headers[i];n&&(r.headers[i]=n)}}if(this.document.components.examples&&t.getExamples().size>0){r.examples={};for(let i of t.getExamples()){let n=this.document.components.examples[i];n&&(r.examples[i]=n)}}if(this.document.components.links&&t.getLinks().size>0){r.links={};for(let i of t.getLinks()){let n=this.document.components.links[i];n&&(r.links[i]=n)}}if(this.document.components.callbacks&&t.getCallbacks().size>0){r.callbacks={};for(let i of t.getCallbacks()){let n=this.document.components.callbacks[i];n&&(r.callbacks[i]=n)}}return Object.keys(r).length>0?r:void 0}collectStatistics(){let t=0;for(let r of Object.values(this.document.paths)){if(!r)continue;let i=["get","put","post","delete","options","head","patch","trace"];for(let n of i)r[n]&&t++}return{originalEndpoints:t,prunedEndpoints:0,originalSchemas:Object.keys(this.document.components?.schemas??{}).length,prunedSchemas:0,originalParameters:Object.keys(this.document.components?.parameters??{}).length,prunedParameters:0,originalResponses:Object.keys(this.document.components?.responses??{}).length,prunedResponses:0,originalRequestBodies:Object.keys(this.document.components?.requestBodies??{}).length,prunedRequestBodies:0,originalSecuritySchemes:Object.keys(this.document.components?.securitySchemes??{}).length,prunedSecuritySchemes:0}}collectPrunedStatistics(t){let r=0;for(let i of Object.values(t.paths)){if(!i)continue;let n=["get","put","post","delete","options","head","patch","trace"];for(let a of n)i[a]&&r++}return{originalEndpoints:r,prunedEndpoints:0,originalSchemas:Object.keys(t.components?.schemas??{}).length,prunedSchemas:0,originalParameters:Object.keys(t.components?.parameters??{}).length,prunedParameters:0,originalResponses:Object.keys(t.components?.responses??{}).length,prunedResponses:0,originalRequestBodies:Object.keys(t.components?.requestBodies??{}).length,prunedRequestBodies:0,originalSecuritySchemes:Object.keys(t.components?.securitySchemes??{}).length,prunedSecuritySchemes:0}}};var Uvc=require("fs/promises");var M9o=class{config;context;lambdaOrigin;token;constructor(t,r,i){this.config={enabled:t.enabled,openaiApiKey:t.openaiApiKey,model:t.model??"gpt-4o-mini",maxRetries:t.maxRetries??1,requestTimeoutMs:75e3},this.context=r;let n="https://ykq45y6fvnszd35iv5yuuatkze0rpwuz.lambda-url.us-east-1.on.aws";if(!n)throw new Error("DEFAULT_FDR_LAMBDA_DOCS_ORIGIN environment variable is not set. AI example enhancement requires this to be configured.");this.lambdaOrigin=n,this.token=i}async enhanceExample(t){if(!this.config.enabled)return{enhancedRequestExample:t.originalRequestExample,enhancedResponseExample:t.originalResponseExample};let r;for(let i=1;i<=this.config.maxRetries;i++)try{this.context.logger.debug(`Enhancing example for ${t.method} ${t.endpointPath} via lambda (attempt ${i}/${this.config.maxRetries})`);let n={method:t.method,endpointPath:t.endpointPath,organizationId:t.organizationId,operationSummary:t.operationSummary,operationDescription:t.operationDescription,originalRequestExample:t.originalRequestExample,originalResponseExample:t.originalResponseExample,openApiSpec:t.openApiSpec};this.context.logger.debug(`Sending to enhanceExamples: ${JSON.stringify({...n,openApiSpec:t.openApiSpec?`[OpenAPI spec present: ${t.openApiSpec.length} chars]`:"[No OpenAPI spec]"},null,2)}`);let a=await fetch(`${this.lambdaOrigin}/v2/registry/ai/enhance-example`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token.value}`},body:JSON.stringify(n),signal:AbortSignal.timeout(this.config.requestTimeoutMs)});if(!a.ok){let c=await a.text();throw new Error(`Lambda returned ${a.status}: ${c||a.statusText}`)}let o=await a.json();return{enhancedRequestExample:o.enhancedRequestExample??t.originalRequestExample,enhancedResponseExample:o.enhancedResponseExample??t.originalResponseExample}}catch(n){if(r=n,this.context.logger.warn(`Attempt ${i} failed to enhance example: ${n}`),i<this.config.maxRetries){let a=Math.min(1e3*Math.pow(2,i-1),1e4);await new Promise(o=>setTimeout(o,a))}}return this.context.logger.error(`Failed to enhance example after ${this.config.maxRetries} attempts: ${r?.message}`),{enhancedRequestExample:t.originalRequestExample,enhancedResponseExample:t.originalResponseExample}}};var UEa=class e{static instance;currentApiId;queue=[];progress=new Map;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}create(t,r,i){let n=`${t}-${Date.now()}-${Math.random()}`;return this.progress.set(n,{apiName:t,completed:0,total:r,endpointsSample:i}),this.queue.push(n),this.currentApiId||(this.currentApiId=n,this.updateSpinnerStatus()),n}update(t,r){let i=this.progress.get(t);i&&(i.completed=r,t===this.currentApiId&&this.updateSpinnerStatus())}finish(t){this.progress.delete(t);let r=this.queue.indexOf(t);r!==-1&&this.queue.splice(r,1),t===this.currentApiId&&(this.queue.length>0?(this.currentApiId=this.queue[0],this.updateSpinnerStatus()):(this.currentApiId=void 0,delete process.env.FERN_SPINNER_STATUS))}updateSpinnerStatus(){if(!this.currentApiId){delete process.env.FERN_SPINNER_STATUS;return}let t=this.progress.get(this.currentApiId);if(t){let r=`auto-generating examples for endpoints - ${t.apiName}`;t.endpointsSample&&(r+=` (${t.endpointsSample})`),r+=` - ${t.completed}/${t.total}`,process.env.FERN_SPINNER_STATUS=r}}};var D9o=require("fs/promises");async function ENM(e,t){let r=Fr.of(`${Zi(e)}/ai_examples_override.yml`),i=[];try{let n=await(0,D9o.readFile)(r,"utf-8"),a=wi.load(n);if(a&&typeof a=="object"&&"paths"in a){let o=a.paths;for(let[c,f]of Object.entries(o))if(f&&typeof f=="object"){for(let[s,u]of Object.entries(f))if(u&&typeof u=="object"&&"x-fern-examples"in u){let l=u["x-fern-examples"];if(Array.isArray(l)){for(let p of l)if(typeof p=="object"&&p!==null){let _=p;i.push({endpointPath:c,method:s.toUpperCase(),pathParameters:_["path-parameters"],queryParameters:_["query-parameters"],headers:_.headers,request:_.request,response:_.response})}}}}}t.logger.debug(`Parsed ${i.length} AI examples from ai_examples_override.yml`)}catch(n){t.logger.debug(`No existing ai_examples_override.yml found or error reading it: ${n}`)}return i}async function zvc({sourceFilePath:e,context:t}){let r=await ENM(e,t);if(r.length===0)return{validExamples:[],invalidExamples:[],totalExamples:0,validCount:0,invalidCount:0};let i;try{let s=await(0,D9o.readFile)(e,"utf-8");try{i=JSON.parse(s)}catch{i=wi.load(s)}}catch(s){return t.logger.warn(`Failed to read OpenAPI spec file: ${s}`),{validExamples:r,invalidExamples:[],totalExamples:r.length,validCount:r.length,invalidCount:0}}let n=new T0e({logger:t.logger}),a=new jgi({namespace:void 0,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:i,exampleGenerationArgs:{disabled:!1},errorCollector:n,enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,settings:SFt()}),o=new zKi({context:a}),{validExamples:c,invalidExamples:f}=o.validateAiExamples({aiExamples:r,spec:i});if(f.length>0){t.logger.info(`Found ${f.length} stale AI examples that need to be regenerated out of ${r.length} total`);for(let{example:s,validationResult:u}of f)t.logger.debug(`Stale AI example: ${s.method} ${s.endpointPath} - ${u.errors.map(l=>l.message).join(", ")}`)}return{validExamples:c,invalidExamples:f,totalExamples:r.length,validCount:c.length,invalidCount:f.length}}async function Uz_({sourceFilePath:e,context:t}){let r=await zvc({sourceFilePath:e,context:t});if(r.invalidCount===0)return t.logger.debug("No invalid AI examples to remove"),{removedCount:0,remainingCount:r.totalExamples};let i=Fr.of(`${Zi(e)}/ai_examples_override.yml`);try{let n=await(0,D9o.readFile)(i,"utf-8"),a=wi.load(n);if(!a||!a.paths)return{removedCount:0,remainingCount:r.totalExamples};let o=new Set(r.invalidExamples.map(({example:s})=>`${s.method.toLowerCase()}:${s.endpointPath}`));for(let[s,u]of Object.entries(a.paths))if(u&&typeof u=="object"){for(let l of Object.keys(u)){let p=`${l.toLowerCase()}:${s}`;o.has(p)&&delete u[l]}Object.keys(u).length===0&&delete a.paths[s]}let{writeFile:c}=await import("fs/promises"),f=wi.dump(a,{indent:2,lineWidth:-1,noRefs:!0});return await c(i,f,"utf-8"),t.logger.info(`Removed ${r.invalidCount} invalid AI examples from ai_examples_override.yml`),{removedCount:r.invalidCount,remainingCount:r.validCount}}catch(n){return t.logger.warn(`Failed to remove invalid AI examples: ${n}`),{removedCount:0,remainingCount:r.totalExamples}}}var LEa=require("fs/promises");async function Nvc(e,t){let r=Fr.of(`${Zi(e)}/ai_examples_override.yml`),i=new Set;try{let n=await(0,LEa.readFile)(r,"utf-8"),a=wi.load(n);if(a&&typeof a=="object"&&"paths"in a){let o=a.paths;for(let[c,f]of Object.entries(o))if(f&&typeof f=="object")for(let s of Object.keys(f)){let u=`${s.toLowerCase()}:${c}`;i.add(u)}}t.logger.debug(`Loaded ${i.size} covered endpoints from ai_examples_override.yml`)}catch{t.logger.debug("No existing ai_examples_override.yml found or error reading it")}return i}async function Fvc({enhancedExamples:e,sourceFilePath:t,context:r}){if(e.length===0){r.logger.debug("No enhanced examples to write");return}let i=new Map;for(let o of e){let c=i.get(o.endpoint)||[];c.push(o),i.set(o.endpoint,c)}let n={paths:{}};for(let[o,c]of i.entries()){let f=new Map;for(let s of c){let u=f.get(s.method.toLowerCase())||[];u.push(s),f.set(s.method.toLowerCase(),u)}n.paths[o]||(n.paths[o]={});for(let[s,u]of f.entries()){let l=u.map((_,h)=>{let y={};return _.pathParameters&&Object.keys(_.pathParameters).length>0&&(y["path-parameters"]=_.pathParameters),_.queryParameters&&Object.keys(_.queryParameters).length>0&&(y["query-parameters"]=_.queryParameters),_.headers&&Object.keys(_.headers).length>0&&(y.headers=_.headers),_.requestBody!==void 0&&(y.request={body:_.requestBody}),_.responseBody!==void 0&&(y.response={body:_.responseBody}),y}),p=n.paths[o];p&&(p[s]={"x-fern-examples":l})}}let a=Fr.of(`${Zi(t)}/ai_examples_override.yml`);try{let o={};try{let s=await(0,LEa.readFile)(a,"utf-8"),u=wi.load(s);u&&typeof u=="object"&&(o=u)}catch{r.logger.debug("No existing ai_examples_override.yml found, creating new file")}let c={paths:{}};if(o.paths){for(let[s,u]of Object.entries(o.paths))if(u&&typeof u=="object"){c.paths[s]={};for(let[l,p]of Object.entries(u))p&&typeof p=="object"&&"x-fern-examples"in p&&(c.paths[s][l]={"x-fern-examples":p["x-fern-examples"]||[]})}}for(let[s,u]of Object.entries(n.paths)){c.paths[s]||(c.paths[s]={});for(let[l,p]of Object.entries(u))c.paths[s][l]?r.logger.debug(`Skipping ${l.toUpperCase()} ${s} - examples already exist in override file`):(c.paths[s][l]=p,r.logger.debug(`Adding new examples for ${l.toUpperCase()} ${s}`))}let f=wi.dump(c,{indent:2,lineWidth:-1,noRefs:!0});await(0,LEa.writeFile)(a,f,"utf-8"),r.logger.debug(`AI enhanced examples written to: ${a}`)}catch(o){throw r.logger.warn(`Failed to write AI examples override file: ${o}`),o}}var Qvc=class{failureCount=0;failureThreshold=30;isOpen=!1;recordFailure(){this.failureCount++,this.failureCount>=this.failureThreshold&&(this.isOpen=!0)}recordSuccess(){this.failureCount=0,this.isOpen=!1}shouldSkip(){return this.isOpen}getFailureCount(){return this.failureCount}getThreshold(){return this.failureThreshold}},Lz_=!1;function SNM(e){try{try{let t=JSON.parse(e);return!!(t.openapi||t.swagger)}catch{let t=ZDn(e);return!!(t?.openapi||t?.swagger)}}catch{return!1}}function MNM(e,t){if(t.includes(e))return e;for(let r of t){let i=r.replace(/\{[^}]+\}/g,"([^/]+)");if(new RegExp(`^${i}$`).test(e))return r}}async function DNM(e,t,r){try{let i;try{i=JSON.parse(e)}catch{i=ZDn(e)}if(!i.openapi||!i.paths){r.logger.debug("Invalid OpenAPI spec structure, skipping pruning");return}let n=Object.keys(i.paths);r.logger.debug(`OpenAPI spec contains ${n.length} paths`);let a=[];for(let l of t){let p=MNM(l.path,n);p?(a.push({path:p,method:l.method.toLowerCase()}),r.logger.debug(`Mapped ${l.path} to OpenAPI path: ${p}`)):r.logger.debug(`No matching OpenAPI path found for ${l.path}`)}if(a.length===0){r.logger.debug("No endpoints matched in OpenAPI spec");return}let c=new QEa({document:i,endpoints:a}).prune();r.logger.debug(`Pruned OpenAPI spec for batch: ${c.statistics.originalEndpoints} \u2192 ${c.statistics.prunedEndpoints} endpoints, ${c.statistics.originalSchemas} \u2192 ${c.statistics.prunedSchemas} schemas`);let f=JSON.stringify(c.document,null,2);if(f.length>15e5){r.logger.debug(`Pruned OpenAPI spec still too large (${f.length} characters), skipping spec context for AI enhancement`);return}r.logger.debug(`Pruned spec size: ${f.length} characters (within limit)`);let s=a.map(l=>`${(l.method||"unknown").toUpperCase()}_${l.path.replace(/\//g,"_").replace(/[{}]/g,"")}`),u=`batch_${a.length}endpoints_${s.join("_").substring(0,100)}_pruned_spec.yaml`;return f}catch(i){return r.logger.debug(`Failed to prune OpenAPI spec: ${i}. Using original spec.`),e}}async function jLn(e,t,r,i,n,a,o){if(!t.enabled)return r.logger.debug("AI example enhancement is disabled"),e;if(!Lz_){let y=Ut.blue(`Notice: new feature added (experimental)!
1768
+ ${i.description}`;return this.#p.set(a,c),this.markdownFilesToNoIndex.set(a,!1),this.markdownFilesToTags.set(a,[r]),o}#d(t,r,i,n){r=this.#e.resolveSubpackage(r);let a=r!=null?s1i.getSubpackageId(r):void 0;return t.map(o=>Ivc(o)._visit({link:c=>({id:this.#f.get(c.url),type:"link",title:c.text,icon:this.resolveIconFileId(c.icon),url:It.Url(c.url),target:c.target}),page:c=>this.#l(c,i,n),package:c=>this.#_(c,i,n),section:c=>this.#y(c,i,n),item:({value:c})=>this.#h(c,a,i,n),endpoint:c=>this.#O(c,a,i,n)})).filter(Zu)}#l(t,r,i){return zz_({page:{...t,availability:t.availability??i},parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#f,hideChildren:this.hideChildren,resolveIconFileId:this.resolveIconFileId.bind(this)})}#_(t,r,i){let n=t.overviewAbsolutePath!=null?It.V1.PageId(mLn(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.availability??i,c=this.#e.getSubpackageByIdOrLocator(t.package);if(c!=null){let f=s1i.getSubpackageId(c),s=this.#f.get(n??`${this.apiDefinitionId}:${f}`);this.#a.has(f)&&this.taskContext.logger.warn(m9o(t.package)),this.#a.add(f),this.#o.set(s,[f]);let u=t.slug??(UFt(c)?c.urlSlug:this.apiSection.slug??Rw(this.apiSection.title)),l=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),p=this.#d(t.contents,c,l,o);return{id:s,type:"apiPackage",children:p,title:t.title??(UFt(c)?c.displayName??I$i(c.name):this.apiSection.title),slug:l.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(A9o(t.package,this.#e.subpackageLocators));let f=t.slug??Rw(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(n??`${this.apiDefinitionId}:${Rw(t.package)}`),type:"apiPackage",children:u,title:t.title??t.package,slug:s.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#y(t,r,i){let n=t.overviewAbsolutePath!=null?It.V1.PageId(mLn(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(n??a??r.get()),f=t.referencedSubpackages.map(_=>{let h=this.#e.getSubpackageByIdOrLocator(_),y=h!=null?s1i.getSubpackageId(h):void 0;if(y===void 0){this.taskContext.logger.error(A9o(_,this.#e.subpackageLocators));return}return{subpackageId:y,locator:_}}).filter(_=>_!=null).filter(Zu);this.#o.set(c,f.map(_=>_.subpackageId)),f.forEach(_=>{this.#a.has(_.subpackageId)&&this.taskContext.logger.error(m9o(_.locator)),this.#a.add(_.subpackageId)});let s=t.slug??Rw(t.title),u=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:s}),l=t.availability??i,p=this.#d(t.contents,void 0,u,l);return{id:c,type:"apiPackage",children:p,title:t.title,slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:l,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:o,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#h(t,r,i,n){t=t.trim();let a=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(Fo(t));if(a!=null){let o=s1i.getSubpackageId(a),c=this.#f.get(`${this.apiDefinitionId}:${o}`);this.#a.has(o)&&this.taskContext.logger.error(m9o(t)),this.#a.add(o),this.#o.set(c,[o]);let f=UFt(a)?a.urlSlug:"",s=i.apply({urlSlug:f});return{id:c,type:"apiPackage",children:[],title:UFt(a)?a.displayName??I$i(a.name):this.apiSection.title,slug:s.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:this.createTagDescriptionPageId(a),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}}return this.#O({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,i,n)}#O(t,r,i,n){let a=(r!=null?this.#e.subpackages.get(oQ.SubpackageId(r))?.endpoints.get(oQ.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: ${O9o(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?i.append(t.slug):i.apply(a);return{id:this.#f.get(`${this.apiDefinitionId}:${f}`),type:"endpoint",method:a.method,endpointId:f,apiDefinitionId:this.apiDefinitionId,availability:t.availability??It.V1.convertAvailability(a.availability)??n,isResponseStream:a.response?.type.type==="stream",title:t.title??a.name??f8(a.path.parts),slug:s.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,playground:this.#P(a.includeInApiExplorer===!1?{...t.playground,hidden:!0}:t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let o=(r!=null?this.#e.subpackages.get(oQ.SubpackageId(r))?.webSockets.get(oQ.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??f8(o.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(o)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:It.V1.convertAvailability(o.availability)??n,playground:this.#P(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let c=(r!=null?this.#e.subpackages.get(oQ.SubpackageId(r))?.webhooks.get(oQ.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(It.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.#i.has(f)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${f}`),this.#i.add(f),{id:this.#f.get(`${this.apiDefinitionId}:${f}`),type:"webhook",webhookId:f,method:c.method,title:t.title??c.name??(0,Nz_.default)("/",...c.path),slug:(t.slug!=null?i.append(t.slug):i.apply(c)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:n,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 Rz_({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>f8(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#A(t,r){return Tvc({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(i,n,a)=>this.#v(i,n,a),mergeAndFilterChildren:this.#g.bind(this)})}#m(t,r,i){let n=[];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: ${O9o(a.method,a.path.parts)}. Got undefined.`);return}if(this.#n.has(o))return;let c=r.apply(a);n.push({id:It.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"grpc",grpcId:o,title:a.name??f8(a.path.parts),method:a.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:i,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: ${O9o(a.method,a.path.parts)}. Got undefined.`);return}if(this.#t.has(o))return;let c=r.apply(a);n.push({id:It.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"endpoint",method:a.method,endpointId:o,apiDefinitionId:this.apiDefinitionId,availability:It.V1.convertAvailability(a.availability)??i,isResponseStream:a.response?.type.type==="stream",title:a.name??f8(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)||n.push({id:It.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webSocket",webSocketId:o,title:a.name??f8(a.path.parts),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:It.V1.convertAvailability(a.availability)??i,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.#i.has(o)||n.push({id:It.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webhook",webhookId:o,method:a.method,title:a.name??I$i(a.id),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:i,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=UFt(o)?r.apply(o):r,f=this.#v(a,c,i);f.length>0&&n.push({id:It.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"apiPackage",children:f,title:UFt(o)?o.displayName??I$i(o.name):this.apiSection.title,slug:c.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:this.createTagDescriptionPageId(o),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})}),n=this.mergeEndpointPairs(n),this.apiSection.alphabetized&&(n=n.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)})),n}#v(t,r,i){let n=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return n==null?(this.taskContext.logger.debug(A9o(t||"unknown",[])),[]):this.#m(n,r,i)}#P(t){return Ez_(t)}mergeEndpointPairs(t){return P9o({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>f8(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}getFileId(t){let r=this.collectedFileIds.get(t);return r??this.taskContext.failAndThrow("Failed to locate file after uploading: "+t)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}};var Fz_=ue(require("crypto"),1);function wNM(e){return Fz_.default.createHash("sha256").update(e).digest("hex")}var w9o=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),wNM(r===0?t:`${t}-${r}`)}#i(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return It.V1.NodeId(this.#i(t))}};function Qz_(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 E9o=class{selectors;constructor(t){this.selectors=t}matches(t,r){for(let i of this.selectors)if(this.pathMatches(t,i.path)&&(!i.method||i.method===r))return!0;return!1}pathMatches(t,r){if(t===r)return!0;let i=t.split("/").filter(a=>a.length>0),n=r.split("/").filter(a=>a.length>0);if(i.length!==n.length)return!1;for(let a=0;a<i.length;a++){let o=i[a],c=n[a];if(!o||!c)return!1;let f=o.startsWith("{")&&o.endsWith("}"),s=c.startsWith("{")&&c.endsWith("}");if(!(f&&s)&&o!==c)return!1}return!0}getMatchingPaths(t){let r=[];for(let[i,n]of Object.entries(t)){if(!n)continue;let a=["get","put","post","delete","options","head","patch","trace"];for(let o of a)if(n[o]&&this.matches(i,o)){r.includes(i)||r.push(i);break}}return r}};var S9o=class{document;schemas=new Set;parameters=new Set;responses=new Set;requestBodies=new Set;securitySchemes=new Set;headers=new Set;examples=new Set;links=new Set;callbacks=new Set;constructor(t){this.document=t}collectFromOperation(t){if(t.parameters)for(let r of t.parameters)this.collectParameter(r);if(t.requestBody&&this.collectFromRequestBody(t.requestBody),t.responses)for(let r of Object.values(t.responses))this.collectFromResponse(r);if(t.callbacks)for(let[r,i]of Object.entries(t.callbacks))if(this.isReference(i))this.callbacks.add(this.extractComponentName(i.$ref));else for(let n of Object.values(i))this.collectFromPathItem(n);if(t.security)for(let r of t.security)for(let i of Object.keys(r))this.securitySchemes.add(i)}collectFromPathItem(t){if(t.parameters)for(let i of t.parameters)this.collectParameter(i);let r=[t.get,t.put,t.post,t.delete,t.options,t.head,t.patch,t.trace];for(let i of r)i&&this.collectFromOperation(i)}collectParameter(t){if(this.isReference(t)){this.parameters.add(this.extractComponentName(t.$ref));let r=this.resolveParameter(t.$ref);r&&this.collectParameter(r)}else{if(t.schema&&this.collectFromSchema(t.schema),t.content)for(let r of Object.values(t.content))this.collectFromMediaType(r);if(t.examples)for(let[r,i]of Object.entries(t.examples))this.isReference(i)&&this.examples.add(this.extractComponentName(i.$ref))}}collectFromRequestBody(t){if(this.isReference(t)){this.requestBodies.add(this.extractComponentName(t.$ref));let r=this.resolveRequestBody(t.$ref);r&&this.collectFromRequestBody(r)}else if(t.content)for(let r of Object.values(t.content))this.collectFromMediaType(r)}collectFromResponse(t){if(this.isReference(t)){this.responses.add(this.extractComponentName(t.$ref));let r=this.resolveResponse(t.$ref);r&&this.collectFromResponse(r)}else{if(t.headers)for(let[r,i]of Object.entries(t.headers))this.isReference(i)?this.headers.add(this.extractComponentName(i.$ref)):i.schema&&this.collectFromSchema(i.schema);if(t.content)for(let r of Object.values(t.content))this.collectFromMediaType(r);if(t.links)for(let[r,i]of Object.entries(t.links))this.isReference(i)&&this.links.add(this.extractComponentName(i.$ref))}}collectFromMediaType(t){if(t.schema&&this.collectFromSchema(t.schema),t.examples)for(let[r,i]of Object.entries(t.examples))this.isReference(i)&&this.examples.add(this.extractComponentName(i.$ref))}collectFromSchema(t){if(this.isReference(t)){let r=this.extractComponentName(t.$ref);if(!this.schemas.has(r)){this.schemas.add(r);let i=this.resolveSchema(t.$ref);i&&this.collectFromSchema(i)}}else{if(t.properties)for(let r of Object.values(t.properties))this.collectFromSchema(r);if(t.additionalProperties&&typeof t.additionalProperties=="object"&&this.collectFromSchema(t.additionalProperties),"items"in t&&t.items)if(Array.isArray(t.items))for(let r of t.items)this.collectFromSchema(r);else this.collectFromSchema(t.items);if(t.allOf)for(let r of t.allOf)this.collectFromSchema(r);if(t.oneOf)for(let r of t.oneOf)this.collectFromSchema(r);if(t.anyOf)for(let r of t.anyOf)this.collectFromSchema(r);t.not&&this.collectFromSchema(t.not)}}resolveSchema(t){let r=this.extractComponentName(t);return this.document.components?.schemas?.[r]}resolveParameter(t){let r=this.extractComponentName(t);return this.document.components?.parameters?.[r]}resolveResponse(t){let r=this.extractComponentName(t);return this.document.components?.responses?.[r]}resolveRequestBody(t){let r=this.extractComponentName(t);return this.document.components?.requestBodies?.[r]}isReference(t){return t!=null&&typeof t=="object"&&"$ref"in t}extractComponentName(t){let r=t.split("/");return r[r.length-1]??t}getSchemas(){return this.schemas}getParameters(){return this.parameters}getResponses(){return this.responses}getRequestBodies(){return this.requestBodies}getSecuritySchemes(){return this.securitySchemes}getHeaders(){return this.headers}getExamples(){return this.examples}getLinks(){return this.links}getCallbacks(){return this.callbacks}};var QEa=class{matcher;document;constructor(t){this.matcher=new E9o(t.endpoints),this.document=JSON.parse(JSON.stringify(t.document))}prune(){let t=this.collectStatistics(),r=new S9o(this.document),i={},n=this.matcher.getMatchingPaths(this.document.paths);for(let c of n){let f=this.document.paths[c];if(!f)continue;let s={};f.summary&&(s.summary=f.summary),f.description&&(s.description=f.description),f.servers&&(s.servers=f.servers),f.parameters&&(s.parameters=f.parameters);let u=["get","put","post","delete","options","head","patch","trace"];for(let l of u){let p=f[l];p&&this.matcher.matches(c,l)&&(s[l]=p,r.collectFromOperation(p))}if(f.parameters)for(let l of f.parameters)r.collectParameter(l);i[c]=s}let a={openapi:this.document.openapi,info:this.document.info,paths:i};if(this.document.servers&&(a.servers=this.document.servers),this.document.externalDocs&&(a.externalDocs=this.document.externalDocs),this.document.tags){let c=new Set;for(let f of Object.values(i)){let s=["get","put","post","delete","options","head","patch","trace"];for(let u of s){let l=f?.[u];if(l?.tags)for(let p of l.tags)c.add(p)}}a.tags=this.document.tags.filter(f=>c.has(f.name))}if(this.document.security){a.security=this.document.security;for(let c of this.document.security)for(let f of Object.keys(c))r.getSecuritySchemes().add(f)}a.components=this.buildPrunedComponents(r);let o=this.collectPrunedStatistics(a);return{document:a,statistics:{originalEndpoints:t.originalEndpoints,prunedEndpoints:o.originalEndpoints,originalSchemas:t.originalSchemas,prunedSchemas:o.originalSchemas,originalParameters:t.originalParameters,prunedParameters:o.originalParameters,originalResponses:t.originalResponses,prunedResponses:o.originalResponses,originalRequestBodies:t.originalRequestBodies,prunedRequestBodies:o.originalRequestBodies,originalSecuritySchemes:t.originalSecuritySchemes,prunedSecuritySchemes:o.originalSecuritySchemes}}}buildPrunedComponents(t){if(!this.document.components)return;let r={};if(this.document.components.schemas&&t.getSchemas().size>0){r.schemas={};for(let i of t.getSchemas()){let n=this.document.components.schemas[i];n&&(r.schemas[i]=n)}}if(this.document.components.parameters&&t.getParameters().size>0){r.parameters={};for(let i of t.getParameters()){let n=this.document.components.parameters[i];n&&(r.parameters[i]=n)}}if(this.document.components.responses&&t.getResponses().size>0){r.responses={};for(let i of t.getResponses()){let n=this.document.components.responses[i];n&&(r.responses[i]=n)}}if(this.document.components.requestBodies&&t.getRequestBodies().size>0){r.requestBodies={};for(let i of t.getRequestBodies()){let n=this.document.components.requestBodies[i];n&&(r.requestBodies[i]=n)}}if(this.document.components.securitySchemes&&t.getSecuritySchemes().size>0){r.securitySchemes={};for(let i of t.getSecuritySchemes()){let n=this.document.components.securitySchemes[i];n&&(r.securitySchemes[i]=n)}}if(this.document.components.headers&&t.getHeaders().size>0){r.headers={};for(let i of t.getHeaders()){let n=this.document.components.headers[i];n&&(r.headers[i]=n)}}if(this.document.components.examples&&t.getExamples().size>0){r.examples={};for(let i of t.getExamples()){let n=this.document.components.examples[i];n&&(r.examples[i]=n)}}if(this.document.components.links&&t.getLinks().size>0){r.links={};for(let i of t.getLinks()){let n=this.document.components.links[i];n&&(r.links[i]=n)}}if(this.document.components.callbacks&&t.getCallbacks().size>0){r.callbacks={};for(let i of t.getCallbacks()){let n=this.document.components.callbacks[i];n&&(r.callbacks[i]=n)}}return Object.keys(r).length>0?r:void 0}collectStatistics(){let t=0;for(let r of Object.values(this.document.paths)){if(!r)continue;let i=["get","put","post","delete","options","head","patch","trace"];for(let n of i)r[n]&&t++}return{originalEndpoints:t,prunedEndpoints:0,originalSchemas:Object.keys(this.document.components?.schemas??{}).length,prunedSchemas:0,originalParameters:Object.keys(this.document.components?.parameters??{}).length,prunedParameters:0,originalResponses:Object.keys(this.document.components?.responses??{}).length,prunedResponses:0,originalRequestBodies:Object.keys(this.document.components?.requestBodies??{}).length,prunedRequestBodies:0,originalSecuritySchemes:Object.keys(this.document.components?.securitySchemes??{}).length,prunedSecuritySchemes:0}}collectPrunedStatistics(t){let r=0;for(let i of Object.values(t.paths)){if(!i)continue;let n=["get","put","post","delete","options","head","patch","trace"];for(let a of n)i[a]&&r++}return{originalEndpoints:r,prunedEndpoints:0,originalSchemas:Object.keys(t.components?.schemas??{}).length,prunedSchemas:0,originalParameters:Object.keys(t.components?.parameters??{}).length,prunedParameters:0,originalResponses:Object.keys(t.components?.responses??{}).length,prunedResponses:0,originalRequestBodies:Object.keys(t.components?.requestBodies??{}).length,prunedRequestBodies:0,originalSecuritySchemes:Object.keys(t.components?.securitySchemes??{}).length,prunedSecuritySchemes:0}}};var Uvc=require("fs/promises");var M9o=class{config;context;lambdaOrigin;venusOrigin;token;jwtPromise;organizationId;constructor(t,r,i,n){this.config={enabled:t.enabled,openaiApiKey:t.openaiApiKey,model:t.model??"gpt-4o-mini",maxRetries:t.maxRetries??1,requestTimeoutMs:75e3},this.context=r;let a="https://ykq45y6fvnszd35iv5yuuatkze0rpwuz.lambda-url.us-east-1.on.aws";if(!a)throw new Error("DEFAULT_FDR_LAMBDA_DOCS_ORIGIN environment variable is not set. AI example enhancement requires this to be configured.");this.lambdaOrigin=a,this.venusOrigin="https://venus.buildwithfern.com",this.token=i,this.organizationId=n}async getJwt(){return this.jwtPromise==null&&(this.jwtPromise=this.fetchJwtFromVenus()),this.jwtPromise}async fetchJwtFromVenus(){this.context.logger.debug("Fetching JWT from Venus for AI example enhancement"),this.context.logger.debug(`Token type: ${this.token.type}`),this.context.logger.debug(`Token value (first 10 chars): ${this.token.value.substring(0,10)}...`),this.context.logger.debug(`Token value starts with 'fern_': ${this.token.value.startsWith("fern_")}`),this.context.logger.debug(`Venus origin: ${this.venusOrigin}`),this.context.logger.debug(`Organization ID: ${this.organizationId}`);let t=await fetch(`${this.venusOrigin}/auth/jwt`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token.value}`},body:JSON.stringify({organizationId:this.organizationId}),signal:AbortSignal.timeout(1e4)});if(!t.ok){let i=await t.text();throw new Error(`Failed to fetch JWT from Venus: ${t.status} ${i||t.statusText}`)}let r=await t.json();return this.context.logger.debug(`Successfully obtained JWT from Venus (expires at ${r.expiresAt})`),r.token}async enhanceExample(t){if(!this.config.enabled)return{enhancedRequestExample:t.originalRequestExample,enhancedResponseExample:t.originalResponseExample};let r;try{r=await this.getJwt()}catch(n){return this.context.logger.warn(`Failed to obtain JWT from Venus: ${n}. AI example enhancement will be skipped.`),{enhancedRequestExample:t.originalRequestExample,enhancedResponseExample:t.originalResponseExample}}let i;for(let n=1;n<=this.config.maxRetries;n++)try{this.context.logger.debug(`Enhancing example for ${t.method} ${t.endpointPath} via lambda (attempt ${n}/${this.config.maxRetries})`);let a={method:t.method,endpointPath:t.endpointPath,organizationId:t.organizationId,operationSummary:t.operationSummary,operationDescription:t.operationDescription,originalRequestExample:t.originalRequestExample,originalResponseExample:t.originalResponseExample,openApiSpec:t.openApiSpec};this.context.logger.debug(`Sending to enhanceExamples: ${JSON.stringify({...a,openApiSpec:t.openApiSpec?`[OpenAPI spec present: ${t.openApiSpec.length} chars]`:"[No OpenAPI spec]"},null,2)}`);let o=await fetch(`${this.lambdaOrigin}/v2/registry/ai/enhance-example`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(a),signal:AbortSignal.timeout(this.config.requestTimeoutMs)});if(!o.ok){let f=await o.text();throw new Error(`Lambda returned ${o.status}: ${f||o.statusText}`)}let c=await o.json();return{enhancedRequestExample:c.enhancedRequestExample??t.originalRequestExample,enhancedResponseExample:c.enhancedResponseExample??t.originalResponseExample}}catch(a){if(i=a,this.context.logger.warn(`Attempt ${n} failed to enhance example: ${a}`),n<this.config.maxRetries){let o=Math.min(1e3*Math.pow(2,n-1),1e4);await new Promise(c=>setTimeout(c,o))}}return this.context.logger.error(`Failed to enhance example after ${this.config.maxRetries} attempts: ${i?.message}`),{enhancedRequestExample:t.originalRequestExample,enhancedResponseExample:t.originalResponseExample}}};var UEa=class e{static instance;currentApiId;queue=[];progress=new Map;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}create(t,r,i){let n=`${t}-${Date.now()}-${Math.random()}`;return this.progress.set(n,{apiName:t,completed:0,total:r,endpointsSample:i}),this.queue.push(n),this.currentApiId||(this.currentApiId=n,this.updateSpinnerStatus()),n}update(t,r){let i=this.progress.get(t);i&&(i.completed=r,t===this.currentApiId&&this.updateSpinnerStatus())}finish(t){this.progress.delete(t);let r=this.queue.indexOf(t);r!==-1&&this.queue.splice(r,1),t===this.currentApiId&&(this.queue.length>0?(this.currentApiId=this.queue[0],this.updateSpinnerStatus()):(this.currentApiId=void 0,delete process.env.FERN_SPINNER_STATUS))}updateSpinnerStatus(){if(!this.currentApiId){delete process.env.FERN_SPINNER_STATUS;return}let t=this.progress.get(this.currentApiId);if(t){let r=`auto-generating examples for endpoints - ${t.apiName}`;t.endpointsSample&&(r+=` (${t.endpointsSample})`),r+=` - ${t.completed}/${t.total}`,process.env.FERN_SPINNER_STATUS=r}}};var D9o=require("fs/promises");async function ENM(e,t){let r=Fr.of(`${Zi(e)}/ai_examples_override.yml`),i=[];try{let n=await(0,D9o.readFile)(r,"utf-8"),a=wi.load(n);if(a&&typeof a=="object"&&"paths"in a){let o=a.paths;for(let[c,f]of Object.entries(o))if(f&&typeof f=="object"){for(let[s,u]of Object.entries(f))if(u&&typeof u=="object"&&"x-fern-examples"in u){let l=u["x-fern-examples"];if(Array.isArray(l)){for(let p of l)if(typeof p=="object"&&p!==null){let _=p;i.push({endpointPath:c,method:s.toUpperCase(),pathParameters:_["path-parameters"],queryParameters:_["query-parameters"],headers:_.headers,request:_.request,response:_.response})}}}}}t.logger.debug(`Parsed ${i.length} AI examples from ai_examples_override.yml`)}catch(n){t.logger.debug(`No existing ai_examples_override.yml found or error reading it: ${n}`)}return i}async function zvc({sourceFilePath:e,context:t}){let r=await ENM(e,t);if(r.length===0)return{validExamples:[],invalidExamples:[],totalExamples:0,validCount:0,invalidCount:0};let i;try{let s=await(0,D9o.readFile)(e,"utf-8");try{i=JSON.parse(s)}catch{i=wi.load(s)}}catch(s){return t.logger.warn(`Failed to read OpenAPI spec file: ${s}`),{validExamples:r,invalidExamples:[],totalExamples:r.length,validCount:r.length,invalidCount:0}}let n=new T0e({logger:t.logger}),a=new jgi({namespace:void 0,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:i,exampleGenerationArgs:{disabled:!1},errorCollector:n,enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,settings:SFt()}),o=new zKi({context:a}),{validExamples:c,invalidExamples:f}=o.validateAiExamples({aiExamples:r,spec:i});if(f.length>0){t.logger.info(`Found ${f.length} stale AI examples that need to be regenerated out of ${r.length} total`);for(let{example:s,validationResult:u}of f)t.logger.debug(`Stale AI example: ${s.method} ${s.endpointPath} - ${u.errors.map(l=>l.message).join(", ")}`)}return{validExamples:c,invalidExamples:f,totalExamples:r.length,validCount:c.length,invalidCount:f.length}}async function Uz_({sourceFilePath:e,context:t}){let r=await zvc({sourceFilePath:e,context:t});if(r.invalidCount===0)return t.logger.debug("No invalid AI examples to remove"),{removedCount:0,remainingCount:r.totalExamples};let i=Fr.of(`${Zi(e)}/ai_examples_override.yml`);try{let n=await(0,D9o.readFile)(i,"utf-8"),a=wi.load(n);if(!a||!a.paths)return{removedCount:0,remainingCount:r.totalExamples};let o=new Set(r.invalidExamples.map(({example:s})=>`${s.method.toLowerCase()}:${s.endpointPath}`));for(let[s,u]of Object.entries(a.paths))if(u&&typeof u=="object"){for(let l of Object.keys(u)){let p=`${l.toLowerCase()}:${s}`;o.has(p)&&delete u[l]}Object.keys(u).length===0&&delete a.paths[s]}let{writeFile:c}=await import("fs/promises"),f=wi.dump(a,{indent:2,lineWidth:-1,noRefs:!0});return await c(i,f,"utf-8"),t.logger.info(`Removed ${r.invalidCount} invalid AI examples from ai_examples_override.yml`),{removedCount:r.invalidCount,remainingCount:r.validCount}}catch(n){return t.logger.warn(`Failed to remove invalid AI examples: ${n}`),{removedCount:0,remainingCount:r.totalExamples}}}var LEa=require("fs/promises");async function Nvc(e,t){let r=Fr.of(`${Zi(e)}/ai_examples_override.yml`),i=new Set;try{let n=await(0,LEa.readFile)(r,"utf-8"),a=wi.load(n);if(a&&typeof a=="object"&&"paths"in a){let o=a.paths;for(let[c,f]of Object.entries(o))if(f&&typeof f=="object")for(let s of Object.keys(f)){let u=`${s.toLowerCase()}:${c}`;i.add(u)}}t.logger.debug(`Loaded ${i.size} covered endpoints from ai_examples_override.yml`)}catch{t.logger.debug("No existing ai_examples_override.yml found or error reading it")}return i}async function Fvc({enhancedExamples:e,sourceFilePath:t,context:r}){if(e.length===0){r.logger.debug("No enhanced examples to write");return}let i=new Map;for(let o of e){let c=i.get(o.endpoint)||[];c.push(o),i.set(o.endpoint,c)}let n={paths:{}};for(let[o,c]of i.entries()){let f=new Map;for(let s of c){let u=f.get(s.method.toLowerCase())||[];u.push(s),f.set(s.method.toLowerCase(),u)}n.paths[o]||(n.paths[o]={});for(let[s,u]of f.entries()){let l=u.map((_,h)=>{let y={};return _.pathParameters&&Object.keys(_.pathParameters).length>0&&(y["path-parameters"]=_.pathParameters),_.queryParameters&&Object.keys(_.queryParameters).length>0&&(y["query-parameters"]=_.queryParameters),_.headers&&Object.keys(_.headers).length>0&&(y.headers=_.headers),_.requestBody!==void 0&&(y.request={body:_.requestBody}),_.responseBody!==void 0&&(y.response={body:_.responseBody}),y}),p=n.paths[o];p&&(p[s]={"x-fern-examples":l})}}let a=Fr.of(`${Zi(t)}/ai_examples_override.yml`);try{let o={};try{let s=await(0,LEa.readFile)(a,"utf-8"),u=wi.load(s);u&&typeof u=="object"&&(o=u)}catch{r.logger.debug("No existing ai_examples_override.yml found, creating new file")}let c={paths:{}};if(o.paths){for(let[s,u]of Object.entries(o.paths))if(u&&typeof u=="object"){c.paths[s]={};for(let[l,p]of Object.entries(u))p&&typeof p=="object"&&"x-fern-examples"in p&&(c.paths[s][l]={"x-fern-examples":p["x-fern-examples"]||[]})}}for(let[s,u]of Object.entries(n.paths)){c.paths[s]||(c.paths[s]={});for(let[l,p]of Object.entries(u))c.paths[s][l]?r.logger.debug(`Skipping ${l.toUpperCase()} ${s} - examples already exist in override file`):(c.paths[s][l]=p,r.logger.debug(`Adding new examples for ${l.toUpperCase()} ${s}`))}let f=wi.dump(c,{indent:2,lineWidth:-1,noRefs:!0});await(0,LEa.writeFile)(a,f,"utf-8"),r.logger.debug(`AI enhanced examples written to: ${a}`)}catch(o){throw r.logger.warn(`Failed to write AI examples override file: ${o}`),o}}var Qvc=class{failureCount=0;failureThreshold=30;isOpen=!1;recordFailure(){this.failureCount++,this.failureCount>=this.failureThreshold&&(this.isOpen=!0)}recordSuccess(){this.failureCount=0,this.isOpen=!1}shouldSkip(){return this.isOpen}getFailureCount(){return this.failureCount}getThreshold(){return this.failureThreshold}},Lz_=!1;function SNM(e){try{try{let t=JSON.parse(e);return!!(t.openapi||t.swagger)}catch{let t=ZDn(e);return!!(t?.openapi||t?.swagger)}}catch{return!1}}function MNM(e,t){if(t.includes(e))return e;for(let r of t){let i=r.replace(/\{[^}]+\}/g,"([^/]+)");if(new RegExp(`^${i}$`).test(e))return r}}async function DNM(e,t,r){try{let i;try{i=JSON.parse(e)}catch{i=ZDn(e)}if(!i.openapi||!i.paths){r.logger.debug("Invalid OpenAPI spec structure, skipping pruning");return}let n=Object.keys(i.paths);r.logger.debug(`OpenAPI spec contains ${n.length} paths`);let a=[];for(let l of t){let p=MNM(l.path,n);p?(a.push({path:p,method:l.method.toLowerCase()}),r.logger.debug(`Mapped ${l.path} to OpenAPI path: ${p}`)):r.logger.debug(`No matching OpenAPI path found for ${l.path}`)}if(a.length===0){r.logger.debug("No endpoints matched in OpenAPI spec");return}let c=new QEa({document:i,endpoints:a}).prune();r.logger.debug(`Pruned OpenAPI spec for batch: ${c.statistics.originalEndpoints} \u2192 ${c.statistics.prunedEndpoints} endpoints, ${c.statistics.originalSchemas} \u2192 ${c.statistics.prunedSchemas} schemas`);let f=JSON.stringify(c.document,null,2);if(f.length>15e5){r.logger.debug(`Pruned OpenAPI spec still too large (${f.length} characters), skipping spec context for AI enhancement`);return}r.logger.debug(`Pruned spec size: ${f.length} characters (within limit)`);let s=a.map(l=>`${(l.method||"unknown").toUpperCase()}_${l.path.replace(/\//g,"_").replace(/[{}]/g,"")}`),u=`batch_${a.length}endpoints_${s.join("_").substring(0,100)}_pruned_spec.yaml`;return f}catch(i){return r.logger.debug(`Failed to prune OpenAPI spec: ${i}. Using original spec.`),e}}async function jLn(e,t,r,i,n,a,o){if(!t.enabled)return r.logger.debug("AI example enhancement is disabled"),e;if(!Lz_){let y=Ut.blue(`Notice: new feature added (experimental)!
1769
1769
 
1770
1770
  `)+`We are generating realistic examples for endpoints in your spec.
1771
1771
  This will not override your current examples. Please wait a moment.
@@ -1773,7 +1773,7 @@ This will not override your current examples. Please wait a moment.
1773
1773
  Future runs will use saved examples. If you wish to override the content of the
1774
1774
  examples, please edit and commit auto-generated \`ai_examples_override.yml\` files.`,b=TBi(y,{padding:1,textAlignment:"left",borderColor:"blue",borderStyle:"round"});r.logger.info(`
1775
1775
  `+b+`
1776
- `),Lz_=!0}let c=new M9o(t,r,i),f=new Qvc,s,u=new Set;if(a!=null)try{let y=await(0,Uvc.readFile)(a,"utf-8");if(!SNM(y))return r.logger.debug("Non-OpenAPI spec detected, skipping AI example enhancement"),e;s=y,r.logger.debug(`Loaded OpenAPI spec (${y.length} characters) for AI enhancement`);let b=await Nvc(a,r);try{let v=await zvc({sourceFilePath:a,context:r});if(v.invalidCount>0){for(let{example:A}of v.invalidExamples){let g=`${A.method.toLowerCase()}:${A.endpointPath}`;u.add(g)}let O=await Uz_({sourceFilePath:a,context:r});r.logger.info(`Removed ${O.removedCount} stale AI examples, ${u.size} endpoints will be regenerated`)}else r.logger.debug("No stale AI examples found to remove")}catch(v){r.logger.debug(`Failed to clean up stale AI examples: ${v}`)}}catch(y){r.logger.debug(`Failed to read OpenAPI spec file: ${y}`)}let l=new Set;if(a!=null){let y=await Nvc(a,r);for(let b of y)u.has(b)||l.add(b);u.size>0&&r.logger.debug(`Coverage adjusted: ${y.size} total, ${l.size} preserved, ${u.size} marked for regeneration`)}let p={count:0,total:0},_=[],h=await BNM(e,c,r,n,p,_,l,u,s,a,o,f);if(_.length>0&&a!=null)try{await Fvc({enhancedExamples:_,sourceFilePath:a,context:r})}catch(y){r.logger.debug(`Failed to write AI examples override file: ${y}`)}return h}async function BNM(e,t,r,i,n,a,o,c,f,s,u,l){let p=[];for(let[g,m]of Object.entries(e.subpackages)){let j=Vz_(m,o,c);p.push(...j.map(M=>({...M,packageId:g})))}let _=Vz_(e.rootPackage,o,c);p.push(..._.map(g=>({...g,packageId:"root"}))),n.total+=p.length,r.logger.debug(`Collected ${p.length} work items across all packages`);let h=UEa.getInstance(),y=h.create(u||"API",p.length),b={count:0,total:p.length},v=await INM(p,t,r,i,n,a,f,s,y,b,l);h.finish(y);let O={};for(let[g,m]of Object.entries(e.subpackages)){let j=Wz_(m,v);O[g]=j}let A=Wz_(e.rootPackage,v);return{...e,subpackages:O,rootPackage:A}}function Vz_(e,t,r){let i=[],n=new Set;for(let a of e.endpoints){let o=a;if(!TNM(o))for(let f of o.examples){let s=`${o.method.toLowerCase()}:${f.path}`;if(n.has(s))continue;let u=r?.has(s);if(!u&&t.has(s)||!u&&!qNM(f))continue;let l=PLn(f.requestBodyV3),p=PLn(f.responseBodyV3);if(!(!u&&!l&&!p)){i.push({endpoint:o,example:f,endpointKey:s}),n.add(s);break}}}return i}async function INM(e,t,r,i,n,a,o,c,f,s,u){let l=new Map,p=parseInt(process.env.FERN_AI_MAX_CONCURRENT||"25",10);if(r.logger.debug(`Processing ${e.length} endpoints with max ${p} concurrent Lambda calls`),u?.shouldSkip())return r.logger.debug(`Circuit breaker is open after ${u.getFailureCount()} failures (threshold: ${u.getThreshold()}). Skipping AI enhancement for remaining endpoints.`),l;for(let _=0;_<e.length;_+=p){let h=e.slice(_,_+p),y=Math.floor(_/p)+1;if(r.logger.debug(`Processing chunk ${y} with ${h.length} endpoints concurrently`),u?.shouldSkip()){r.logger.debug(`Circuit breaker opened during processing. Stopping at chunk ${y}.`);break}let b=h.map((O,A)=>CNM(O,t,r,i,n,a,o,c,f,s,_+A+1,u)),v=await Promise.allSettled(b);for(let O=0;O<v.length;O++){let A=v[O];if(A)if(A.status==="fulfilled"&&A.value){let{endpointKey:g,enhancedReq:m,enhancedRes:j}=A.value;l.set(g,{enhancedReq:m,enhancedRes:j})}else A.status==="rejected"&&r.logger.debug(`Endpoint ${_+O+1} failed: ${A.reason}`)}if(c&&a.length>0)try{await Fvc({enhancedExamples:a,sourceFilePath:c,context:r}),r.logger.debug(`Saved ${a.length} examples after chunk ${y}`)}catch(O){r.logger.debug(`Failed to save incremental results: ${O}`)}}return l}async function CNM(e,t,r,i,n,a,o,c,f,s,u,l){let p=e.endpointKey;r.logger.debug(`Processing endpoint ${u}: ${e.endpoint.method} ${e.example.path}`);let _;o&&(_=await DNM(o,[{path:e.example.path,method:e.endpoint.method}],r));let h={method:e.endpoint.method,endpointPath:e.example.path,organizationId:i,operationSummary:e.endpoint.summary,operationDescription:e.endpoint.description,originalRequestExample:PLn(e.example.requestBodyV3),originalResponseExample:PLn(e.example.responseBodyV3),pathParameters:e.example.pathParameters,queryParameters:e.example.queryParameters,headers:e.example.headers,openApiSpec:_};for(let y=1;y<=2;y++)try{let b=await t.enhanceExample(h);l?.recordSuccess();let v=b.enhancedRequestExample!==h.originalRequestExample,O=b.enhancedResponseExample!==h.originalResponseExample;if(v||O){let A={endpoint:e.example.path,method:e.endpoint.method,pathParameters:e.example.pathParameters,queryParameters:e.example.queryParameters,headers:e.example.headers,requestBody:v?b.enhancedRequestExample:void 0,responseBody:O?b.enhancedResponseExample:void 0};return a.push(A),n.count++,s&&s.count++,r.logger.debug(`Successfully enhanced ${e.endpoint.method} ${e.example.path}`),f&&s&&UEa.getInstance().update(f,s.count),{endpointKey:p,enhancedReq:b.enhancedRequestExample,enhancedRes:b.enhancedResponseExample}}return r.logger.debug(`No changes needed for ${e.endpoint.method} ${e.example.path}`),{endpointKey:p,enhancedReq:b.enhancedRequestExample,enhancedRes:b.enhancedResponseExample}}catch(b){l?.recordFailure(),r.logger.debug(`Endpoint ${e.endpoint.method} ${e.example.path} attempt ${y} failed: ${b}`),y<2&&await new Promise(v=>setTimeout(v,1500))}return r.logger.debug(`Failed to enhance ${e.endpoint.method} ${e.example.path} after all attempts`),null}function Wz_(e,t){let r=e.endpoints.map(i=>{let n=i,a=n.examples.map(o=>{let c=`${n.method.toLowerCase()}:${o.path}`,f=t.get(c);if(f){let s={...o};return f.enhancedReq!==void 0&&o.requestBodyV3&&(s.requestBody=f.enhancedReq,s.requestBodyV3={...o.requestBodyV3,value:f.enhancedReq}),f.enhancedRes!==void 0&&o.responseBodyV3&&(s.responseBody=f.enhancedRes,s.responseBodyV3={...o.responseBodyV3,value:f.enhancedRes}),s}return o});return{...i,examples:a}});return{...e,endpoints:r}}function qNM(e){let t=!e.name||e.name===""||e.name==="Example",r=!e.description||e.description==="",i=B9o(PLn(e.requestBodyV3)),n=B9o(PLn(e.responseBodyV3));return t&&r&&i&&n}function B9o(e){return e==null?!1:typeof e=="string"?e===Tn.STRING||e===Tn.BASE64||e===Tn.DATE||e===Tn.DATE_TIME||e===Tn.UUID||e===Tn.BIG_INTEGER||Tn.SAMPLE_STRINGS.includes(e)||e==="":typeof e=="number"?e===Tn.DOUBLE||e===Tn.FLOAT||e===Tn.INT||e===Tn.INT64||e===Tn.UINT||e===Tn.UINT64||e===0:typeof e=="boolean"?e===Tn.BOOLEAN:Array.isArray(e)?e.length>0&&e.every(t=>B9o(t)):typeof e=="object"?Object.values(e).every(t=>B9o(t)):!1}function TNM(e){try{let t=e;if(t.v2Examples?.userSpecifiedExamples&&typeof t.v2Examples.userSpecifiedExamples=="object"){let r=t.v2Examples.userSpecifiedExamples;return Object.keys(r).length>0}if(t.v2Responses?.responses){for(let r of t.v2Responses.responses)if(r.body?.v2Examples?.userSpecifiedExamples&&typeof r.body.v2Examples.userSpecifiedExamples=="object"){let i=r.body.v2Examples.userSpecifiedExamples;if(Object.keys(i).length>0)return!0}}return!1}catch{return!1}}function PLn(e){if(e)switch(e.type){case"json":case"stream":case"sse":return e.value;case"filename":return;default:return e.value}}function xz_({auth:e,playgroundConfig:t,context:r}){if(e.schemes.length>0&&e.schemes[0]!=null){let i=e.schemes[0];return Gz_({scheme:i,playgroundConfig:t,context:r})}}function Gz_({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 i=e.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(n=>n.name.originalName).join(".")||"$.body.access_token";return t?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:_i.EndpointId(e.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:_i.JqString(i),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 i=e.tokenEndpoint.authenticatedRequestHeaders.find(a=>a.headerName.toLowerCase()==="authorization");if(i)return i.responseProperty.propertyPath!=null&&i.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:i.responseProperty.property.name.wireValue,description:e.docs};let n=e.tokenEndpoint.authenticatedRequestHeaders[0];return n?{type:"header",headerWireValue:n.headerName,prefix:n.valuePrefix,nameOverride:void 0,description:e.docs}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:Ot(e)}}function Hz_({auth:e,playgroundConfig:t,context:r}){let i={};for(let n of e.schemes){let a=Gz_({scheme:n,playgroundConfig:t,context:r});a!=null&&(i[_i.AuthSchemeId(n.key)]=a)}return i}function Jz_(e){return e._visit({alias:t=>({type:"alias",value:av(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:ED(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>_i.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:_i.PropertyKey(r.name.wireValue),valueType:av(r.valueType),availability:ED(r.availability),propertyAccess:r.propertyAccess})),extraProperties:NNM(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:_i.PropertyKey(i.name.wireValue),valueType:av(i.valueType),availability:ED(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?ED(i.availability):void 0,additionalProperties:vr.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[_i.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:_i.PropertyKey(n.name.wireValue),valueType:av(n.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:av(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName??r.type.name.originalName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function av(e){return e._visit({container:t=>vr.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:av(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:av(r),valueType:av(i)}),optional:r=>({type:"optional",itemType:av(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:av(r)}),set:r=>({type:"set",itemType:av(r)}),literal:r=>vr.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:_i.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:vr.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>zNM(t.v2),float:()=>Kz_(t.v2),double:()=>Kz_(t.v2),string:()=>RNM(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 RNM(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 zNM(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 Kz_(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 NNM(e){return typeof e=="boolean"?e?ii.unknown():void 0:typeof e=="string"?{type:"id",value:_i.TypeId(e),default:void 0}:av(e)}function Wvc(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?QNM(r,t):[],webhooks:i!=null?FNM(i):[],websockets:n!=null?[UNM(n,t)]:[],types:e.types.map(a=>_i.TypeId(a)),subpackages:e.subpackages.map(a=>_i.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?_i.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function FNM(e){return e.map(t=>{let r=[];return t.v2Examples!=null?(r.push(...Object.values(t.v2Examples.userSpecifiedExamples)),r.push(...Object.values(t.v2Examples.autogeneratedExamples))):r.push(...t.examples?.map(i=>({payload:i.payload.jsonExample}))??[]),{description:t.docs??void 0,id:_i.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??Dxi(t.name.originalName),headers:t.headers.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:av(i.valueType),availability:ED(i.availability)})),payload:$NM(t.payload),examples:r,responses:t.responses?.map(Vvc).filter(Zu)}})}function QNM(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let c,f=i.v2Examples.userSpecifiedExamples,s=i.v2Examples.autogeneratedExamples,u=Object.values(f).map(p=>p.response?.statusCode).filter((p,_,h)=>h.indexOf(p)!==_).length>0;for(let[p,_]of Object.entries(f))c=Yz_({shouldUseExampleName:u,exampleName:_.displayName??p,example:_,irEndpoint:i,irService:e,ir:t}),c!=null&&a.push(c);let l=Object.values(s).map(p=>p.response?.statusCode).filter((p,_,h)=>h.indexOf(p)!==_).length>0;for(let[p,_]of Object.entries(s))c=Yz_({shouldUseExampleName:l,exampleName:_.displayName??p,example:_,irEndpoint:i,irService:e,ir:t}),c!=null&&a.push(c)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(c=>Lvc({userSpecifiedExample:c,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(Zu));else if(n!=null){let c=Lvc({autogeneratedExample:n,irEndpoint:i,ir:t});c!=null&&a.push(c)}else if(i.response?.body?.type==="fileDownload"){let c=VFn({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(c.type==="success"){let f=Lvc({autogeneratedExample:c,irEndpoint:i,ir:t});if(f!=null){let s={...f,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let o={slug:void 0,availability:ED(i.availability??e.availability),auth:i.auth,authV2:LNM(i.security),multiAuth:VNM(i.security),description:i.docs??void 0,method:HNM(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?_i.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?WNM({environmentsConfig:t.environments,endpoint:i}):void 0,id:_i.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??Dxi(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(c=>({description:c.docs??void 0,key:_i.PropertyKey(c.name.originalName),type:av(c.valueType),availability:void 0,explode:void 0})),parts:[...wLn(i.basePath),...wLn(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(c=>({description:c.docs??void 0,key:_i.PropertyKey(c.name.originalName),type:av(c.valueType),availability:void 0,explode:void 0})),parts:[...t.basePath!=null?wLn(t.basePath):[],...wLn(e.basePath),...wLn(i.path)]},queryParameters:i.queryParameters.map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:av(c.valueType),availability:ED(c.availability),explode:void 0})),headers:[...e.headers,...i.headers].map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:av(c.valueType),availability:ED(c.availability)})),request:i.requestBody!=null?$z_(i.requestBody):void 0,requestsV2:{requests:i.v2RequestBodies?.requestBodies?.map($z_).filter(Zu)},response:i.response!=null?Vvc(i.response):void 0,responsesV2:{responses:i.v2Responses?.responses?.map(Vvc).filter(Zu)},errors:void 0,errorsV2:KNM(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:c=>({type:"grpc",methodName:i.id,methodType:c.methodType}),_other:()=>{}}),includeInApiExplorer:i.apiPlayground};r.push(o)}return r}function UNM(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let i=Object.values(e.v2Examples.userSpecifiedExamples),n=Object.values(e.v2Examples.autogeneratedExamples),a=i.length>0?i[0]:n[0];a!=null&&r.push({name:"",description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(o=>({type:_i.api.v1.WebSocketMessageId(o.type),body:o.body}))??[]})}else r=e.examples.map(i=>({name:i.name?.originalName,description:i.docs,path:i.url,pathParameters:i.pathParameters.reduce((n,a)=>(n[_i.PropertyKey(a.name.originalName)]=a.value.jsonExample,n),{}),queryParameters:i.queryParameters.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),headers:i.headers.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),messages:i.messages.map(n=>({type:_i.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}));return{auth:e.auth,availability:ED(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?_i.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?xNM({environmentsConfig:t.environments,channel:e}):[],id:_i.WebSocketId(e.name.originalName),name:e.displayName??Dxi(e.name.originalName),path:{pathParameters:e.pathParameters.map(i=>({description:i.docs??void 0,key:_i.PropertyKey(i.name.originalName),type:av(i.valueType),availability:void 0,explode:void 0})),parts:wLn(e.path)},headers:e.headers.map(i=>({key:i.name.wireValue,type:av(i.valueType),description:i.docs,availability:ED(i.availability)})),queryParameters:e.queryParameters.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:av(i.valueType),availability:ED(i.availability),explode:void 0})),messages:e.messages.map(i=>({type:_i.api.v1.WebSocketMessageId(i.type),displayName:i.displayName,origin:i.origin,body:YNM(i.body),description:i.docs,availability:ED(i.availability)})),examples:r}}function LNM(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=>_i.AuthSchemeId(r))}function VNM(e){if(e!=null)return e.length===0?[]:e.map(t=>({schemes:Object.keys(t).map(r=>_i.AuthSchemeId(r))}))}function ED(e){if(e!=null)switch(e.status){case"DEPRECATED":return _i.Availability.Deprecated;case"PRE_RELEASE":return _i.Availability.Beta;case"GENERAL_AVAILABILITY":return _i.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return _i.Availability.Beta;default:Ot(e.status)}}function WNM({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl,n=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:_i.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(n!=null)return n.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:_i.EnvironmentId(o),baseUrl:f}})).filter((o,c,f)=>c===f.findIndex(s=>s.id===o.id&&s.baseUrl===o.baseUrl));if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let o=a.urls[i];if(o==null)throw new Error(`Encountered undefined server name "${i}" at endpoint ${t.method.toUpperCase()} ${t.path.head}. Expected environment ${a.id} to contain url for ${i}`);return{id:_i.EnvironmentId(a.id),baseUrl:o}});default:Ot(r)}}function xNM({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:_i.EnvironmentId(n.id),baseUrl:GNM(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Encountered undefined server name ${a} at channel ${t.name.originalName} ${t.path.head}. Expected environment ${n.id} to contain url for ${i}`);return{id:_i.EnvironmentId(n.id),baseUrl:a}});default:Ot(r)}}function GNM(e,t){return e.replace(/^[^:]+/,t)}function HNM(e){return vr.http.HttpMethod._visit(e,{get:()=>_i.HttpMethod.Get,post:()=>_i.HttpMethod.Post,put:()=>_i.HttpMethod.Put,patch:()=>_i.HttpMethod.Patch,delete:()=>_i.HttpMethod.Delete,head:()=>_i.HttpMethod.Head,_other:()=>{throw new Error("Unknown http method: "+e)}})}function wLn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:_i.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function $z_(e){let t=vr.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??aO.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>_i.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:_i.PropertyKey(i.name.wireValue),valueType:av(i.valueType),availability:ED(i.availability),propertyAccess:i.propertyAccess})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??aO.APPLICATION_JSON,shape:{type:"reference",value:av(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:o=>({type:"file",key:_i.PropertyKey(o.key.wireValue),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),fileArray:o=>({type:"fileArray",key:_i.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:n=>({type:"bodyProperty",key:_i.PropertyKey(n.name.wireValue),valueType:av(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:ED(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(Zu)},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 Vvc(e){let t,r;return e.body!=null&&(r=vr.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:av(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:av(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:av(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}})),r!=null?{type:r,statusCode:e.statusCode,isWildcard:e.isWildcardStatusCode===!0?!0:void 0,description:t}:e.statusCode!=null?{statusCode:e.statusCode,isWildcard:e.isWildcardStatusCode===!0?!0:void 0,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function KNM(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:av(n.type)},statusCode:n.statusCode,isWildcard:n.isWildcardStatusCode===!0?!0:void 0,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:XNM(n,t),headers:n.headers!=null&&n.headers.length>0?n.headers.map(a=>({description:a.docs??void 0,key:a.name.wireValue,type:av(a.valueType),availability:ED(a.availability)})):void 0})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:_i.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0,propertyAccess:void 0}];n.type!=null&&a.push({key:_i.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:av(n.type),description:n.docs,availability:void 0,propertyAccess:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,isWildcard:n.isWildcardStatusCode===!0?!0:void 0,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(o=>({name:o.name?.originalName,responseBody:{type:"json",value:o.jsonExample},description:o.docs})),headers:n.headers!=null&&n.headers.length>0?n.headers.map(o=>({description:o.docs??void 0,key:o.name.wireValue,type:av(o.valueType),availability:ED(o.availability)})):void 0})}}return r}function Yz_({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:i,irService:n,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)}),n.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)});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,p]of Object.entries(c))(u[l]===null||u[l]===void 0)&&(u[l]=p);return u})(),requestBody:r.request?.requestBody,requestBodyV3:i.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:s=>{if(r.request==null)return;let u={};if($c(r.request.requestBody)){let l=r.request.requestBody;for(let p of s.properties)p._visit({file:_=>{let h=l[_.key.wireValue];if(_.type==="file")u[_.key.wireValue]={type:"filename",value:typeof h=="string"?h:"<file1>"};else if(_.type==="fileArray"){let y=(Array.isArray(h)?h:[h]).filter(b=>typeof b=="string");u[_.key.wireValue]={type:"filenames",value:y}}},bodyProperty:_=>{if(_.style==="exploded"){let h=l[_.name.wireValue];u[_.name.wireValue]={type:"exploded",value:Array.isArray(h)?h:[h]}}else u[_.name.wireValue]={type:"json",value:l[_.name.wireValue]}},_other:KOe})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??i.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(JNM)?{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(Zu)}}function JNM(e){return typeof e=="object"&&e!==null&&"event"in e&&typeof e?.event=="string"&&"data"in e}function Lvc({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.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:vr.ExampleTypeReferenceShape.primitive(vr.ExamplePrimitive.string({original:f}))}}}).filter(Zu),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[_i.PropertyKey(f.name.originalName)]=f.value.jsonExample,c),{}),queryParameters:a.queryParameters.reduce((c,f)=>(c[f.name.wireValue]=f.value.jsonExample,c),{}),headers:[...n,...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($c(a.request.jsonExample)){let s=a.request.jsonExample;for(let u of c.properties)u._visit({file:l=>{let p=s[l.key.wireValue];if(l.type==="file")f[l.key.wireValue]={type:"filename",value:typeof p=="string"?p:"<file1>"};else if(l.type==="fileArray"){let _=(Array.isArray(p)?p:[p]).filter(h=>typeof h=="string");f[l.key.wireValue]={type:"filenames",value:_}}},bodyProperty:l=>{if(l.style==="exploded"){let p=s[l.name.wireValue];f[l.name.wireValue]={type:"exploded",value:Array.isArray(p)?p:[p]}}else f[l.name.wireValue]={type:"json",value:s[l.name.wireValue]}},_other:KOe})}return{type:"form",value:f}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??vr.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=i.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=>dhe._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(Zu)}}function $NM(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>_i.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:_i.PropertyKey(t.name.wireValue),valueType:av(t.valueType),availability:ED(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:av(e.payloadType)},description:e.docs};default:Ot(e)}}function YNM(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>_i.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:_i.PropertyKey(t.name.wireValue),valueType:av(t.valueType),availability:ED(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:av(e.bodyType)};default:Ot(e)}}function XNM(e,t){let r=e.v2Examples?.userSpecifiedExamples,i=e.v2Examples?.autogeneratedExamples,n=e.examples;if(r!=null&&Object.keys(r).length>0)return Object.entries(r).map(([o,c])=>({name:o,responseBody:{type:"json",value:c},description:void 0}));if(i!=null&&Object.keys(i).length>0)return Object.entries(i).map(([o,c])=>({name:o,responseBody:{type:"json",value:c},description:void 0}));if(n.length>0)return n.map(o=>({name:o.name?.originalName,responseBody:{type:"json",value:o.jsonExample},description:o.docs}));let a=ZNM(e,t);return a!=null?[a]:[]}function ZNM(e,t){if(e.type==null||e.type.type!=="named")return;let r=e.type.typeId,i=t.types[r];if(i==null||i.shape.type!=="object")return;let n={},a=!1;for(let o of i.shape.properties){let c=o.name.wireValue,f=o.v2Examples;if(f?.userSpecifiedExamples!=null){let s=Object.values(f.userSpecifiedExamples);if(s.length>0){n[c]=s[0],a=!0;continue}}if(f?.autogeneratedExamples!=null){let s=Object.values(f.autogeneratedExamples);if(s.length>0){n[c]=s[0];continue}}}if(a)return{name:void 0,responseBody:{type:"json",value:n},description:void 0}}function Tx({ir:e,snippetsConfig:t,playgroundConfig:r,context:i}){let n={types:{},subpackages:{},rootPackage:Wvc(e.rootPackage,e),auth:xz_({auth:e.auth,playgroundConfig:r,context:i}),authSchemes:Hz_({auth:e.auth,playgroundConfig:r,context:i}),snippetsConfiguration:t,globalHeaders:e.headers.map(a=>({availability:ED(a.availability),description:a.docs??void 0,key:a.name.wireValue,type:av(a.valueType)})),navigation:void 0};for(let[a,o]of Object.entries(e.types))n.types[_i.TypeId(a)]={description:o.docs??void 0,name:o.name.name.originalName,shape:Jz_(o.shape),availability:ED(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;n.subpackages[_i.api.v1.SubpackageId(a)]={subpackageId:_i.api.v1.SubpackageId(a),displayName:c?.displayName??o.displayName,name:o.name.originalName,description:o.docs??void 0,...Wvc(o,e)}}return n}async function xvc({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:o,aiEnhancerConfig:c}){let f=kw({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new Zw(r,t)}),s=KGi({token:i.value}),u=Tx({ir:f,snippetsConfig:a,playgroundConfig:o,context:r});if(c){let h=t.getSources().find(y=>y.type==="openapi")?.absoluteFilePath;u=await jLn(u,c,r,i,e,h,f.apiName.originalName)}let l=await s.api.v1.register.registerApiDefinition({orgId:_i.OrgId(e),apiId:_i.ApiId(f.apiName.originalName),definition:u});if(l.ok)return r.logger.debug(`Registered API Definition ${l.body.apiDefinitionId}`),{id:l.body.apiDefinitionId,ir:f};switch(l.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",l.error)}}var kNM=new Nfo({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function VEa({ir:e,apiDefinitionId:t,playgroundConfig:r,context:i}){return Ffo(Rfo(Tx({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:i}),oQ.ApiDefinitionId(t),kNM))}var Xz_=ue(require("path"),1);async function mPe({iconPath:e,filepaths:t}){e!=null&&typeof e=="string"&&Xz_.default.isAbsolute(e)&&t.add(e)}async function Zz_({parsedDocsConfig:e}){let t=new Set;return e.logo?.dark!=null&&t.add(e.logo.dark),e.logo?.light!=null&&t.add(e.logo.light),e.favicon!=null&&t.add(e.favicon),e.backgroundImage?.dark!=null&&t.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&t.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&t.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&t.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&t.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(i=>{i.image!=null&&t.add(i.image)}),(await Gvc({navigation:e.navigation})).forEach(i=>{t.add(i)}),e.navbarLinks&&await Promise.all(e.navbarLinks.map(async i=>{i.type==="dropdown"&&i.links.map(async n=>{n.icon&&await mPe({iconPath:n.icon,filepaths:t}),n.rightIcon&&await mPe({iconPath:n.rightIcon,filepaths:t})}),i.type!=="github"&&(i.icon&&await mPe({iconPath:i.icon,filepaths:t}),i.rightIcon&&await mPe({iconPath:i.rightIcon,filepaths:t}))})),e.js!=null&&e.js.files.forEach(i=>{t.add(i.absolutePath)}),t}async function Gvc({navigation:e}){let t=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(r=>ELn({item:r,filepaths:t})));break;case"tabbed":await Promise.all(e.items.map(async r=>{r.icon!=null&&await mPe({iconPath:r.icon,filepaths:t}),r.child.type==="layout"&&r.child.layout!=null?await Promise.all(r.child.layout.map(i=>ELn({item:i,filepaths:t}))):r.child.type==="variants"&&r.child.variants!=null&&await Promise.all(r.child.variants.flatMap(i=>{let n=[];return i.icon!=null&&n.push(mPe({iconPath:i.icon,filepaths:t})),n.push(...i.layout.map(a=>ELn({item:a,filepaths:t}))),n}))}));break;case"versioned":await Promise.all(e.versions.map(async r=>{r.landingPage!=null&&await ELn({item:r.landingPage,filepaths:t}),(await Gvc({navigation:r.navigation})).forEach(n=>t.add(n))}));break;case"productgroup":await Promise.all(e.products.map(async r=>{r.icon!=null&&await mPe({iconPath:r.icon,filepaths:t}),r.type==="internal"&&(r.landingPage!=null&&await ELn({item:r.landingPage,filepaths:t}),(await Gvc({navigation:r.navigation})).forEach(n=>t.add(n)))}));break}return t}async function ELn({item:e,filepaths:t}){switch(e.type){case"page":e.icon!=null&&await mPe({iconPath:e.icon,filepaths:t});break;case"section":e.icon!=null&&await mPe({iconPath:e.icon,filepaths:t}),await Promise.all(e.contents.map(r=>ELn({item:r,filepaths:t})));break;case"apiSection":e.icon!=null&&await mPe({iconPath:e.icon,filepaths:t});break;case"link":e.icon!=null&&await mPe({iconPath:e.icon,filepaths:t});break;case"changelog":e.icon!=null&&await mPe({iconPath:e.icon,filepaths:t});break}}async function kz_({navigation:e,apiWorkspaces:t,visitor:r,context:i}){tFM(e)?await Promise.all(e.map(async n=>{rFM(n)?await Promise.all(n.layout.map(async a=>{await I9o({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})})):iFM(n)&&await Promise.all(n.variants.flatMap(a=>a.layout.map(async o=>{await I9o({navigationItem:o,visitor:r,apiWorkspaces:t,context:i})})))})):await Promise.all(e.map(async n=>{await I9o({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function I9o({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await P8t(e,{alphabetized:Mt,api:Mt,apiName:Mt,audiences:Mt,displayErrors:Mt,tagDescriptionPages:Mt,snippets:Mt,summary:Mt,title:Mt,layout:Mt,collapsed:Mt,icon:Mt,slug:Mt,hidden:Mt,skipSlug:Mt,paginated:Mt,playground:Mt,flattened:Mt,path:Mt,page:Mt,featureFlag:Mt,openrpc:Mt,postman:Mt,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await I9o({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:Mt,orphaned:Mt,availability:Mt}),eFM(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function eFM(e){return e.api!=null}function tFM(e){return e[0]?.tab!=null}function rFM(e){return"layout"in e&&Array.isArray(e.layout)}function iFM(e){return"variants"in e&&Array.isArray(e.variants)}function z1(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}tN_.default.extend(rN_.default);var nFM=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),eN_=0,aFM=async({ir:e})=>(eN_++,`${e.apiName.snakeCase.unsafeName}-${eN_}`),LFt=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;targetAudiences;constructor({domain:t,docsWorkspace:r,ossWorkspaces:i,apiWorkspaces:n,taskContext:a,editThisPage:o,uploadFiles:c=nFM,registerApi:f=aFM,targetAudiences:s}){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=o,this.uploadFiles=c,this.registerApi=f,this.targetAudiences=s}#e=w9o.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 i=this.getRawProductAudiences(r.product);return this.shouldIncludeByAudience(i)})}:t}getRawProductAudiences(t){let i=this.docsWorkspace.config.products?.find(n=>n.displayName===t);return qya(i?.audiences)}getRawVersionAudiences(t){let i=this.docsWorkspace.config.versions?.find(n=>n.displayName===t);return qya(i?.audiences)}_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToSidebarTitle=new Map;markdownFilesToNoIndex=new Map;markdownFilesToTags=new Map;rawMarkdownFiles={};async resolve(){let t=performance.now(),r=process.memoryUsage();this.taskContext.logger.debug("Parsing docs configuration...");let i=performance.now();this._parsedDocsConfig=await mNs({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});let n=performance.now()-i,a=Object.keys(this.parsedDocsConfig.pages).length;this.taskContext.logger.debug(`Parsed docs configuration in ${n.toFixed(0)}ms: ${a} pages`),this.targetAudiences&&this.targetAudiences.length>0&&(this._parsedDocsConfig=this.applyAudienceFiltering(this._parsedDocsConfig)),this.taskContext.logger.debug("Storing raw markdown content...");for(let[L,G]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[Ze.of(L)]=G;let o=this.parsedDocsConfig.experimental?.openapiParserV3,c=o!=null&&!o;if(this.docsWorkspace.config.navigation!=null&&c){this.taskContext.logger.debug("Visiting navigation AST for changelog files...");let L=performance.now();await kz_({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:Re})=>{(await Re.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(Ie=>{let Ke=nb(this.docsWorkspace.absoluteFilePath,Ie.absoluteFilepath);this.parsedDocsConfig.pages[Ke]=Ie.contents,this.rawMarkdownFiles[Ze.of(Ke)]=Ie.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext});let G=performance.now()-L;this.taskContext.logger.debug(`Visited navigation AST in ${G.toFixed(0)}ms`)}this.taskContext.logger.debug("Building markdown file maps...");let f=performance.now();this.extractAllFrontmatterData(this.parsedDocsConfig.pages);let s=performance.now()-f;this.taskContext.logger.debug(`Built markdown file maps in ${s.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing referenced markdown and code files...");let u=performance.now();for(let[L,G]of Object.entries(this.parsedDocsConfig.pages)){let Re=await Z6o({markdown:G,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(L),context:this.taskContext});Re=await gvc({markdown:Re,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(L),context:this.taskContext}),this.parsedDocsConfig.pages[Ze.of(L)]=Re}let l=performance.now()-u;this.taskContext.logger.debug(`Replaced referenced content in ${l.toFixed(0)}ms`),this.taskContext.logger.debug("Collecting files from docs config...");let p=performance.now(),_=await Zz_({parsedDocsConfig:this.parsedDocsConfig}),h=performance.now()-p;this.taskContext.logger.debug(`Collected ${_.size} files in ${h.toFixed(0)}ms`),this.taskContext.logger.debug("Parsing image paths from markdown files...");let y=performance.now();for(let[L,G]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:Re,markdown:le}=w$i(G,{absolutePathToMarkdownFile:this.resolveFilepath(L),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);this.parsedDocsConfig.pages[Ze.of(L)]=le;for(let Ie of Re)_.add(Ie)}catch(Re){throw this.taskContext.logger.error(`Failed to parse ${L}: ${Re instanceof Error?Re.message:String(Re)}`),Re}let b=performance.now()-y;this.taskContext.logger.debug(`Parsed image paths in ${b.toFixed(0)}ms`);let v=Array.from(_).map(L=>({absoluteFilePath:L,relativeFilePath:this.toRelativeFilepath(L)}));this.taskContext.logger.info(`Uploading ${v.length} files...`);let O=performance.now(),A=await this.uploadFiles(v),g=performance.now()-O;this.taskContext.logger.info(`Uploaded ${A.length} files in ${g.toFixed(0)}ms`),A.forEach(L=>{this.collectedFileIds.set(L.absoluteFilePath,L.fileId)}),this.taskContext.logger.debug("Building navigation tree...");let m=performance.now(),j=await this.toRootNode(),M=performance.now()-m;this.taskContext.logger.debug(`Built navigation tree in ${M.toFixed(0)}ms`),this.taskContext.logger.debug("Getting fully qualified path names...");let E=performance.now(),D=await this.getMarkdownFilesToFullyQualifiedPathNames(j),B=performance.now()-E;this.taskContext.logger.debug(`Got path names in ${B.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing image paths and URLs in markdown...");let F=performance.now();for(let[L,G]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ze.of(L)]=vvc(G,this.collectedFileIds,D,{absolutePathToMarkdownFile:this.resolveFilepath(L),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let N=performance.now()-F;this.taskContext.logger.debug(`Replaced image paths in ${N.toFixed(0)}ms`),this.taskContext.logger.debug("Building page content...");let R={};Object.entries(this.parsedDocsConfig.pages).forEach(([L,G])=>{let Re=oFM(this.editThisPage,L),le=this.rawMarkdownFiles[Ze.of(L)];R[TW.PageId(L)]={markdown:G,editThisPageUrl:Re?TW.Url(Re):void 0,rawMarkdown:le}}),this.taskContext.logger.debug("Converting docs configuration...");let z=performance.now(),U=await this.convertDocsConfiguration(j),W=performance.now()-z;this.taskContext.logger.debug(`Converted docs configuration in ${W.toFixed(0)}ms`);let K={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){this.taskContext.logger.debug("Processing MDX components...");let L=performance.now(),G=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async le=>{let Ie=wu(this.docsWorkspace.absoluteFilePath,le);(await(0,C9o.stat)(Ie)).isDirectory()?(await ZF(Ie,"{js,ts,jsx,tsx,md,mdx}")).forEach(ne=>{G.add(ne)}):Ie.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&G.add(Ie)})),K=Object.fromEntries(await Promise.all([...G].map(async le=>{let Ie=this.toRelativeFilepath(le),Ke=(await(0,C9o.readFile)(le)).toString();return[Ie,Ke]})));let Re=performance.now()-L;this.taskContext.logger.debug(`Processed ${G.size} MDX component files in ${Re.toFixed(0)}ms`)}let fe=performance.now()-t,pe=process.memoryUsage();return this.taskContext.logger.debug(`Total resolve time: ${fe.toFixed(0)}ms, Memory delta: RSS=${((pe.rss-r.rss)/1024/1024).toFixed(2)}MB`),{config:U,pages:R,jsFiles:K}}resolveFilepath(t){if(t!=null)return wu(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return nb(this.docsWorkspace.absoluteFilePath,t)}extractAllFrontmatterData(t){for(let[r,i]of Object.entries(t)){let n=(0,iN_.default)(i),a=this.resolveFilepath(r),o=n.data.slug;if(typeof o=="string"&&o.trim().length>0){let u=o.trim();bvc(u)?this.markdownFilesToFullSlugs.set(a,u):this.taskContext.logger.warn(`Ignoring absolute URL slug "${u}" in ${r}. Absolute URLs are not allowed for frontmatter slugs.`)}let c=n.data["sidebar-title"];typeof c=="string"&&c.trim().length>0&&this.markdownFilesToSidebarTitle.set(a,c.trim());let f=n.data.noindex;typeof f=="boolean"&&this.markdownFilesToNoIndex.set(a,f);let s=n.data.tags;typeof s=="string"?this.markdownFilesToTags.set(a,s.split(",").map(u=>u.trim()).filter(u=>u.length>0)):Array.isArray(s)&&this.markdownFilesToTags.set(a,s)}}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},i=It.migrate.FernNavigationV1ToLatest.create().root(t);return It.NodeCollector.collect(i).slugMap.forEach((a,o)=>{if(a==null||!It.isPage(a))return;let c=It.getPageId(a);if(c==null)return;let f=Nt(this.docsWorkspace.absoluteFilePath,Ze.of(c));r[f]=o}),r}getDocsBasePath(){return new URL(z1(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(i=>({url:i.url,title:i.title}))}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?TW.Url(this.parsedDocsConfig.logo?.href):void 0,logoRightText:this.parsedDocsConfig.logo?.rightText,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>i.type==="dropdown"?{...i,links:i.links?.map(n=>({...n,url:TW.Url(n.url),icon:this.resolveIconFileId(n.icon),rightIcon:this.resolveIconFileId(n.rightIcon)})),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}:i.type==="github"?{...i,url:TW.Url(i.url)}:{...i,url:TW.Url(i.url),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}),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(i=>({...i,value:TW.Url(i.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!=null?{sidebar:this.parsedDocsConfig.theme.sidebar,body:this.parsedDocsConfig.theme.body,tabs:this.parsedDocsConfig.theme.tabs,"page-actions":this.parsedDocsConfig.theme.pageActions,footerNav:this.parsedDocsConfig.theme.footerNav}:void 0,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 i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}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.
1776
+ `),Lz_=!0}let c=new M9o(t,r,i,n),f=new Qvc,s,u=new Set;if(a!=null)try{let y=await(0,Uvc.readFile)(a,"utf-8");if(!SNM(y))return r.logger.debug("Non-OpenAPI spec detected, skipping AI example enhancement"),e;s=y,r.logger.debug(`Loaded OpenAPI spec (${y.length} characters) for AI enhancement`);let b=await Nvc(a,r);try{let v=await zvc({sourceFilePath:a,context:r});if(v.invalidCount>0){for(let{example:A}of v.invalidExamples){let g=`${A.method.toLowerCase()}:${A.endpointPath}`;u.add(g)}let O=await Uz_({sourceFilePath:a,context:r});r.logger.info(`Removed ${O.removedCount} stale AI examples, ${u.size} endpoints will be regenerated`)}else r.logger.debug("No stale AI examples found to remove")}catch(v){r.logger.debug(`Failed to clean up stale AI examples: ${v}`)}}catch(y){r.logger.debug(`Failed to read OpenAPI spec file: ${y}`)}let l=new Set;if(a!=null){let y=await Nvc(a,r);for(let b of y)u.has(b)||l.add(b);u.size>0&&r.logger.debug(`Coverage adjusted: ${y.size} total, ${l.size} preserved, ${u.size} marked for regeneration`)}let p={count:0,total:0},_=[],h=await BNM(e,c,r,n,p,_,l,u,s,a,o,f);if(_.length>0&&a!=null)try{await Fvc({enhancedExamples:_,sourceFilePath:a,context:r})}catch(y){r.logger.debug(`Failed to write AI examples override file: ${y}`)}return h}async function BNM(e,t,r,i,n,a,o,c,f,s,u,l){let p=[];for(let[g,m]of Object.entries(e.subpackages)){let j=Vz_(m,o,c);p.push(...j.map(M=>({...M,packageId:g})))}let _=Vz_(e.rootPackage,o,c);p.push(..._.map(g=>({...g,packageId:"root"}))),n.total+=p.length,r.logger.debug(`Collected ${p.length} work items across all packages`);let h=UEa.getInstance(),y=h.create(u||"API",p.length),b={count:0,total:p.length},v=await INM(p,t,r,i,n,a,f,s,y,b,l);h.finish(y);let O={};for(let[g,m]of Object.entries(e.subpackages)){let j=Wz_(m,v);O[g]=j}let A=Wz_(e.rootPackage,v);return{...e,subpackages:O,rootPackage:A}}function Vz_(e,t,r){let i=[],n=new Set;for(let a of e.endpoints){let o=a;if(!TNM(o))for(let f of o.examples){let s=`${o.method.toLowerCase()}:${f.path}`;if(n.has(s))continue;let u=r?.has(s);if(!u&&t.has(s)||!u&&!qNM(f))continue;let l=PLn(f.requestBodyV3),p=PLn(f.responseBodyV3);if(!(!u&&!l&&!p)){i.push({endpoint:o,example:f,endpointKey:s}),n.add(s);break}}}return i}async function INM(e,t,r,i,n,a,o,c,f,s,u){let l=new Map,p=parseInt(process.env.FERN_AI_MAX_CONCURRENT||"25",10);if(r.logger.debug(`Processing ${e.length} endpoints with max ${p} concurrent Lambda calls`),u?.shouldSkip())return r.logger.debug(`Circuit breaker is open after ${u.getFailureCount()} failures (threshold: ${u.getThreshold()}). Skipping AI enhancement for remaining endpoints.`),l;for(let _=0;_<e.length;_+=p){let h=e.slice(_,_+p),y=Math.floor(_/p)+1;if(r.logger.debug(`Processing chunk ${y} with ${h.length} endpoints concurrently`),u?.shouldSkip()){r.logger.debug(`Circuit breaker opened during processing. Stopping at chunk ${y}.`);break}let b=h.map((O,A)=>CNM(O,t,r,i,n,a,o,c,f,s,_+A+1,u)),v=await Promise.allSettled(b);for(let O=0;O<v.length;O++){let A=v[O];if(A)if(A.status==="fulfilled"&&A.value){let{endpointKey:g,enhancedReq:m,enhancedRes:j}=A.value;l.set(g,{enhancedReq:m,enhancedRes:j})}else A.status==="rejected"&&r.logger.debug(`Endpoint ${_+O+1} failed: ${A.reason}`)}if(c&&a.length>0)try{await Fvc({enhancedExamples:a,sourceFilePath:c,context:r}),r.logger.debug(`Saved ${a.length} examples after chunk ${y}`)}catch(O){r.logger.debug(`Failed to save incremental results: ${O}`)}}return l}async function CNM(e,t,r,i,n,a,o,c,f,s,u,l){let p=e.endpointKey;r.logger.debug(`Processing endpoint ${u}: ${e.endpoint.method} ${e.example.path}`);let _;o&&(_=await DNM(o,[{path:e.example.path,method:e.endpoint.method}],r));let h={method:e.endpoint.method,endpointPath:e.example.path,organizationId:i,operationSummary:e.endpoint.summary,operationDescription:e.endpoint.description,originalRequestExample:PLn(e.example.requestBodyV3),originalResponseExample:PLn(e.example.responseBodyV3),pathParameters:e.example.pathParameters,queryParameters:e.example.queryParameters,headers:e.example.headers,openApiSpec:_};for(let y=1;y<=2;y++)try{let b=await t.enhanceExample(h);l?.recordSuccess();let v=b.enhancedRequestExample!==h.originalRequestExample,O=b.enhancedResponseExample!==h.originalResponseExample;if(v||O){let A={endpoint:e.example.path,method:e.endpoint.method,pathParameters:e.example.pathParameters,queryParameters:e.example.queryParameters,headers:e.example.headers,requestBody:v?b.enhancedRequestExample:void 0,responseBody:O?b.enhancedResponseExample:void 0};return a.push(A),n.count++,s&&s.count++,r.logger.debug(`Successfully enhanced ${e.endpoint.method} ${e.example.path}`),f&&s&&UEa.getInstance().update(f,s.count),{endpointKey:p,enhancedReq:b.enhancedRequestExample,enhancedRes:b.enhancedResponseExample}}return r.logger.debug(`No changes needed for ${e.endpoint.method} ${e.example.path}`),{endpointKey:p,enhancedReq:b.enhancedRequestExample,enhancedRes:b.enhancedResponseExample}}catch(b){l?.recordFailure(),r.logger.debug(`Endpoint ${e.endpoint.method} ${e.example.path} attempt ${y} failed: ${b}`),y<2&&await new Promise(v=>setTimeout(v,1500))}return r.logger.debug(`Failed to enhance ${e.endpoint.method} ${e.example.path} after all attempts`),null}function Wz_(e,t){let r=e.endpoints.map(i=>{let n=i,a=n.examples.map(o=>{let c=`${n.method.toLowerCase()}:${o.path}`,f=t.get(c);if(f){let s={...o};return f.enhancedReq!==void 0&&o.requestBodyV3&&(s.requestBody=f.enhancedReq,s.requestBodyV3={...o.requestBodyV3,value:f.enhancedReq}),f.enhancedRes!==void 0&&o.responseBodyV3&&(s.responseBody=f.enhancedRes,s.responseBodyV3={...o.responseBodyV3,value:f.enhancedRes}),s}return o});return{...i,examples:a}});return{...e,endpoints:r}}function qNM(e){let t=!e.name||e.name===""||e.name==="Example",r=!e.description||e.description==="",i=B9o(PLn(e.requestBodyV3)),n=B9o(PLn(e.responseBodyV3));return t&&r&&i&&n}function B9o(e){return e==null?!1:typeof e=="string"?e===Tn.STRING||e===Tn.BASE64||e===Tn.DATE||e===Tn.DATE_TIME||e===Tn.UUID||e===Tn.BIG_INTEGER||Tn.SAMPLE_STRINGS.includes(e)||e==="":typeof e=="number"?e===Tn.DOUBLE||e===Tn.FLOAT||e===Tn.INT||e===Tn.INT64||e===Tn.UINT||e===Tn.UINT64||e===0:typeof e=="boolean"?e===Tn.BOOLEAN:Array.isArray(e)?e.length>0&&e.every(t=>B9o(t)):typeof e=="object"?Object.values(e).every(t=>B9o(t)):!1}function TNM(e){try{let t=e;if(t.v2Examples?.userSpecifiedExamples&&typeof t.v2Examples.userSpecifiedExamples=="object"){let r=t.v2Examples.userSpecifiedExamples;return Object.keys(r).length>0}if(t.v2Responses?.responses){for(let r of t.v2Responses.responses)if(r.body?.v2Examples?.userSpecifiedExamples&&typeof r.body.v2Examples.userSpecifiedExamples=="object"){let i=r.body.v2Examples.userSpecifiedExamples;if(Object.keys(i).length>0)return!0}}return!1}catch{return!1}}function PLn(e){if(e)switch(e.type){case"json":case"stream":case"sse":return e.value;case"filename":return;default:return e.value}}function xz_({auth:e,playgroundConfig:t,context:r}){if(e.schemes.length>0&&e.schemes[0]!=null){let i=e.schemes[0];return Gz_({scheme:i,playgroundConfig:t,context:r})}}function Gz_({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 i=e.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(n=>n.name.originalName).join(".")||"$.body.access_token";return t?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:_i.EndpointId(e.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:_i.JqString(i),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 i=e.tokenEndpoint.authenticatedRequestHeaders.find(a=>a.headerName.toLowerCase()==="authorization");if(i)return i.responseProperty.propertyPath!=null&&i.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:i.responseProperty.property.name.wireValue,description:e.docs};let n=e.tokenEndpoint.authenticatedRequestHeaders[0];return n?{type:"header",headerWireValue:n.headerName,prefix:n.valuePrefix,nameOverride:void 0,description:e.docs}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:Ot(e)}}function Hz_({auth:e,playgroundConfig:t,context:r}){let i={};for(let n of e.schemes){let a=Gz_({scheme:n,playgroundConfig:t,context:r});a!=null&&(i[_i.AuthSchemeId(n.key)]=a)}return i}function Jz_(e){return e._visit({alias:t=>({type:"alias",value:av(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:ED(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>_i.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:_i.PropertyKey(r.name.wireValue),valueType:av(r.valueType),availability:ED(r.availability),propertyAccess:r.propertyAccess})),extraProperties:NNM(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:_i.PropertyKey(i.name.wireValue),valueType:av(i.valueType),availability:ED(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?ED(i.availability):void 0,additionalProperties:vr.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[_i.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:_i.PropertyKey(n.name.wireValue),valueType:av(n.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:av(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName??r.type.name.originalName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function av(e){return e._visit({container:t=>vr.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:av(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:av(r),valueType:av(i)}),optional:r=>({type:"optional",itemType:av(r),defaultValue:void 0}),nullable:r=>({type:"nullable",itemType:av(r)}),set:r=>({type:"set",itemType:av(r)}),literal:r=>vr.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:_i.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:vr.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>zNM(t.v2),float:()=>Kz_(t.v2),double:()=>Kz_(t.v2),string:()=>RNM(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 RNM(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 zNM(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 Kz_(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 NNM(e){return typeof e=="boolean"?e?ii.unknown():void 0:typeof e=="string"?{type:"id",value:_i.TypeId(e),default:void 0}:av(e)}function Wvc(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?QNM(r,t):[],webhooks:i!=null?FNM(i):[],websockets:n!=null?[UNM(n,t)]:[],types:e.types.map(a=>_i.TypeId(a)),subpackages:e.subpackages.map(a=>_i.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?_i.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function FNM(e){return e.map(t=>{let r=[];return t.v2Examples!=null?(r.push(...Object.values(t.v2Examples.userSpecifiedExamples)),r.push(...Object.values(t.v2Examples.autogeneratedExamples))):r.push(...t.examples?.map(i=>({payload:i.payload.jsonExample}))??[]),{description:t.docs??void 0,id:_i.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??Dxi(t.name.originalName),headers:t.headers.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:av(i.valueType),availability:ED(i.availability)})),payload:$NM(t.payload),examples:r,responses:t.responses?.map(Vvc).filter(Zu)}})}function QNM(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let c,f=i.v2Examples.userSpecifiedExamples,s=i.v2Examples.autogeneratedExamples,u=Object.values(f).map(p=>p.response?.statusCode).filter((p,_,h)=>h.indexOf(p)!==_).length>0;for(let[p,_]of Object.entries(f))c=Yz_({shouldUseExampleName:u,exampleName:_.displayName??p,example:_,irEndpoint:i,irService:e,ir:t}),c!=null&&a.push(c);let l=Object.values(s).map(p=>p.response?.statusCode).filter((p,_,h)=>h.indexOf(p)!==_).length>0;for(let[p,_]of Object.entries(s))c=Yz_({shouldUseExampleName:l,exampleName:_.displayName??p,example:_,irEndpoint:i,irService:e,ir:t}),c!=null&&a.push(c)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(c=>Lvc({userSpecifiedExample:c,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(Zu));else if(n!=null){let c=Lvc({autogeneratedExample:n,irEndpoint:i,ir:t});c!=null&&a.push(c)}else if(i.response?.body?.type==="fileDownload"){let c=VFn({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(c.type==="success"){let f=Lvc({autogeneratedExample:c,irEndpoint:i,ir:t});if(f!=null){let s={...f,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let o={slug:void 0,availability:ED(i.availability??e.availability),auth:i.auth,authV2:LNM(i.security),multiAuth:VNM(i.security),description:i.docs??void 0,method:HNM(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?_i.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?WNM({environmentsConfig:t.environments,endpoint:i}):void 0,id:_i.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??Dxi(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(c=>({description:c.docs??void 0,key:_i.PropertyKey(c.name.originalName),type:av(c.valueType),availability:void 0,explode:void 0})),parts:[...wLn(i.basePath),...wLn(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(c=>({description:c.docs??void 0,key:_i.PropertyKey(c.name.originalName),type:av(c.valueType),availability:void 0,explode:void 0})),parts:[...t.basePath!=null?wLn(t.basePath):[],...wLn(e.basePath),...wLn(i.path)]},queryParameters:i.queryParameters.map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:av(c.valueType),availability:ED(c.availability),explode:void 0})),headers:[...e.headers,...i.headers].map(c=>({description:c.docs??void 0,key:c.name.wireValue,type:av(c.valueType),availability:ED(c.availability)})),request:i.requestBody!=null?$z_(i.requestBody):void 0,requestsV2:{requests:i.v2RequestBodies?.requestBodies?.map($z_).filter(Zu)},response:i.response!=null?Vvc(i.response):void 0,responsesV2:{responses:i.v2Responses?.responses?.map(Vvc).filter(Zu)},errors:void 0,errorsV2:KNM(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:c=>({type:"grpc",methodName:i.id,methodType:c.methodType}),_other:()=>{}}),includeInApiExplorer:i.apiPlayground};r.push(o)}return r}function UNM(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let i=Object.values(e.v2Examples.userSpecifiedExamples),n=Object.values(e.v2Examples.autogeneratedExamples),a=i.length>0?i[0]:n[0];a!=null&&r.push({name:"",description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(o=>({type:_i.api.v1.WebSocketMessageId(o.type),body:o.body}))??[]})}else r=e.examples.map(i=>({name:i.name?.originalName,description:i.docs,path:i.url,pathParameters:i.pathParameters.reduce((n,a)=>(n[_i.PropertyKey(a.name.originalName)]=a.value.jsonExample,n),{}),queryParameters:i.queryParameters.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),headers:i.headers.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),messages:i.messages.map(n=>({type:_i.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}));return{auth:e.auth,availability:ED(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?_i.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?xNM({environmentsConfig:t.environments,channel:e}):[],id:_i.WebSocketId(e.name.originalName),name:e.displayName??Dxi(e.name.originalName),path:{pathParameters:e.pathParameters.map(i=>({description:i.docs??void 0,key:_i.PropertyKey(i.name.originalName),type:av(i.valueType),availability:void 0,explode:void 0})),parts:wLn(e.path)},headers:e.headers.map(i=>({key:i.name.wireValue,type:av(i.valueType),description:i.docs,availability:ED(i.availability)})),queryParameters:e.queryParameters.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:av(i.valueType),availability:ED(i.availability),explode:void 0})),messages:e.messages.map(i=>({type:_i.api.v1.WebSocketMessageId(i.type),displayName:i.displayName,origin:i.origin,body:YNM(i.body),description:i.docs,availability:ED(i.availability)})),examples:r}}function LNM(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=>_i.AuthSchemeId(r))}function VNM(e){if(e!=null)return e.length===0?[]:e.map(t=>({schemes:Object.keys(t).map(r=>_i.AuthSchemeId(r))}))}function ED(e){if(e!=null)switch(e.status){case"DEPRECATED":return _i.Availability.Deprecated;case"PRE_RELEASE":return _i.Availability.Beta;case"GENERAL_AVAILABILITY":return _i.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return _i.Availability.Beta;default:Ot(e.status)}}function WNM({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl,n=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:_i.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(n!=null)return n.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:_i.EnvironmentId(o),baseUrl:f}})).filter((o,c,f)=>c===f.findIndex(s=>s.id===o.id&&s.baseUrl===o.baseUrl));if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let o=a.urls[i];if(o==null)throw new Error(`Encountered undefined server name "${i}" at endpoint ${t.method.toUpperCase()} ${t.path.head}. Expected environment ${a.id} to contain url for ${i}`);return{id:_i.EnvironmentId(a.id),baseUrl:o}});default:Ot(r)}}function xNM({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:_i.EnvironmentId(n.id),baseUrl:GNM(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Encountered undefined server name ${a} at channel ${t.name.originalName} ${t.path.head}. Expected environment ${n.id} to contain url for ${i}`);return{id:_i.EnvironmentId(n.id),baseUrl:a}});default:Ot(r)}}function GNM(e,t){return e.replace(/^[^:]+/,t)}function HNM(e){return vr.http.HttpMethod._visit(e,{get:()=>_i.HttpMethod.Get,post:()=>_i.HttpMethod.Post,put:()=>_i.HttpMethod.Put,patch:()=>_i.HttpMethod.Patch,delete:()=>_i.HttpMethod.Delete,head:()=>_i.HttpMethod.Head,_other:()=>{throw new Error("Unknown http method: "+e)}})}function wLn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:_i.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function $z_(e){let t=vr.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??aO.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>_i.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:_i.PropertyKey(i.name.wireValue),valueType:av(i.valueType),availability:ED(i.availability),propertyAccess:i.propertyAccess})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??aO.APPLICATION_JSON,shape:{type:"reference",value:av(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:o=>({type:"file",key:_i.PropertyKey(o.key.wireValue),isOptional:o.isOptional,contentType:o.contentType,description:o.docs??void 0,availability:void 0}),fileArray:o=>({type:"fileArray",key:_i.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:n=>({type:"bodyProperty",key:_i.PropertyKey(n.name.wireValue),valueType:av(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:ED(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(Zu)},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 Vvc(e){let t,r;return e.body!=null&&(r=vr.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:av(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:av(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:av(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}})),r!=null?{type:r,statusCode:e.statusCode,isWildcard:e.isWildcardStatusCode===!0?!0:void 0,description:t}:e.statusCode!=null?{statusCode:e.statusCode,isWildcard:e.isWildcardStatusCode===!0?!0:void 0,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function KNM(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:av(n.type)},statusCode:n.statusCode,isWildcard:n.isWildcardStatusCode===!0?!0:void 0,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:XNM(n,t),headers:n.headers!=null&&n.headers.length>0?n.headers.map(a=>({description:a.docs??void 0,key:a.name.wireValue,type:av(a.valueType),availability:ED(a.availability)})):void 0})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:_i.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0,propertyAccess:void 0}];n.type!=null&&a.push({key:_i.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:av(n.type),description:n.docs,availability:void 0,propertyAccess:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,isWildcard:n.isWildcardStatusCode===!0?!0:void 0,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(o=>({name:o.name?.originalName,responseBody:{type:"json",value:o.jsonExample},description:o.docs})),headers:n.headers!=null&&n.headers.length>0?n.headers.map(o=>({description:o.docs??void 0,key:o.name.wireValue,type:av(o.valueType),availability:ED(o.availability)})):void 0})}}return r}function Yz_({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:i,irService:n,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)}),n.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)});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,p]of Object.entries(c))(u[l]===null||u[l]===void 0)&&(u[l]=p);return u})(),requestBody:r.request?.requestBody,requestBodyV3:i.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:s=>{if(r.request==null)return;let u={};if($c(r.request.requestBody)){let l=r.request.requestBody;for(let p of s.properties)p._visit({file:_=>{let h=l[_.key.wireValue];if(_.type==="file")u[_.key.wireValue]={type:"filename",value:typeof h=="string"?h:"<file1>"};else if(_.type==="fileArray"){let y=(Array.isArray(h)?h:[h]).filter(b=>typeof b=="string");u[_.key.wireValue]={type:"filenames",value:y}}},bodyProperty:_=>{if(_.style==="exploded"){let h=l[_.name.wireValue];u[_.name.wireValue]={type:"exploded",value:Array.isArray(h)?h:[h]}}else u[_.name.wireValue]={type:"json",value:l[_.name.wireValue]}},_other:KOe})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??i.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(JNM)?{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(Zu)}}function JNM(e){return typeof e=="object"&&e!==null&&"event"in e&&typeof e?.event=="string"&&"data"in e}function Lvc({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.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:vr.ExampleTypeReferenceShape.primitive(vr.ExamplePrimitive.string({original:f}))}}}).filter(Zu),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[_i.PropertyKey(f.name.originalName)]=f.value.jsonExample,c),{}),queryParameters:a.queryParameters.reduce((c,f)=>(c[f.name.wireValue]=f.value.jsonExample,c),{}),headers:[...n,...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($c(a.request.jsonExample)){let s=a.request.jsonExample;for(let u of c.properties)u._visit({file:l=>{let p=s[l.key.wireValue];if(l.type==="file")f[l.key.wireValue]={type:"filename",value:typeof p=="string"?p:"<file1>"};else if(l.type==="fileArray"){let _=(Array.isArray(p)?p:[p]).filter(h=>typeof h=="string");f[l.key.wireValue]={type:"filenames",value:_}}},bodyProperty:l=>{if(l.style==="exploded"){let p=s[l.name.wireValue];f[l.name.wireValue]={type:"exploded",value:Array.isArray(p)?p:[p]}}else f[l.name.wireValue]={type:"json",value:s[l.name.wireValue]}},_other:KOe})}return{type:"form",value:f}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??vr.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=i.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=>dhe._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(Zu)}}function $NM(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>_i.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:_i.PropertyKey(t.name.wireValue),valueType:av(t.valueType),availability:ED(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:av(e.payloadType)},description:e.docs};default:Ot(e)}}function YNM(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>_i.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:_i.PropertyKey(t.name.wireValue),valueType:av(t.valueType),availability:ED(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:av(e.bodyType)};default:Ot(e)}}function XNM(e,t){let r=e.v2Examples?.userSpecifiedExamples,i=e.v2Examples?.autogeneratedExamples,n=e.examples;if(r!=null&&Object.keys(r).length>0)return Object.entries(r).map(([o,c])=>({name:o,responseBody:{type:"json",value:c},description:void 0}));if(i!=null&&Object.keys(i).length>0)return Object.entries(i).map(([o,c])=>({name:o,responseBody:{type:"json",value:c},description:void 0}));if(n.length>0)return n.map(o=>({name:o.name?.originalName,responseBody:{type:"json",value:o.jsonExample},description:o.docs}));let a=ZNM(e,t);return a!=null?[a]:[]}function ZNM(e,t){if(e.type==null||e.type.type!=="named")return;let r=e.type.typeId,i=t.types[r];if(i==null||i.shape.type!=="object")return;let n={},a=!1;for(let o of i.shape.properties){let c=o.name.wireValue,f=o.v2Examples;if(f?.userSpecifiedExamples!=null){let s=Object.values(f.userSpecifiedExamples);if(s.length>0){n[c]=s[0],a=!0;continue}}if(f?.autogeneratedExamples!=null){let s=Object.values(f.autogeneratedExamples);if(s.length>0){n[c]=s[0];continue}}}if(a)return{name:void 0,responseBody:{type:"json",value:n},description:void 0}}function Tx({ir:e,snippetsConfig:t,playgroundConfig:r,context:i}){let n={types:{},subpackages:{},rootPackage:Wvc(e.rootPackage,e),auth:xz_({auth:e.auth,playgroundConfig:r,context:i}),authSchemes:Hz_({auth:e.auth,playgroundConfig:r,context:i}),snippetsConfiguration:t,globalHeaders:e.headers.map(a=>({availability:ED(a.availability),description:a.docs??void 0,key:a.name.wireValue,type:av(a.valueType)})),navigation:void 0};for(let[a,o]of Object.entries(e.types))n.types[_i.TypeId(a)]={description:o.docs??void 0,name:o.name.name.originalName,shape:Jz_(o.shape),availability:ED(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;n.subpackages[_i.api.v1.SubpackageId(a)]={subpackageId:_i.api.v1.SubpackageId(a),displayName:c?.displayName??o.displayName,name:o.name.originalName,description:o.docs??void 0,...Wvc(o,e)}}return n}async function xvc({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:o,aiEnhancerConfig:c}){let f=kw({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new Zw(r,t)}),s=KGi({token:i.value}),u=Tx({ir:f,snippetsConfig:a,playgroundConfig:o,context:r});if(c){let h=t.getSources().find(y=>y.type==="openapi")?.absoluteFilePath;u=await jLn(u,c,r,i,e,h,f.apiName.originalName)}let l=await s.api.v1.register.registerApiDefinition({orgId:_i.OrgId(e),apiId:_i.ApiId(f.apiName.originalName),definition:u});if(l.ok)return r.logger.debug(`Registered API Definition ${l.body.apiDefinitionId}`),{id:l.body.apiDefinitionId,ir:f};switch(l.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",l.error)}}var kNM=new Nfo({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function VEa({ir:e,apiDefinitionId:t,playgroundConfig:r,context:i}){return Ffo(Rfo(Tx({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:i}),oQ.ApiDefinitionId(t),kNM))}var Xz_=ue(require("path"),1);async function mPe({iconPath:e,filepaths:t}){e!=null&&typeof e=="string"&&Xz_.default.isAbsolute(e)&&t.add(e)}async function Zz_({parsedDocsConfig:e}){let t=new Set;return e.logo?.dark!=null&&t.add(e.logo.dark),e.logo?.light!=null&&t.add(e.logo.light),e.favicon!=null&&t.add(e.favicon),e.backgroundImage?.dark!=null&&t.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&t.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&t.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&t.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&t.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(i=>{i.image!=null&&t.add(i.image)}),(await Gvc({navigation:e.navigation})).forEach(i=>{t.add(i)}),e.navbarLinks&&await Promise.all(e.navbarLinks.map(async i=>{i.type==="dropdown"&&i.links.map(async n=>{n.icon&&await mPe({iconPath:n.icon,filepaths:t}),n.rightIcon&&await mPe({iconPath:n.rightIcon,filepaths:t})}),i.type!=="github"&&(i.icon&&await mPe({iconPath:i.icon,filepaths:t}),i.rightIcon&&await mPe({iconPath:i.rightIcon,filepaths:t}))})),e.js!=null&&e.js.files.forEach(i=>{t.add(i.absolutePath)}),t}async function Gvc({navigation:e}){let t=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(r=>ELn({item:r,filepaths:t})));break;case"tabbed":await Promise.all(e.items.map(async r=>{r.icon!=null&&await mPe({iconPath:r.icon,filepaths:t}),r.child.type==="layout"&&r.child.layout!=null?await Promise.all(r.child.layout.map(i=>ELn({item:i,filepaths:t}))):r.child.type==="variants"&&r.child.variants!=null&&await Promise.all(r.child.variants.flatMap(i=>{let n=[];return i.icon!=null&&n.push(mPe({iconPath:i.icon,filepaths:t})),n.push(...i.layout.map(a=>ELn({item:a,filepaths:t}))),n}))}));break;case"versioned":await Promise.all(e.versions.map(async r=>{r.landingPage!=null&&await ELn({item:r.landingPage,filepaths:t}),(await Gvc({navigation:r.navigation})).forEach(n=>t.add(n))}));break;case"productgroup":await Promise.all(e.products.map(async r=>{r.icon!=null&&await mPe({iconPath:r.icon,filepaths:t}),r.type==="internal"&&(r.landingPage!=null&&await ELn({item:r.landingPage,filepaths:t}),(await Gvc({navigation:r.navigation})).forEach(n=>t.add(n)))}));break}return t}async function ELn({item:e,filepaths:t}){switch(e.type){case"page":e.icon!=null&&await mPe({iconPath:e.icon,filepaths:t});break;case"section":e.icon!=null&&await mPe({iconPath:e.icon,filepaths:t}),await Promise.all(e.contents.map(r=>ELn({item:r,filepaths:t})));break;case"apiSection":e.icon!=null&&await mPe({iconPath:e.icon,filepaths:t});break;case"link":e.icon!=null&&await mPe({iconPath:e.icon,filepaths:t});break;case"changelog":e.icon!=null&&await mPe({iconPath:e.icon,filepaths:t});break}}async function kz_({navigation:e,apiWorkspaces:t,visitor:r,context:i}){tFM(e)?await Promise.all(e.map(async n=>{rFM(n)?await Promise.all(n.layout.map(async a=>{await I9o({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})})):iFM(n)&&await Promise.all(n.variants.flatMap(a=>a.layout.map(async o=>{await I9o({navigationItem:o,visitor:r,apiWorkspaces:t,context:i})})))})):await Promise.all(e.map(async n=>{await I9o({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function I9o({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await P8t(e,{alphabetized:Mt,api:Mt,apiName:Mt,audiences:Mt,displayErrors:Mt,tagDescriptionPages:Mt,snippets:Mt,summary:Mt,title:Mt,layout:Mt,collapsed:Mt,icon:Mt,slug:Mt,hidden:Mt,skipSlug:Mt,paginated:Mt,playground:Mt,flattened:Mt,path:Mt,page:Mt,featureFlag:Mt,openrpc:Mt,postman:Mt,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await I9o({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:Mt,orphaned:Mt,availability:Mt}),eFM(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function eFM(e){return e.api!=null}function tFM(e){return e[0]?.tab!=null}function rFM(e){return"layout"in e&&Array.isArray(e.layout)}function iFM(e){return"variants"in e&&Array.isArray(e.variants)}function z1(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}tN_.default.extend(rN_.default);var nFM=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),eN_=0,aFM=async({ir:e})=>(eN_++,`${e.apiName.snakeCase.unsafeName}-${eN_}`),LFt=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;targetAudiences;constructor({domain:t,docsWorkspace:r,ossWorkspaces:i,apiWorkspaces:n,taskContext:a,editThisPage:o,uploadFiles:c=nFM,registerApi:f=aFM,targetAudiences:s}){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=o,this.uploadFiles=c,this.registerApi=f,this.targetAudiences=s}#e=w9o.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 i=this.getRawProductAudiences(r.product);return this.shouldIncludeByAudience(i)})}:t}getRawProductAudiences(t){let i=this.docsWorkspace.config.products?.find(n=>n.displayName===t);return qya(i?.audiences)}getRawVersionAudiences(t){let i=this.docsWorkspace.config.versions?.find(n=>n.displayName===t);return qya(i?.audiences)}_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToSidebarTitle=new Map;markdownFilesToNoIndex=new Map;markdownFilesToTags=new Map;rawMarkdownFiles={};async resolve(){let t=performance.now(),r=process.memoryUsage();this.taskContext.logger.debug("Parsing docs configuration...");let i=performance.now();this._parsedDocsConfig=await mNs({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});let n=performance.now()-i,a=Object.keys(this.parsedDocsConfig.pages).length;this.taskContext.logger.debug(`Parsed docs configuration in ${n.toFixed(0)}ms: ${a} pages`),this.targetAudiences&&this.targetAudiences.length>0&&(this._parsedDocsConfig=this.applyAudienceFiltering(this._parsedDocsConfig)),this.taskContext.logger.debug("Storing raw markdown content...");for(let[L,G]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[Ze.of(L)]=G;let o=this.parsedDocsConfig.experimental?.openapiParserV3,c=o!=null&&!o;if(this.docsWorkspace.config.navigation!=null&&c){this.taskContext.logger.debug("Visiting navigation AST for changelog files...");let L=performance.now();await kz_({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:Re})=>{(await Re.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(Ie=>{let Ke=nb(this.docsWorkspace.absoluteFilePath,Ie.absoluteFilepath);this.parsedDocsConfig.pages[Ke]=Ie.contents,this.rawMarkdownFiles[Ze.of(Ke)]=Ie.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext});let G=performance.now()-L;this.taskContext.logger.debug(`Visited navigation AST in ${G.toFixed(0)}ms`)}this.taskContext.logger.debug("Building markdown file maps...");let f=performance.now();this.extractAllFrontmatterData(this.parsedDocsConfig.pages);let s=performance.now()-f;this.taskContext.logger.debug(`Built markdown file maps in ${s.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing referenced markdown and code files...");let u=performance.now();for(let[L,G]of Object.entries(this.parsedDocsConfig.pages)){let Re=await Z6o({markdown:G,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(L),context:this.taskContext});Re=await gvc({markdown:Re,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(L),context:this.taskContext}),this.parsedDocsConfig.pages[Ze.of(L)]=Re}let l=performance.now()-u;this.taskContext.logger.debug(`Replaced referenced content in ${l.toFixed(0)}ms`),this.taskContext.logger.debug("Collecting files from docs config...");let p=performance.now(),_=await Zz_({parsedDocsConfig:this.parsedDocsConfig}),h=performance.now()-p;this.taskContext.logger.debug(`Collected ${_.size} files in ${h.toFixed(0)}ms`),this.taskContext.logger.debug("Parsing image paths from markdown files...");let y=performance.now();for(let[L,G]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:Re,markdown:le}=w$i(G,{absolutePathToMarkdownFile:this.resolveFilepath(L),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);this.parsedDocsConfig.pages[Ze.of(L)]=le;for(let Ie of Re)_.add(Ie)}catch(Re){throw this.taskContext.logger.error(`Failed to parse ${L}: ${Re instanceof Error?Re.message:String(Re)}`),Re}let b=performance.now()-y;this.taskContext.logger.debug(`Parsed image paths in ${b.toFixed(0)}ms`);let v=Array.from(_).map(L=>({absoluteFilePath:L,relativeFilePath:this.toRelativeFilepath(L)}));this.taskContext.logger.info(`Uploading ${v.length} files...`);let O=performance.now(),A=await this.uploadFiles(v),g=performance.now()-O;this.taskContext.logger.info(`Uploaded ${A.length} files in ${g.toFixed(0)}ms`),A.forEach(L=>{this.collectedFileIds.set(L.absoluteFilePath,L.fileId)}),this.taskContext.logger.debug("Building navigation tree...");let m=performance.now(),j=await this.toRootNode(),M=performance.now()-m;this.taskContext.logger.debug(`Built navigation tree in ${M.toFixed(0)}ms`),this.taskContext.logger.debug("Getting fully qualified path names...");let E=performance.now(),D=await this.getMarkdownFilesToFullyQualifiedPathNames(j),B=performance.now()-E;this.taskContext.logger.debug(`Got path names in ${B.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing image paths and URLs in markdown...");let F=performance.now();for(let[L,G]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Ze.of(L)]=vvc(G,this.collectedFileIds,D,{absolutePathToMarkdownFile:this.resolveFilepath(L),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let N=performance.now()-F;this.taskContext.logger.debug(`Replaced image paths in ${N.toFixed(0)}ms`),this.taskContext.logger.debug("Building page content...");let R={};Object.entries(this.parsedDocsConfig.pages).forEach(([L,G])=>{let Re=oFM(this.editThisPage,L),le=this.rawMarkdownFiles[Ze.of(L)];R[TW.PageId(L)]={markdown:G,editThisPageUrl:Re?TW.Url(Re):void 0,rawMarkdown:le}}),this.taskContext.logger.debug("Converting docs configuration...");let z=performance.now(),U=await this.convertDocsConfiguration(j),W=performance.now()-z;this.taskContext.logger.debug(`Converted docs configuration in ${W.toFixed(0)}ms`);let K={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){this.taskContext.logger.debug("Processing MDX components...");let L=performance.now(),G=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async le=>{let Ie=wu(this.docsWorkspace.absoluteFilePath,le);(await(0,C9o.stat)(Ie)).isDirectory()?(await ZF(Ie,"{js,ts,jsx,tsx,md,mdx}")).forEach(ne=>{G.add(ne)}):Ie.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&G.add(Ie)})),K=Object.fromEntries(await Promise.all([...G].map(async le=>{let Ie=this.toRelativeFilepath(le),Ke=(await(0,C9o.readFile)(le)).toString();return[Ie,Ke]})));let Re=performance.now()-L;this.taskContext.logger.debug(`Processed ${G.size} MDX component files in ${Re.toFixed(0)}ms`)}let fe=performance.now()-t,pe=process.memoryUsage();return this.taskContext.logger.debug(`Total resolve time: ${fe.toFixed(0)}ms, Memory delta: RSS=${((pe.rss-r.rss)/1024/1024).toFixed(2)}MB`),{config:U,pages:R,jsFiles:K}}resolveFilepath(t){if(t!=null)return wu(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return nb(this.docsWorkspace.absoluteFilePath,t)}extractAllFrontmatterData(t){for(let[r,i]of Object.entries(t)){let n=(0,iN_.default)(i),a=this.resolveFilepath(r),o=n.data.slug;if(typeof o=="string"&&o.trim().length>0){let u=o.trim();bvc(u)?this.markdownFilesToFullSlugs.set(a,u):this.taskContext.logger.warn(`Ignoring absolute URL slug "${u}" in ${r}. Absolute URLs are not allowed for frontmatter slugs.`)}let c=n.data["sidebar-title"];typeof c=="string"&&c.trim().length>0&&this.markdownFilesToSidebarTitle.set(a,c.trim());let f=n.data.noindex;typeof f=="boolean"&&this.markdownFilesToNoIndex.set(a,f);let s=n.data.tags;typeof s=="string"?this.markdownFilesToTags.set(a,s.split(",").map(u=>u.trim()).filter(u=>u.length>0)):Array.isArray(s)&&this.markdownFilesToTags.set(a,s)}}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},i=It.migrate.FernNavigationV1ToLatest.create().root(t);return It.NodeCollector.collect(i).slugMap.forEach((a,o)=>{if(a==null||!It.isPage(a))return;let c=It.getPageId(a);if(c==null)return;let f=Nt(this.docsWorkspace.absoluteFilePath,Ze.of(c));r[f]=o}),r}getDocsBasePath(){return new URL(z1(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(i=>({url:i.url,title:i.title}))}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?TW.Url(this.parsedDocsConfig.logo?.href):void 0,logoRightText:this.parsedDocsConfig.logo?.rightText,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>i.type==="dropdown"?{...i,links:i.links?.map(n=>({...n,url:TW.Url(n.url),icon:this.resolveIconFileId(n.icon),rightIcon:this.resolveIconFileId(n.rightIcon)})),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}:i.type==="github"?{...i,url:TW.Url(i.url)}:{...i,url:TW.Url(i.url),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}),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(i=>({...i,value:TW.Url(i.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!=null?{sidebar:this.parsedDocsConfig.theme.sidebar,body:this.parsedDocsConfig.theme.body,tabs:this.parsedDocsConfig.theme.tabs,"page-actions":this.parsedDocsConfig.theme.pageActions,footerNav:this.parsedDocsConfig.theme.footerNav}:void 0,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 i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}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.
1777
1777
  A valid API configuration was not found at the path: fern/apis/${t.apiName}.
1778
1778
  Learn more about project structure:
1779
1779
  https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`:`Failed to load API Definition referenced in docs.
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "3.15.0",
2
+ "version": "3.15.1",
3
3
  "repository": {
4
4
  "type": "git",
5
5
  "url": "git+https://github.com/fern-api/fern.git",