fern-api 3.31.0 → 3.31.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +4 -4
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1145,7 +1145,7 @@ ${EC_.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&Rjc(th
|
|
|
1145
1145
|
`+m_n.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?m_n.default.cyan(RC_(t,this.opt.mask)):m_n.default.italic(m_n.default.dim("[hidden]")):this.opt.mask?RC_(t,this.opt.mask):m_n.default.italic(m_n.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 f7o=ce(eR(),1);var Rq_=ce(y0c(),1),c7o=require("child_process"),ckn=require("fs"),s7o=ce(require("path"),1),zq_=ce(require("os"),1),Nq_=require("crypto"),ewc=ce(qq_(),1);var a7o=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var FWa=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var o7o=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var u7o=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function l7o(e="",t,r){let i=new twc(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 Tq_(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function LKM(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 twc=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=LKM(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??zq_.default.tmpdir(),r=(0,Nq_.randomUUID)(),i=Tq_(this.fileOptions.prefix),n=Tq_(this.fileOptions.postfix),a=`${i}${r}${n}`,o=s7o.default.resolve(t,a),c=s7o.default.resolve(t)+s7o.default.sep;if(!o.startsWith(c))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=o;let d={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(d.mode=this.fileOptions.mode),(0,ckn.writeFileSync)(this.tempFile,this.text,d)}catch(t){throw new a7o(t)}}readTemporaryFile(){try{let t=(0,ckn.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,Rq_.detect)(t)??"utf8";ewc.default.encodingExists(r)||(r="utf8"),this.text=ewc.default.decode(t,r)}}catch(t){throw new o7o(t)}}removeTemporaryFile(){try{(0,ckn.unlinkSync)(this.tempFile)}catch(t){throw new u7o(t)}}launchEditor(){try{let t=(0,c7o.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new FWa(t)}}launchEditorAsync(t){try{(0,c7o.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new FWa(r)}}};var Fq_=ce(ive(),1);var QWa=class extends tR{_run(t){this.done=t,this.editorResult=new Fq_.Subject;let r=F4(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"?f7o.default.dim("Received"):f7o.default.dim("Press <enter> to launch your preferred editor."),t&&(r=f7o.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),l7o(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 Wq_=require("stream");var Lq_=ce(require("readline"),1),Vq_=ce(Uq_(),1),E_n=class{constructor(t){this.rl||=Lq_.default.createInterface(WKM(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 WKM(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 Vq_.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var UWa=class extends E_n{constructor(t={}){super(t),this.log=new Wq_.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return PWa(this.rl,this.bottomBar.split(`
|
|
1146
1146
|
`).length),this}updateBottomBar(t){return PWa(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+`
|
|
1147
1147
|
`}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&&qHo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var kO=ce(ive(),1),xq_=ce(G8a(),1);var d7o=ce(ive(),1),Gq_=ce(G8a(),1),p7o=function(e,t,r){return typeof e[t]!="function"?(0,d7o.of)(e):(0,d7o.from)((0,Gq_.default)(e[t])(r).then(i=>(e[t]=i,e)))};var Hq_={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}},lkn=class extends E_n{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,kO.from)(t):(0,kO.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,kO.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,kO.from)([t]),this.process=i.pipe((0,kO.concatMap)(this.processQuestion.bind(this)),(0,kO.publish)()),this.process.connect(),this.process.pipe((0,kO.reduce)((n,a)=>(Hq_.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,kO.defer)(()=>(0,kO.of)(t).pipe((0,kO.concatMap)(this.setDefaultType.bind(this)),(0,kO.concatMap)(this.filterIfRunnable.bind(this)),(0,kO.concatMap)(()=>p7o(t,"message",this.answers)),(0,kO.concatMap)(()=>p7o(t,"default",this.answers)),(0,kO.concatMap)(()=>p7o(t,"choices",this.answers)),(0,kO.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,kO.defer)(()=>(0,kO.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,kO.defer)(()=>(0,kO.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&Hq_.get(this.answers,t.name)!==void 0)return kO.EMPTY;if(t.when===!1)return kO.EMPTY;if(typeof t.when!="function")return(0,kO.of)(t);let{answers:r}=this;return(0,kO.defer)(()=>(0,kO.from)((0,xq_.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,kO.filter)(i=>i!=null)))}};function Kq_(e){let t=function(r,i){let n;try{n=new lkn(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",wWa),this.registerPrompt("input",A_n),this.registerPrompt("number",EWa),this.registerPrompt("confirm",SWa),this.registerPrompt("rawlist",MWa),this.registerPrompt("expand",DWa),this.registerPrompt("checkbox",BWa),this.registerPrompt("password",IWa),this.registerPrompt("editor",QWa)},t.restoreDefaultPrompts(),t}var iwc=Kq_();function HKM(e,t){iwc.registerPrompt(e,t)}function xKM(){iwc.restoreDefaultPrompts()}var KKM={prompt:iwc,ui:{BottomBar:UWa,Prompt:lkn},createPromptModule:Kq_,registerPrompt:HKM,restoreDefaultPrompts:xKM,Separator:d$},_7o=KKM;var fkn=require("path");function $q_(){let e=JKM();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function JKM(e=process.argv[1]?(0,fkn.dirname)(process.argv[1]):process.cwd(),t=fkn.sep==="\\"){let r=t?Jq_(e):e;return i=>{if(!i)return;let n=t?Jq_(i):i,{dir:a,base:o,ext:c}=fkn.posix.parse(n);(c===".js"||c===".mjs"||c===".cjs")&&(o=o.slice(0,-1*c.length));let d=decodeURIComponent(o);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${d}`;if(a.startsWith(r)){let u=a.slice(r.length+1).replace(/\//g,".");return u?`${u}:${d}`:d}return d}}function Jq_(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var nwc=e=>{if("flags"in e){let t=Yq_(e.flags),r=Xq_(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,Zq_(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,$KM(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function $KM(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 Yq_=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,S_n(r)]).filter(([,t])=>t!==void 0)),Xq_=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?Zq_(i):void 0]}))};var S_n=e=>e===void 0?void 0:e.variant??e.enabled,Zq_=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var h7o="0123456789abcdef",y7o=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length===16)return new e(t);throw new TypeError("not 128-bit length")}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/256,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;default: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)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=h7o.charAt(this.bytes[r]>>>4),t+=h7o.charAt(15&this.bytes[r]),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=h7o.charAt(this.bytes[r]>>>4),t+=h7o.charAt(15&this.bytes[r]);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}},awc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??YKM()}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))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return y7o.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}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,y7o.ofInner(t)}},YKM=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),kq_,HJt=()=>XKM().toString(),XKM=()=>(kq_||(kq_=new awc)).generate();var ZKM=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],e1_=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return ZKM.concat(t).some(i=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};var _$=(function(e){return 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.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e})({});var eJM=Array.isArray,t1_=Object.prototype,zA9=t1_.hasOwnProperty,owc=t1_.toString,r1_=eJM||function(e){return owc.call(e)==="[object Array]"};var dkn=e=>e===void 0,LWa=e=>owc.call(e)=="[object String]",i1_=e=>LWa(e)&&e.trim().length===0;var n1_=e=>owc.call(e)=="[object Number]";var uwc=e=>e instanceof Error;function tJM(e,t){try{return e instanceof t}catch{return!1}}function VWa(e){return e===null||typeof e!="object"}function M_n(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function a1_(e){return M_n(e,"ErrorEvent")}function b7o(e){return!dkn(Event)&&tJM(e,Event)}function o1_(e){return M_n(e,"Object")}function WWa(e,t,r,i,n){return t>r&&(i.warn("min cannot be greater than max."),t=r),n1_(e)?e>r?(i.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+n),WWa(n||r,t,r,i))}var rJM=864e5,v7o=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=WWa(t.bucketSize,0,100,t._logger),this._refillRate=WWa(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=WWa(t.refillInterval,0,rJM,t._logger)}_applyRefill(t,r){let i=r-t.lastAccess,n=Math.floor(i/this._refillInterval);if(n>0){let a=n*this._refillRate;t.tokens=Math.min(t.tokens+a,this._bucketSize),t.lastAccess=t.lastAccess+n*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),i=String(t),n=this._buckets[i];return n?this._applyRefill(n,r):(n={tokens:this._bucketSize,lastAccess:r},this._buckets[i]=n),n.tokens===0?!0:(n.tokens--,n.tokens===0&&this._onBucketRateLimited?.(t),n.tokens===0)}stop(){this._buckets={}}};var g7o=class{add(t){let r=HJt();return this.promiseByIds[r]=t,t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds),r=t.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}};function iJM(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var u1_=(e,t,r)=>{function i(a,...o){t(()=>{let c=r[a];c(e,...o)})}return{info:(...a)=>{i("log",...a)},warn:(...a)=>{i("warn",...a)},error:(...a)=>{i("error",...a)},critical:(...a)=>{r.error(e,...a)},createLogger:a=>u1_(`${e} ${a}`,t,r)}},nJM=e=>e();function s1_(e,t=nJM){return u1_(e,t,iJM())}var _kn="Mobile",A7o="iOS",pkn="Android",c1_="Tablet",JA9=pkn+" "+c1_;var aJM="Apple",$A9=aJM+" Watch",l1_="Safari",m7o="BlackBerry",f1_="Samsung",oJM=f1_+"Browser",uJM=f1_+" Internet",P7o="Chrome",sJM=P7o+" OS",cJM=P7o+" "+A7o,d1_="Internet Explorer",lJM=d1_+" "+_kn,cwc="Opera",YA9=cwc+" Mini",p1_="Edge",fJM="Microsoft "+p1_,lwc="Firefox",dJM=lwc+" "+A7o,fwc="Nintendo",dwc="PlayStation",O7o="Xbox",pJM=pkn+" "+_kn,_JM=_kn+" "+l1_,GWa="Windows",hJM=GWa+" Phone";var _1_="Generic",XA9=_1_+" "+_kn.toLowerCase(),ZA9=_1_+" "+c1_.toLowerCase(),yJM="Konqueror",IG="(\\d+(\\.\\d+)?)",swc=new RegExp("Version/"+IG),kA9=new RegExp(O7o,"i"),em9=new RegExp(dwc+" \\w+","i"),tm9=new RegExp(fwc+" \\w+","i"),bJM=new RegExp(m7o+"|PlayBook|BB10","i"),vJM={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var rm9={[lJM]:[new RegExp("rv:"+IG)],[fJM]:[new RegExp(p1_+"?\\/"+IG)],[P7o]:[new RegExp("("+P7o+"|CrMo)\\/"+IG)],[cJM]:[new RegExp("CriOS\\/"+IG)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+IG)],[l1_]:[swc],[_JM]:[swc],[cwc]:[new RegExp("("+cwc+"|OPR)\\/"+IG)],[lwc]:[new RegExp(lwc+"\\/"+IG)],[dJM]:[new RegExp("FxiOS\\/"+IG)],[yJM]:[new RegExp("Konqueror[:/]?"+IG,"i")],[m7o]:[new RegExp(m7o+" "+IG),swc],[pJM]:[new RegExp("android\\s"+IG,"i")],[uJM]:[new RegExp(oJM+"\\/"+IG)],[d1_]:[new RegExp("(rv:|MSIE )"+IG)],Mozilla:[new RegExp("rv:"+IG)]};var im9=[[new RegExp(O7o+"; "+O7o+" (.*?)[);]","i"),e=>[O7o,e&&e[1]||""]],[new RegExp(fwc,"i"),[fwc,""]],[new RegExp(dwc,"i"),[dwc,""]],[bJM,[m7o,""]],[new RegExp(GWa,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[hJM,""];if(new RegExp(_kn).test(t)&&!/IEMobile\b/.test(t))return[GWa+" "+_kn,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=vJM[i]||"";return/arm/i.test(t)&&(n="RT"),[GWa,n]}return[GWa,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[A7o,t.join(".")]}return[A7o,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=dkn(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+pkn+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+pkn+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[pkn,t.join(".")]}return[pkn,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[sJM,""]],[/Linux|debian/i,["Linux",""]]];var h1_="utf8";function y1_(e,t){if(!e||typeof e!="string"||gJM(e))throw new Error(t)}function gJM(e){return e.trim().length===0}function b1_(e){return e?.replace(/\/+$/,"")}async function v1_(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 j7o(){return new Date().toISOString()}function D_n(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var g1_=e=>e instanceof Error;function pwc(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var w7o=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)}};function O1_(){return"CompressionStream"in globalThis}async function _wc(e,t=!0){try{let i=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(i).blob()}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var hkn=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()}},HWa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function A1_(e){if(e instanceof hkn){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 hwc(e){return typeof e=="object"&&(e instanceof hkn||e instanceof HWa)}function m1_(e){return typeof e=="object"&&e instanceof hkn&&e.status===413}var xWa=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new g7o,this._events=new w7o,this._isInitialized=!1,y1_(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=b1_(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.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:hwc},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.evaluationEnvironments=r?.evaluationEnvironments,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=s1_("[PostHog]",this.logMsgIfDebug.bind(this)),this.disableCompression=!O1_()||(r?.disableCompression??!1)}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(_$.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(_$.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(_$.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>this._logger.info(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){return this.promiseQueue.add(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._logger.error("Remote config could not be loaded",n),this._events.emit("error",n)})}async getFlags(t,r={},i={},n={},a={},o=!0){await this._initPromise;let c=o?"&config=true":"",d=`${this.host}/flags/?v=2${c}`,s={token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a};this.evaluationEnvironments&&this.evaluationEnvironments.length>0&&(s.evaluation_environments=this.evaluationEnvironments);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(s)};return this._logger.info("Flags URL",d),this.fetchWithRetry(d,u,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(l=>l.json()).then(l=>nwc(l)).catch(l=>{this._events.emit("error",l)})}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 d=S_n(c.response);return d===void 0&&(d=!1),{response:d,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,evaluatedAt:c.evaluatedAt}}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 d=c[t];return d===void 0?null:d}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 d=await this.getFlags(t,r,i,n,c);if(d!==void 0)return d.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),d.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:d?.requestId}):d}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("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._logger.error(c),this._events.emit("error",new Error(o));return}return a.json()}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}))?.surveys;return n&&this._logger.info("Surveys fetched from API: ",JSON.stringify(n)),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(_$.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(_$.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(_$.Props,this.props)})}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,r,i),a=this.getPersistedProperty(_$.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),a.push({message:n}),this.setPersistedProperty(_$.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=D_n(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n={api_key:this.apiKey,batch:[this.prepareMessage(t,r,i)],sent_at:j7o()};this.historicalMigration&&(n.historical_migration=!0);let a=JSON.stringify(n),o=`${this.host}/batch/`,c=this.disableCompression?null:await _wc(a,this.isDebug),d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...c!==null&&{"Content-Encoding":"gzip"}},body:c||a};try{await this.fetchWithRetry(o,d)}catch(s){this._events.emit("error",s)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:j7o(),uuid:i?.uuid?i.uuid:HJt()};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 A1_(t)})}async flush(){let t=pwc([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),pwc([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(_$.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(_=>_.message),o=()=>{let h=(this.getPersistedProperty(_$.Queue)||[]).slice(n.length);this.setPersistedProperty(_$.Queue,h),t=h},c={api_key:this.apiKey,batch:a,sent_at:j7o()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=`${this.host}/batch/`,u=this.disableCompression?null:await _wc(d,this.isDebug),l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||d},p={retryCheck:_=>m1_(_)?!1:hwc(_)};try{await this.fetchWithRetry(s,l,p)}catch(_){if(m1_(_)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw _ instanceof HWa||o(),this._events.emit("error",_),_}o(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){AbortSignal.timeout??=function(c){let d=new AbortController;return setTimeout(()=>d.abort(),c),d.signal};let a=r.body?r.body:"",o=-1;try{o=a instanceof Blob?a.size:Buffer.byteLength(a,h1_)}catch{a instanceof Blob?o=a.size:o=new TextEncoder().encode(a).length}return await v1_(async()=>{let c=null;try{c=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(s){throw new HWa(s)}if(!(r.mode==="no-cors")&&(c.status<200||c.status>=400))throw new hkn(c,o);return c},{...this._retryOptions,...i})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(_$.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!hwc(n))throw n;await A1_(n)}};return Promise.race([new Promise((n,a)=>{D_n(()=>{this._logger.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._logger.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}};var h$={};Zt(h$,{DOMExceptionCoercer:()=>bwc,ErrorCoercer:()=>vwc,ErrorEventCoercer:()=>gwc,ErrorPropertiesBuilder:()=>ywc,EventCoercer:()=>mwc,ObjectCoercer:()=>Awc,PrimitiveCoercer:()=>Pwc,PromiseRejectionEventCoercer:()=>jwc,ReduceableCache:()=>wwc,StringCoercer:()=>Owc,chromeStackLineParser:()=>w1_,createStackParser:()=>qJM,geckoStackLineParser:()=>S1_,nodeStackLineParser:()=>I1_,opera10StackLineParser:()=>M1_,opera11StackLineParser:()=>D1_,reverseAndStripFrames:()=>T1_,winjsStackLineParser:()=>E1_});var E7o,P1_,S7o;function j1_(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return S7o&&r.length===P1_||(P1_=r.length,S7o=r.reduce((i,n)=>{E7o||(E7o={});let a=E7o[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,E7o[n]=[s,u];break}}}return i},{})),S7o}var OJM=4,ywc=class{constructor(t,r,i=[]){this.coercers=t,this.stackParser=r,this.modifiers=i}buildFromUnknown(t,r={}){let n=r&&r.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(n,r,0).apply(t),c=this.buildParsingContext(),d=this.parseStacktrace(o,c);return{$exception_list:this.convertToExceptionList(d,n),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&r1_(r.stacktrace.frames)&&(r.stacktrace.frames=await this.applyModifiers(r.stacktrace.frames));return t}coerceFallback(t){return{type:"Error",value:"Unknown error",stack:t.syntheticException?.stack,synthetic:!0}}parseStacktrace(t,r){let i;t.cause!=null&&(i=this.parseStacktrace(t.cause,r));let n;return t.stack!=""&&t.stack!=null&&(n=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?1:0),r.chunkIdMap)),{...t,cause:i,stack:n}}applyChunkIds(t,r){return t.map(i=>(i.filename&&r&&(i.chunk_id=r[i.filename]),i))}applyCoercers(t,r){for(let i of this.coercers)if(i.match(t))return i.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let i of this.modifiers)r=await i(r);return r}convertToExceptionList(t,r){let i={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(i.stacktrace={type:"raw",frames:t.stack});let n=[i];return t.cause!=null&&n.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),n}buildParsingContext(){return{chunkIdMap:j1_(this.stackParser)}}buildCoercingContext(t,r,i=0){let n=(o,c)=>{if(c<=OJM){let d=this.buildCoercingContext(t,r,c);return this.applyCoercers(o,d)}};return{...r,syntheticException:i==0?r.syntheticException:void 0,mechanism:t,apply:o=>n(o,i),next:o=>n(o,i+1)}}};var U4="?";function xJt(e,t,r,i,n){let a={platform:e,filename:t,function:r==="<anonymous>"?U4:r,in_app:!0};return dkn(i)||(a.lineno=i),dkn(n)||(a.colno=n),a}var M7o=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return r||i?[e.indexOf("@")!==-1?e.split("@")[0]:U4,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var AJM=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,mJM=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,PJM=/\((\S*)(?::(\d+))(?::(\d+))\)/,w1_=(e,t)=>{let r=AJM.exec(e);if(r){let[,n,a,o]=r;return xJt(t,n,U4,+a,+o)}let i=mJM.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let c=PJM.exec(i[2]);c&&(i[2]=c[1],i[3]=c[2],i[4]=c[3])}let[a,o]=M7o(i[1]||U4,i[2]);return xJt(t,o,a,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var jJM=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,E1_=(e,t)=>{let r=jJM.exec(e);return r?xJt(t,r[2],r[1]||U4,+r[3],r[4]?+r[4]:void 0):void 0};var wJM=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,EJM=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,S1_=(e,t)=>{let r=wJM.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=EJM.exec(r[3]);o&&(r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]="")}let n=r[3],a=r[1]||U4;return[a,n]=M7o(a,n),xJt(t,n,a,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var SJM=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,M1_=(e,t)=>{let r=SJM.exec(e);return r?xJt(t,r[2],r[3]||U4,+r[1]):void 0},MJM=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,D1_=(e,t)=>{let r=MJM.exec(e);return r?xJt(t,r[5],r[3]||r[4]||U4,+r[1],+r[2]):void 0};var DJM=/^\s*[-]{4,}$/,BJM=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,I1_=(e,t)=>{let r=e.match(BJM);if(r){let i,n,a,o,c;if(r[1]){a=r[1];let u=a.lastIndexOf(".");if(a[u-1]==="."&&u--,u>0){i=a.slice(0,u),n=a.slice(u+1);let l=i.indexOf(".Module");l>0&&(a=a.slice(l+1),i=i.slice(0,l))}o=void 0}n&&(o=i,c=n),n==="<anonymous>"&&(c=void 0,a=void 0),a===void 0&&(c=c||U4,a=o?`${o}.${c}`:c);let d=r[2]?.startsWith("file://")?r[2].slice(7):r[2],s=r[5]==="native";return d?.match(/\/[A-Z]:/)&&(d=d.slice(1)),!d&&r[5]&&!s&&(d=r[5]),{filename:d?decodeURI(d):void 0,module:void 0,function:a,lineno:B1_(r[3]),colno:B1_(r[4]),in_app:IJM(d||"",s),platform:t}}if(e.match(DJM))return{filename:e,platform:t}};function IJM(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 B1_(e){return parseInt(e||"",10)||void 0}var C1_=/\(error: (.*)\)/,q1_=50;function T1_(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,q1_).map(r=>({...r,filename:r.filename||CJM(t).filename,function:r.function||U4}))}function CJM(e){return e[e.length-1]||{}}function qJM(e,...t){return(r,i=0)=>{let n=[],a=r.split(`
|
|
1148
|
-
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=C1_.test(c)?c.replace(C1_,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=q1_)break}}return T1_(n)}}var bwc=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=LWa(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return M_n(t,"DOMException")}isDOMError(t){return M_n(t,"DOMError")}};var vwc=class{match(t){return uwc(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var gwc=class{constructor(){}match(t){return a1_(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var TJM=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Owc=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(TJM);return n&&(r=n[1],i=n[2]),[r,i]}};var R1_=["fatal","error","warning","log","info","debug"];function D7o(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var Awc=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return b7o(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=D7o(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return LWa(t)&&!i1_(t)&&R1_.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(g1_(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var mwc=class{match(t){return b7o(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${D7o(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Pwc=class{match(t){return VWa(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var jwc=class{match(t){return M_n(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return VWa(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(VWa(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var wwc=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)}}};var F1_=require("fs"),Q1_=require("readline"),B7o=new h$.ReduceableCache(25),U1_=new h$.ReduceableCache(20),Ewc=7,RJM=1e3,zJM=1e4;async function L1_(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"||UJM(o)||LJM(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(U1_.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=WJM(a);if(o.every(d=>VJM(n,d)))continue;let c=GJM(B7o,n,{});i.push(NJM(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&FJM(e,B7o),B7o.reduce(),e}function NJM(e,t,r){return new Promise(i=>{let n=(0,F1_.createReadStream)(e),a=(0,Q1_.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],l=s[1];function p(){U1_.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]=HJM(_,0),c>=l)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],l=h[1]}})})}function FJM(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;QJM(r.lineno,r,i)}}function QJM(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=V1_(e);n<e;n++){let a=r[n];if(a===void 0)return void z1_(t);t.pre_context.push(a)}if(r[e]===void 0)return void z1_(t);t.context_line=r[e];let i=W1_(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 z1_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function UJM(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function LJM(e){return e.lineno!==void 0&&e.lineno>zJM||e.colno!==void 0&&e.colno>RJM}function VJM(e,t){let r=B7o.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 WJM(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=N1_(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+Ewc:(n.push(i),i=N1_(a)),t++}return n}function N1_(e){return[V1_(e),W1_(e)]}function V1_(e){return Math.max(1,e-Ewc)}function W1_(e){return e+Ewc}function GJM(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function HJM(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}function xJM(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(i))},{_posthogErrorHandler:!0})}function G1_(e,t){globalThis.process?.on("uncaughtException",xJM(e,t))}function H1_(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var KJM=2e3,SFi=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new v7o({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||HJt(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(G1_(this.onException.bind(this),this.onFatalError.bind(this)),H1_(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)})())}async onFatalError(t){console.error(t),await this.client.shutdown(KJM),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var x1_="5.17.4";async function K1_(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}var JJM=6e4,$JM=1152921504606847e3,YJM=["is_not"],ykn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},v0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},KJt=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},I7o=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||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,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;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof KJt||d instanceof v0?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(l=>this.featureFlagsByKey[l]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async l=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(l,t,r,i,n,void 0,u);o[l.key]=p,_&&(c[l.key]=_)}catch(p){p instanceof KJt||p instanceof v0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${l.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${l.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new v0("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new v0("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new v0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new v0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new v0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new v0(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let l=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=l}catch(l){throw new v0(`Error evaluating flag dependency '${d}' for flag '${a}': ${l}`)}else n[d]=!1;else throw new v0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new v0(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,l=a.multivariate?.variants||[];d=u&&l.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof KJt)throw u;if(u instanceof v0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new v0("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?Z1_(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):X1_(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await J1_(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await J1_(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}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(JJM,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0;return;case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new ykn(`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 ykn(`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 ykn(`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 i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof ykn&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=D_n(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function J1_(e,t,r=""){let i=await K1_(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/$JM}function X1_(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 v0("Operator is_not_set is not supported")}else throw new v0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!YJM.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 d(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 $1_(String(n))&&String(o).match(String(n))!==null;case"not_regex":return $1_(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?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new v0("Date operations cannot be performed on boolean values");let s=ZJM(String(n));if(s==null&&(s=Y1_(n)),s==null)throw new v0(`Invalid date: ${n}`);let u=Y1_(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new v0(`Unknown operator: ${a}`)}}function XJM(e,t){if(!(e in t))throw new KJt(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function Z1_(e,t,r,i=!1){let n=String(e.value);XJM(n,r);let a=r[n];return k1_(a,t,r,i)}function k1_(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 d=k1_(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof KJt)throw d;if(d instanceof v0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new v0("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=Z1_(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=X1_(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof KJt)throw d;if(d instanceof v0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new v0("can't match cohort without a given cohort property value");return n==="AND"}function $1_(e){try{return new RegExp(e),!0}catch{return!1}}function Y1_(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 v0(`${e} is in an invalid date format`)}throw new v0(`The date provided ${e} must be a string, number, or date object`)}function ZJM(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{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()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var C7o=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var kJM=100,eT_=3e4,e$M=5e4,q7o=class extends xWa{constructor(t,r={}){if(super(t,r),this._memoryStorage=new C7o,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,kJM):eT_,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.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new I7o({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider}))}this.errorTracking=new SFi(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||e$M}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):fetch(t,r)}getLibraryVersion(){return x1_}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._logger.warn("Called capture() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{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=eT_){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:d,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,d,s);d=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=this.options.sendFeatureFlagEvent??!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=l!==void 0,_,h,y;if(!p&&!o){let v=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(v===void 0)return;y=v.response,l=S_n(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${l}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(b))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(b):this.distinctIdHasSentFlagCalls[r]=[b],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,$feature_flag_id:y?.metadata?.id,$feature_flag_version:y?.metadata?.version,$feature_flag_reason:y?.reason?.description??y?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:l,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,personProperties:d,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,a,d,s);d=u.allPersonProperties,s=u.allGroupProperties;let l;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let h=this.featureFlagsPoller?.featureFlagsByKey[t];if(h)try{let y=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(h,r,a,d,s,i);y&&(i=y.value,l=y.payload)}catch(y){if(y instanceof KJt||y instanceof v0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(l!==void 0)&&!c&&(l=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),l}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}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,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),l={},p={},_=!0;if(u&&(l=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);l={...l,...h.flags||{}},p={...p,...h.payloads||{}}}return{featureFlags:l,featureFlagPayloads:p}}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)}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=D_n(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(o1_(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,l]of Object.entries(r||{}))s[u]=String(l);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,l]of Object.entries(r||{}))s[u]=String(l);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}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");this.addPendingPromise(SFi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(SFi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),l=r||u?.distinctId,p={...u?.properties||{},...n||{}};l||(l=HJt(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:l,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.event,{}}).then(y=>{let b={};if(y)for(let[O,A]of Object.entries(y))b[`$feature/${O}`]=A;let v=Object.keys(y||{}).filter(O=>y?.[O]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&e1_(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var tT_=require("async_hooks"),T7o=class{constructor(){this.storage=new tT_.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var rT_="posthog-node";function t$M(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[Swc.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let l=o.exception?.values||[],p=l.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:l[0]?.value||o.message,$exception_type:l[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:l[0]?.value||o.message,$sentry_exception_type:l[0]?.type,$sentry_tags:o.tags};return t&&r&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var Swc=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=rT_,this.name=rT_,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(t$M(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};SFi.errorPropertiesBuilder=new h$.ErrorPropertiesBuilder([new h$.EventCoercer,new h$.ErrorCoercer,new h$.ObjectCoercer,new h$.StringCoercer,new h$.PrimitiveCoercer],h$.createStackParser("node:javascript",h$.nodeStackLineParser),[$q_(),L1_]);var bkn=class extends q7o{getLibraryId(){return"posthog-node"}initializeContext(){return new T7o}};var R7o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new bkn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.31.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var KWa=class{async sendEvent(){}async identify(){}async flush(){}};var vkn=require("fs/promises"),oT_=require("os"),uT_=require("path");var iT_=ce(require("crypto")),N7o=new Uint8Array(256),z7o=N7o.length;function Mwc(){return z7o>N7o.length-16&&(iT_.default.randomFillSync(N7o),z7o=0),N7o.slice(z7o,z7o+=16)}var L4=[];for(let e=0;e<256;++e)L4.push((e+256).toString(16).slice(1));function nT_(e,t=0){return L4[e[t+0]]+L4[e[t+1]]+L4[e[t+2]]+L4[e[t+3]]+"-"+L4[e[t+4]]+L4[e[t+5]]+"-"+L4[e[t+6]]+L4[e[t+7]]+"-"+L4[e[t+8]]+L4[e[t+9]]+"-"+L4[e[t+10]]+L4[e[t+11]]+L4[e[t+12]]+L4[e[t+13]]+L4[e[t+14]]+L4[e[t+15]]}var aT_=ce(require("crypto")),Dwc={randomUUID:aT_.default.randomUUID};function r$M(e,t,r){if(Dwc.randomUUID&&!t&&!e)return Dwc.randomUUID();e=e||{};let i=e.random||(e.rng||Mwc)();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 nT_(i)}var ave=r$M;var i$M="id",n$M=".fern",JWa=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new bkn(r),this.userId=t==null?void 0:Agc(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"3.31.0",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await I4({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ct(Cr.of((0,oT_.homedir)()),Ze.of(n$M),Ze.of(i$M));await ji(t)||(await(0,vkn.mkdir)((0,uT_.dirname)(t),{recursive:!0}),await(0,vkn.writeFile)(t,ave())),this.persistedDistinctId=(await(0,vkn.readFile)(t)).toString()}return this.persistedDistinctId}};var Bwc;async function gkn(){return Bwc==null&&(Bwc=await a$M()),Bwc}async function a$M(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new KWa;let r=await nWo();return r!=null?new JWa({token:r,posthogApiKey:e}):await MZn()!=null?new R7o({posthogApiKey:e}):new JWa({token:void 0,posthogApiKey:e})}catch{return new KWa}}function $Wa(e,t){return function(){return e.apply(t,arguments)}}var{toString:o$M}=Object.prototype,{getPrototypeOf:Cwc}=Object,{iterator:Q7o,toStringTag:cT_}=Symbol,U7o=(e=>t=>{let r=o$M.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),c3t=e=>(e=e.toLowerCase(),t=>U7o(t)===e),L7o=e=>t=>typeof t===e,{isArray:Akn}=Array,Okn=L7o("undefined");function YWa(e){return e!==null&&!Okn(e)&&e.constructor!==null&&!Okn(e.constructor)&&y$(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var lT_=c3t("ArrayBuffer");function u$M(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&lT_(e.buffer),t}var s$M=L7o("string"),y$=L7o("function"),fT_=L7o("number"),XWa=e=>e!==null&&typeof e=="object",c$M=e=>e===!0||e===!1,F7o=e=>{if(U7o(e)!=="object")return!1;let t=Cwc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(cT_ in e)&&!(Q7o in e)},l$M=e=>{if(!XWa(e)||YWa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},f$M=c3t("Date"),d$M=c3t("File"),p$M=c3t("Blob"),_$M=c3t("FileList"),h$M=e=>XWa(e)&&y$(e.pipe),y$M=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||y$(e.append)&&((t=U7o(e))==="formdata"||t==="object"&&y$(e.toString)&&e.toString()==="[object FormData]"))},b$M=c3t("URLSearchParams"),[v$M,g$M,O$M,A$M]=["ReadableStream","Request","Response","Headers"].map(c3t),m$M=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function ZWa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),Akn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(YWa(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 dT_(e,t){if(YWa(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 B_n=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,pT_=e=>!Okn(e)&&e!==B_n;function Iwc(){let{caseless:e,skipUndefined:t}=pT_(this)&&this||{},r={},i=(n,a)=>{let o=e&&dT_(r,a)||a;F7o(r[o])&&F7o(n)?r[o]=Iwc(r[o],n):F7o(n)?r[o]=Iwc({},n):Akn(n)?r[o]=n.slice():(!t||!Okn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&ZWa(arguments[n],i);return r}var P$M=(e,t,r,{allOwnKeys:i}={})=>(ZWa(t,(n,a)=>{r&&y$(n)?e[a]=$Wa(n,r):e[a]=n},{allOwnKeys:i}),e),j$M=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),w$M=(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)},E$M=(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&&Cwc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},S$M=(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},M$M=e=>{if(!e)return null;if(Akn(e))return e;let t=e.length;if(!fT_(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},D$M=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Cwc(Uint8Array)),B$M=(e,t)=>{let i=(e&&e[Q7o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},I$M=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},C$M=c3t("HTMLFormElement"),q$M=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),sT_=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),T$M=c3t("RegExp"),_T_=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};ZWa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},R$M=e=>{_T_(e,(t,r)=>{if(y$(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(y$(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+"'")})}})},z$M=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return Akn(e)?i(e):i(String(e).split(t)),r},N$M=()=>{},F$M=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function Q$M(e){return!!(e&&y$(e.append)&&e[cT_]==="FormData"&&e[Q7o])}var U$M=e=>{let t=new Array(10),r=(i,n)=>{if(XWa(i)){if(t.indexOf(i)>=0)return;if(YWa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=Akn(i)?[]:{};return ZWa(i,(o,c)=>{let d=r(o,n+1);!Okn(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},L$M=c3t("AsyncFunction"),V$M=e=>e&&(XWa(e)||y$(e))&&y$(e.then)&&y$(e.catch),hT_=((e,t)=>e?setImmediate:t?((r,i)=>(B_n.addEventListener("message",({source:n,data:a})=>{n===B_n&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),B_n.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",y$(B_n.postMessage)),W$M=typeof queueMicrotask<"u"?queueMicrotask.bind(B_n):typeof process<"u"&&process.nextTick||hT_,G$M=e=>e!=null&&y$(e[Q7o]),rr={isArray:Akn,isArrayBuffer:lT_,isBuffer:YWa,isFormData:y$M,isArrayBufferView:u$M,isString:s$M,isNumber:fT_,isBoolean:c$M,isObject:XWa,isPlainObject:F7o,isEmptyObject:l$M,isReadableStream:v$M,isRequest:g$M,isResponse:O$M,isHeaders:A$M,isUndefined:Okn,isDate:f$M,isFile:d$M,isBlob:p$M,isRegExp:T$M,isFunction:y$,isStream:h$M,isURLSearchParams:b$M,isTypedArray:D$M,isFileList:_$M,forEach:ZWa,merge:Iwc,extend:P$M,trim:m$M,stripBOM:j$M,inherits:w$M,toFlatObject:E$M,kindOf:U7o,kindOfTest:c3t,endsWith:S$M,toArray:M$M,forEachEntry:B$M,matchAll:I$M,isHTMLForm:C$M,hasOwnProperty:sT_,hasOwnProp:sT_,reduceDescriptors:_T_,freezeMethods:R$M,toObjectSet:z$M,toCamelCase:q$M,noop:N$M,toFiniteNumber:F$M,findKey:dT_,global:B_n,isContextDefined:pT_,isSpecCompliantForm:Q$M,toJSONObject:U$M,isAsyncFn:L$M,isThenable:V$M,setImmediate:hT_,asap:W$M,isIterable:G$M};function mkn(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)}rr.inherits(mkn,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:rr.toJSONObject(this.config),code:this.code,status:this.status}}});var yT_=mkn.prototype,bT_={};["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=>{bT_[e]={value:e}});Object.defineProperties(mkn,bT_);Object.defineProperty(yT_,"isAxiosError",{value:!0});mkn.from=(e,t,r,i,n,a)=>{let o=Object.create(yT_);rr.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",d=t==null&&e?e.code:t;return mkn.call(o,c,d,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 Ba=mkn;var vT_=ce(WXn(),1),V7o=vT_.default;function qwc(e){return rr.isPlainObject(e)||rr.isArray(e)}function OT_(e){return rr.endsWith(e,"[]")?e.slice(0,-2):e}function gT_(e,t,r){return e?e.concat(t).map(function(n,a){return n=OT_(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function H$M(e){return rr.isArray(e)&&!e.some(qwc)}var x$M=rr.toFlatObject(rr,{},null,function(t){return/^is[A-Z]/.test(t)});function K$M(e,t,r){if(!rr.isObject(e))throw new TypeError("target must be an object");t=t||new(V7o||FormData),r=rr.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!rr.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&rr.isSpecCompliantForm(t);if(!rr.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(rr.isDate(h))return h.toISOString();if(rr.isBoolean(h))return h.toString();if(!d&&rr.isBlob(h))throw new Ba("Blob is not supported. Use a Buffer instead.");return rr.isArrayBuffer(h)||rr.isTypedArray(h)?d&&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(rr.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(rr.isArray(h)&&H$M(h)||(rr.isFileList(h)||rr.endsWith(y,"[]"))&&(v=rr.toArray(h)))return y=OT_(y),v.forEach(function(A,g){!(rr.isUndefined(A)||A===null)&&t.append(o===!0?gT_([y],g,a):o===null?y:y+"[]",s(A))}),!1}return qwc(h)?!0:(t.append(gT_(b,y,a),s(h)),!1)}let l=[],p=Object.assign(x$M,{defaultVisitor:u,convertValue:s,isVisitable:qwc});function _(h,y){if(!rr.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),rr.forEach(h,function(v,O){(!(rr.isUndefined(v)||v===null)&&n.call(t,v,rr.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),l.pop()}}if(!rr.isObject(e))throw new TypeError("data must be an object");return _(e),t}var V7i=K$M;function AT_(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function mT_(e,t){this._pairs=[],e&&V7i(e,this,t)}var PT_=mT_.prototype;PT_.append=function(t,r){this._pairs.push([t,r])};PT_.toString=function(t){let r=t?function(i){return t.call(this,i,AT_)}:AT_;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var jT_=mT_;function J$M(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function I_n(e,t,r){if(!t)return e;let i=r&&r.encode||J$M;rr.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=rr.isURLSearchParams(t)?t.toString():new jT_(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Twc=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){rr.forEach(this.handlers,function(i){i!==null&&t(i)})}},Rwc=Twc;var Pkn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var MT_=ce(require("crypto"),1);var wT_=ce(require("url"),1),ET_=wT_.default.URLSearchParams;var zwc="abcdefghijklmnopqrstuvwxyz",ST_="0123456789",DT_={DIGIT:ST_,ALPHA:zwc,ALPHA_DIGIT:zwc+zwc.toUpperCase()+ST_},$$M=(e=16,t=DT_.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);MT_.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},BT_={isNode:!0,classes:{URLSearchParams:ET_,FormData:V7o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:DT_,generateString:$$M,protocols:["http","https","file","data"]};var Qwc={};Zt(Qwc,{hasBrowserEnv:()=>Fwc,hasStandardBrowserEnv:()=>Y$M,hasStandardBrowserWebWorkerEnv:()=>X$M,navigator:()=>Nwc,origin:()=>Z$M});var Fwc=typeof window<"u"&&typeof document<"u",Nwc=typeof navigator=="object"&&navigator||void 0,Y$M=Fwc&&(!Nwc||["ReactNative","NativeScript","NS"].indexOf(Nwc.product)<0),X$M=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Z$M=Fwc&&window.location.href||"http://localhost";var om={...Qwc,...BT_};function Uwc(e,t){return V7i(e,new om.classes.URLSearchParams,{visitor:function(r,i,n,a){return om.isNode&&rr.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function k$M(e){return rr.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function eYM(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 tYM(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),d=a>=r.length;return o=!o&&rr.isArray(n)?n.length:o,d?(rr.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!rr.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&rr.isArray(n[o])&&(n[o]=eYM(n[o])),!c)}if(rr.isFormData(e)&&rr.isFunction(e.entries)){let r={};return rr.forEachEntry(e,(i,n)=>{t(k$M(i),n,r,0)}),r}return null}var W7o=tYM;function rYM(e,t,r){if(rr.isString(e))try{return(t||JSON.parse)(e),rr.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var Lwc={transitional:Pkn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=rr.isObject(t);if(a&&rr.isHTMLForm(t)&&(t=new FormData(t)),rr.isFormData(t))return n?JSON.stringify(W7o(t)):t;if(rr.isArrayBuffer(t)||rr.isBuffer(t)||rr.isStream(t)||rr.isFile(t)||rr.isBlob(t)||rr.isReadableStream(t))return t;if(rr.isArrayBufferView(t))return t.buffer;if(rr.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 Uwc(t,this.formSerializer).toString();if((c=rr.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return V7i(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),rYM(t)):t}],transformResponse:[function(t){let r=this.transitional||Lwc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(rr.isResponse(t)||rr.isReadableStream(t))return t;if(t&&rr.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"?Ba.from(c,Ba.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:om.classes.FormData,Blob:om.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};rr.forEach(["delete","get","head","post","put","patch"],e=>{Lwc.headers[e]={}});var jkn=Lwc;var iYM=rr.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"]),IT_=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1148
|
+
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=C1_.test(c)?c.replace(C1_,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=q1_)break}}return T1_(n)}}var bwc=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=LWa(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return M_n(t,"DOMException")}isDOMError(t){return M_n(t,"DOMError")}};var vwc=class{match(t){return uwc(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var gwc=class{constructor(){}match(t){return a1_(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var TJM=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Owc=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(TJM);return n&&(r=n[1],i=n[2]),[r,i]}};var R1_=["fatal","error","warning","log","info","debug"];function D7o(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var Awc=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{type:this.getType(t),value:this.getValue(t),stack:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return b7o(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=D7o(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return LWa(t)&&!i1_(t)&&R1_.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(g1_(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var mwc=class{match(t){return b7o(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${D7o(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Pwc=class{match(t){return VWa(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var jwc=class{match(t){return M_n(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return VWa(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(VWa(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var wwc=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)}}};var F1_=require("fs"),Q1_=require("readline"),B7o=new h$.ReduceableCache(25),U1_=new h$.ReduceableCache(20),Ewc=7,RJM=1e3,zJM=1e4;async function L1_(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"||UJM(o)||LJM(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(U1_.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=WJM(a);if(o.every(d=>VJM(n,d)))continue;let c=GJM(B7o,n,{});i.push(NJM(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&FJM(e,B7o),B7o.reduce(),e}function NJM(e,t,r){return new Promise(i=>{let n=(0,F1_.createReadStream)(e),a=(0,Q1_.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],l=s[1];function p(){U1_.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]=HJM(_,0),c>=l)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],l=h[1]}})})}function FJM(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;QJM(r.lineno,r,i)}}function QJM(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=V1_(e);n<e;n++){let a=r[n];if(a===void 0)return void z1_(t);t.pre_context.push(a)}if(r[e]===void 0)return void z1_(t);t.context_line=r[e];let i=W1_(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 z1_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function UJM(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function LJM(e){return e.lineno!==void 0&&e.lineno>zJM||e.colno!==void 0&&e.colno>RJM}function VJM(e,t){let r=B7o.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 WJM(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=N1_(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+Ewc:(n.push(i),i=N1_(a)),t++}return n}function N1_(e){return[V1_(e),W1_(e)]}function V1_(e){return Math.max(1,e-Ewc)}function W1_(e){return e+Ewc}function GJM(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function HJM(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}function xJM(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(i))},{_posthogErrorHandler:!0})}function G1_(e,t){globalThis.process?.on("uncaughtException",xJM(e,t))}function H1_(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var KJM=2e3,SFi=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new v7o({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||HJt(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(G1_(this.onException.bind(this),this.onFatalError.bind(this)),H1_(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)})())}async onFatalError(t){console.error(t),await this.client.shutdown(KJM),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var x1_="5.17.4";async function K1_(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}var JJM=6e4,$JM=1152921504606847e3,YJM=["is_not"],ykn=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},v0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},KJt=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},I7o=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||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,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;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof KJt||d instanceof v0?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(l=>this.featureFlagsByKey[l]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async l=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(l,t,r,i,n,void 0,u);o[l.key]=p,_&&(c[l.key]=_)}catch(p){p instanceof KJt||p instanceof v0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${l.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${l.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new v0("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new v0("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new v0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new v0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new v0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new v0(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let l=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=l}catch(l){throw new v0(`Error evaluating flag dependency '${d}' for flag '${a}': ${l}`)}else n[d]=!1;else throw new v0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new v0(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,l=a.multivariate?.variants||[];d=u&&l.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof KJt)throw u;if(u instanceof v0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new v0("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?Z1_(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):X1_(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await J1_(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await J1_(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}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(JJM,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0;return;case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new ykn(`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 ykn(`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 ykn(`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 i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length);break}default:return}}catch(t){t instanceof ykn&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=D_n(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function J1_(e,t,r=""){let i=await K1_(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/$JM}function X1_(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 v0("Operator is_not_set is not supported")}else throw new v0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!YJM.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 d(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 $1_(String(n))&&String(o).match(String(n))!==null;case"not_regex":return $1_(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?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new v0("Date operations cannot be performed on boolean values");let s=ZJM(String(n));if(s==null&&(s=Y1_(n)),s==null)throw new v0(`Invalid date: ${n}`);let u=Y1_(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new v0(`Unknown operator: ${a}`)}}function XJM(e,t){if(!(e in t))throw new KJt(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function Z1_(e,t,r,i=!1){let n=String(e.value);XJM(n,r);let a=r[n];return k1_(a,t,r,i)}function k1_(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 d=k1_(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof KJt)throw d;if(d instanceof v0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new v0("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=Z1_(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=X1_(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof KJt)throw d;if(d instanceof v0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new v0("can't match cohort without a given cohort property value");return n==="AND"}function $1_(e){try{return new RegExp(e),!0}catch{return!1}}function Y1_(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 v0(`${e} is in an invalid date format`)}throw new v0(`The date provided ${e} must be a string, number, or date object`)}function ZJM(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{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()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var C7o=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var kJM=100,eT_=3e4,e$M=5e4,q7o=class extends xWa{constructor(t,r={}){if(super(t,r),this._memoryStorage=new C7o,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,kJM):eT_,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.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new I7o({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider}))}this.errorTracking=new SFi(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||e$M}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):fetch(t,r)}getLibraryVersion(){return x1_}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._logger.warn("Called capture() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{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=eT_){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:d,groupProperties:s}=i||{},u=this.addLocalPersonAndGroupProperties(r,n,d,s);d=u.allPersonProperties,s=u.allGroupProperties,o==null&&(o=!1),c==null&&(c=this.options.sendFeatureFlagEvent??!0);let l=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),p=l!==void 0,_,h,y;if(!p&&!o){let v=await super.getFeatureFlagDetailStateless(t,r,n,d,s,a);if(v===void 0)return;y=v.response,l=S_n(y),_=v?.requestId,h=v?.evaluatedAt}let b=`${t}_${l}`;return c&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(b))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(b):this.distinctIdHasSentFlagCalls[r]=[b],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:l,$feature_flag_id:y?.metadata?.id,$feature_flag_version:y?.metadata?.version,$feature_flag_reason:y?.reason?.description??y?.reason?.code,locally_evaluated:p,[`$feature/${t}`]:l,$feature_flag_request_id:_,$feature_flag_evaluated_at:h},groups:n,disableGeoip:a})),l}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:o}=n||{},{onlyEvaluateLocally:c,personProperties:d,groupProperties:s}=n||{},u=this.addLocalPersonAndGroupProperties(r,a,d,s);d=u.allPersonProperties,s=u.allGroupProperties;let l;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let h=this.featureFlagsPoller?.featureFlagsByKey[t];if(h)try{let y=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(h,r,a,d,s,i);y&&(i=y.value,l=y.payload)}catch(y){if(y instanceof KJt||y instanceof v0)this._logger?.info(`${y.name} when computing flag locally: ${h.key}: ${y.message}`);else throw y}}return c==null&&(c=!1),!(l!==void 0)&&!c&&(l=await super.getFeatureFlagPayloadStateless(t,r,a,d,s,o)),l}async getRemoteConfigPayload(t){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}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,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),l={},p={},_=!0;if(u&&(l=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);l={...l,...h.flags||{}},p={...p,...h.payloads||{}}}return{featureFlags:l,featureFlagPayloads:p}}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)}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=D_n(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(o1_(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,l]of Object.entries(r||{}))s[u]=String(l);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,l]of Object.entries(r||{}))s[u]=String(l);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}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");this.addPendingPromise(SFi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.capture(a)))}async captureExceptionImmediate(t,r,i){let n=new Error("PostHog syntheticException");this.addPendingPromise(SFi.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),l=r||u?.distinctId,p={...u?.properties||{},...n||{}};l||(l=HJt(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:l,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.event,{}}).then(y=>{let b={};if(y)for(let[O,A]of Object.entries(y))b[`$feature/${O}`]=A;let v=Object.keys(y||{}).filter(O=>y?.[O]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&e1_(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var tT_=require("async_hooks"),T7o=class{constructor(){this.storage=new tT_.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var rT_="posthog-node";function t$M(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[Swc.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let l=o.exception?.values||[],p=l.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:l[0]?.value||o.message,$exception_type:l[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:l[0]?.value||o.message,$sentry_exception_type:l[0]?.type,$sentry_tags:o.tags};return t&&r&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var Swc=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=rT_,this.name=rT_,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(t$M(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};SFi.errorPropertiesBuilder=new h$.ErrorPropertiesBuilder([new h$.EventCoercer,new h$.ErrorCoercer,new h$.ObjectCoercer,new h$.StringCoercer,new h$.PrimitiveCoercer],h$.createStackParser("node:javascript",h$.nodeStackLineParser),[$q_(),L1_]);var bkn=class extends q7o{getLibraryId(){return"posthog-node"}initializeContext(){return new T7o}};var R7o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new bkn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.31.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var KWa=class{async sendEvent(){}async identify(){}async flush(){}};var vkn=require("fs/promises"),oT_=require("os"),uT_=require("path");var iT_=ce(require("crypto")),N7o=new Uint8Array(256),z7o=N7o.length;function Mwc(){return z7o>N7o.length-16&&(iT_.default.randomFillSync(N7o),z7o=0),N7o.slice(z7o,z7o+=16)}var L4=[];for(let e=0;e<256;++e)L4.push((e+256).toString(16).slice(1));function nT_(e,t=0){return L4[e[t+0]]+L4[e[t+1]]+L4[e[t+2]]+L4[e[t+3]]+"-"+L4[e[t+4]]+L4[e[t+5]]+"-"+L4[e[t+6]]+L4[e[t+7]]+"-"+L4[e[t+8]]+L4[e[t+9]]+"-"+L4[e[t+10]]+L4[e[t+11]]+L4[e[t+12]]+L4[e[t+13]]+L4[e[t+14]]+L4[e[t+15]]}var aT_=ce(require("crypto")),Dwc={randomUUID:aT_.default.randomUUID};function r$M(e,t,r){if(Dwc.randomUUID&&!t&&!e)return Dwc.randomUUID();e=e||{};let i=e.random||(e.rng||Mwc)();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 nT_(i)}var ave=r$M;var i$M="id",n$M=".fern",JWa=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new bkn(r),this.userId=t==null?void 0:Agc(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"3.31.1",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await I4({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Ct(Cr.of((0,oT_.homedir)()),Ze.of(n$M),Ze.of(i$M));await ji(t)||(await(0,vkn.mkdir)((0,uT_.dirname)(t),{recursive:!0}),await(0,vkn.writeFile)(t,ave())),this.persistedDistinctId=(await(0,vkn.readFile)(t)).toString()}return this.persistedDistinctId}};var Bwc;async function gkn(){return Bwc==null&&(Bwc=await a$M()),Bwc}async function a$M(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new KWa;let r=await nWo();return r!=null?new JWa({token:r,posthogApiKey:e}):await MZn()!=null?new R7o({posthogApiKey:e}):new JWa({token:void 0,posthogApiKey:e})}catch{return new KWa}}function $Wa(e,t){return function(){return e.apply(t,arguments)}}var{toString:o$M}=Object.prototype,{getPrototypeOf:Cwc}=Object,{iterator:Q7o,toStringTag:cT_}=Symbol,U7o=(e=>t=>{let r=o$M.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),c3t=e=>(e=e.toLowerCase(),t=>U7o(t)===e),L7o=e=>t=>typeof t===e,{isArray:Akn}=Array,Okn=L7o("undefined");function YWa(e){return e!==null&&!Okn(e)&&e.constructor!==null&&!Okn(e.constructor)&&y$(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var lT_=c3t("ArrayBuffer");function u$M(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&lT_(e.buffer),t}var s$M=L7o("string"),y$=L7o("function"),fT_=L7o("number"),XWa=e=>e!==null&&typeof e=="object",c$M=e=>e===!0||e===!1,F7o=e=>{if(U7o(e)!=="object")return!1;let t=Cwc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(cT_ in e)&&!(Q7o in e)},l$M=e=>{if(!XWa(e)||YWa(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},f$M=c3t("Date"),d$M=c3t("File"),p$M=c3t("Blob"),_$M=c3t("FileList"),h$M=e=>XWa(e)&&y$(e.pipe),y$M=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||y$(e.append)&&((t=U7o(e))==="formdata"||t==="object"&&y$(e.toString)&&e.toString()==="[object FormData]"))},b$M=c3t("URLSearchParams"),[v$M,g$M,O$M,A$M]=["ReadableStream","Request","Response","Headers"].map(c3t),m$M=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function ZWa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),Akn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(YWa(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 dT_(e,t){if(YWa(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 B_n=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,pT_=e=>!Okn(e)&&e!==B_n;function Iwc(){let{caseless:e,skipUndefined:t}=pT_(this)&&this||{},r={},i=(n,a)=>{let o=e&&dT_(r,a)||a;F7o(r[o])&&F7o(n)?r[o]=Iwc(r[o],n):F7o(n)?r[o]=Iwc({},n):Akn(n)?r[o]=n.slice():(!t||!Okn(n))&&(r[o]=n)};for(let n=0,a=arguments.length;n<a;n++)arguments[n]&&ZWa(arguments[n],i);return r}var P$M=(e,t,r,{allOwnKeys:i}={})=>(ZWa(t,(n,a)=>{r&&y$(n)?e[a]=$Wa(n,r):e[a]=n},{allOwnKeys:i}),e),j$M=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),w$M=(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)},E$M=(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&&Cwc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},S$M=(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},M$M=e=>{if(!e)return null;if(Akn(e))return e;let t=e.length;if(!fT_(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},D$M=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Cwc(Uint8Array)),B$M=(e,t)=>{let i=(e&&e[Q7o]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},I$M=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},C$M=c3t("HTMLFormElement"),q$M=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),sT_=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),T$M=c3t("RegExp"),_T_=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};ZWa(r,(n,a)=>{let o;(o=t(n,a,e))!==!1&&(i[a]=o||n)}),Object.defineProperties(e,i)},R$M=e=>{_T_(e,(t,r)=>{if(y$(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(y$(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+"'")})}})},z$M=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return Akn(e)?i(e):i(String(e).split(t)),r},N$M=()=>{},F$M=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function Q$M(e){return!!(e&&y$(e.append)&&e[cT_]==="FormData"&&e[Q7o])}var U$M=e=>{let t=new Array(10),r=(i,n)=>{if(XWa(i)){if(t.indexOf(i)>=0)return;if(YWa(i))return i;if(!("toJSON"in i)){t[n]=i;let a=Akn(i)?[]:{};return ZWa(i,(o,c)=>{let d=r(o,n+1);!Okn(d)&&(a[c]=d)}),t[n]=void 0,a}}return i};return r(e,0)},L$M=c3t("AsyncFunction"),V$M=e=>e&&(XWa(e)||y$(e))&&y$(e.then)&&y$(e.catch),hT_=((e,t)=>e?setImmediate:t?((r,i)=>(B_n.addEventListener("message",({source:n,data:a})=>{n===B_n&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),B_n.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",y$(B_n.postMessage)),W$M=typeof queueMicrotask<"u"?queueMicrotask.bind(B_n):typeof process<"u"&&process.nextTick||hT_,G$M=e=>e!=null&&y$(e[Q7o]),rr={isArray:Akn,isArrayBuffer:lT_,isBuffer:YWa,isFormData:y$M,isArrayBufferView:u$M,isString:s$M,isNumber:fT_,isBoolean:c$M,isObject:XWa,isPlainObject:F7o,isEmptyObject:l$M,isReadableStream:v$M,isRequest:g$M,isResponse:O$M,isHeaders:A$M,isUndefined:Okn,isDate:f$M,isFile:d$M,isBlob:p$M,isRegExp:T$M,isFunction:y$,isStream:h$M,isURLSearchParams:b$M,isTypedArray:D$M,isFileList:_$M,forEach:ZWa,merge:Iwc,extend:P$M,trim:m$M,stripBOM:j$M,inherits:w$M,toFlatObject:E$M,kindOf:U7o,kindOfTest:c3t,endsWith:S$M,toArray:M$M,forEachEntry:B$M,matchAll:I$M,isHTMLForm:C$M,hasOwnProperty:sT_,hasOwnProp:sT_,reduceDescriptors:_T_,freezeMethods:R$M,toObjectSet:z$M,toCamelCase:q$M,noop:N$M,toFiniteNumber:F$M,findKey:dT_,global:B_n,isContextDefined:pT_,isSpecCompliantForm:Q$M,toJSONObject:U$M,isAsyncFn:L$M,isThenable:V$M,setImmediate:hT_,asap:W$M,isIterable:G$M};function mkn(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)}rr.inherits(mkn,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:rr.toJSONObject(this.config),code:this.code,status:this.status}}});var yT_=mkn.prototype,bT_={};["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=>{bT_[e]={value:e}});Object.defineProperties(mkn,bT_);Object.defineProperty(yT_,"isAxiosError",{value:!0});mkn.from=(e,t,r,i,n,a)=>{let o=Object.create(yT_);rr.toFlatObject(e,o,function(u){return u!==Error.prototype},s=>s!=="isAxiosError");let c=e&&e.message?e.message:"Error",d=t==null&&e?e.code:t;return mkn.call(o,c,d,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 Ba=mkn;var vT_=ce(WXn(),1),V7o=vT_.default;function qwc(e){return rr.isPlainObject(e)||rr.isArray(e)}function OT_(e){return rr.endsWith(e,"[]")?e.slice(0,-2):e}function gT_(e,t,r){return e?e.concat(t).map(function(n,a){return n=OT_(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function H$M(e){return rr.isArray(e)&&!e.some(qwc)}var x$M=rr.toFlatObject(rr,{},null,function(t){return/^is[A-Z]/.test(t)});function K$M(e,t,r){if(!rr.isObject(e))throw new TypeError("target must be an object");t=t||new(V7o||FormData),r=rr.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!rr.isUndefined(b[y])});let i=r.metaTokens,n=r.visitor||u,a=r.dots,o=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&rr.isSpecCompliantForm(t);if(!rr.isFunction(n))throw new TypeError("visitor must be a function");function s(h){if(h===null)return"";if(rr.isDate(h))return h.toISOString();if(rr.isBoolean(h))return h.toString();if(!d&&rr.isBlob(h))throw new Ba("Blob is not supported. Use a Buffer instead.");return rr.isArrayBuffer(h)||rr.isTypedArray(h)?d&&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(rr.endsWith(y,"{}"))y=i?y:y.slice(0,-2),h=JSON.stringify(h);else if(rr.isArray(h)&&H$M(h)||(rr.isFileList(h)||rr.endsWith(y,"[]"))&&(v=rr.toArray(h)))return y=OT_(y),v.forEach(function(A,g){!(rr.isUndefined(A)||A===null)&&t.append(o===!0?gT_([y],g,a):o===null?y:y+"[]",s(A))}),!1}return qwc(h)?!0:(t.append(gT_(b,y,a),s(h)),!1)}let l=[],p=Object.assign(x$M,{defaultVisitor:u,convertValue:s,isVisitable:qwc});function _(h,y){if(!rr.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+y.join("."));l.push(h),rr.forEach(h,function(v,O){(!(rr.isUndefined(v)||v===null)&&n.call(t,v,rr.isString(O)?O.trim():O,y,p))===!0&&_(v,y?y.concat(O):[O])}),l.pop()}}if(!rr.isObject(e))throw new TypeError("data must be an object");return _(e),t}var V7i=K$M;function AT_(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function mT_(e,t){this._pairs=[],e&&V7i(e,this,t)}var PT_=mT_.prototype;PT_.append=function(t,r){this._pairs.push([t,r])};PT_.toString=function(t){let r=t?function(i){return t.call(this,i,AT_)}:AT_;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var jT_=mT_;function J$M(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function I_n(e,t,r){if(!t)return e;let i=r&&r.encode||J$M;rr.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=rr.isURLSearchParams(t)?t.toString():new jT_(t,r).toString(i),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Twc=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){rr.forEach(this.handlers,function(i){i!==null&&t(i)})}},Rwc=Twc;var Pkn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var MT_=ce(require("crypto"),1);var wT_=ce(require("url"),1),ET_=wT_.default.URLSearchParams;var zwc="abcdefghijklmnopqrstuvwxyz",ST_="0123456789",DT_={DIGIT:ST_,ALPHA:zwc,ALPHA_DIGIT:zwc+zwc.toUpperCase()+ST_},$$M=(e=16,t=DT_.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);MT_.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},BT_={isNode:!0,classes:{URLSearchParams:ET_,FormData:V7o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:DT_,generateString:$$M,protocols:["http","https","file","data"]};var Qwc={};Zt(Qwc,{hasBrowserEnv:()=>Fwc,hasStandardBrowserEnv:()=>Y$M,hasStandardBrowserWebWorkerEnv:()=>X$M,navigator:()=>Nwc,origin:()=>Z$M});var Fwc=typeof window<"u"&&typeof document<"u",Nwc=typeof navigator=="object"&&navigator||void 0,Y$M=Fwc&&(!Nwc||["ReactNative","NativeScript","NS"].indexOf(Nwc.product)<0),X$M=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Z$M=Fwc&&window.location.href||"http://localhost";var om={...Qwc,...BT_};function Uwc(e,t){return V7i(e,new om.classes.URLSearchParams,{visitor:function(r,i,n,a){return om.isNode&&rr.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...t})}function k$M(e){return rr.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function eYM(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 tYM(e){function t(r,i,n,a){let o=r[a++];if(o==="__proto__")return!0;let c=Number.isFinite(+o),d=a>=r.length;return o=!o&&rr.isArray(n)?n.length:o,d?(rr.hasOwnProp(n,o)?n[o]=[n[o],i]:n[o]=i,!c):((!n[o]||!rr.isObject(n[o]))&&(n[o]=[]),t(r,i,n[o],a)&&rr.isArray(n[o])&&(n[o]=eYM(n[o])),!c)}if(rr.isFormData(e)&&rr.isFunction(e.entries)){let r={};return rr.forEachEntry(e,(i,n)=>{t(k$M(i),n,r,0)}),r}return null}var W7o=tYM;function rYM(e,t,r){if(rr.isString(e))try{return(t||JSON.parse)(e),rr.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var Lwc={transitional:Pkn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=rr.isObject(t);if(a&&rr.isHTMLForm(t)&&(t=new FormData(t)),rr.isFormData(t))return n?JSON.stringify(W7o(t)):t;if(rr.isArrayBuffer(t)||rr.isBuffer(t)||rr.isStream(t)||rr.isFile(t)||rr.isBlob(t)||rr.isReadableStream(t))return t;if(rr.isArrayBufferView(t))return t.buffer;if(rr.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 Uwc(t,this.formSerializer).toString();if((c=rr.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return V7i(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),rYM(t)):t}],transformResponse:[function(t){let r=this.transitional||Lwc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(rr.isResponse(t)||rr.isReadableStream(t))return t;if(t&&rr.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"?Ba.from(c,Ba.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:om.classes.FormData,Blob:om.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};rr.forEach(["delete","get","head","post","put","patch"],e=>{Lwc.headers[e]={}});var jkn=Lwc;var iYM=rr.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"]),IT_=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1149
1149
|
`).forEach(function(o){n=o.indexOf(":"),r=o.substring(0,n).trim().toLowerCase(),i=o.substring(n+1).trim(),!(!r||t[r]&&iYM[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var CT_=Symbol("internals");function kWa(e){return e&&String(e).trim().toLowerCase()}function G7o(e){return e===!1||e==null?e:rr.isArray(e)?e.map(G7o):String(e)}function nYM(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 aYM=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Vwc(e,t,r,i,n){if(rr.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!rr.isString(t)){if(rr.isString(i))return t.indexOf(i)!==-1;if(rr.isRegExp(i))return i.test(t)}}function oYM(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function uYM(e,t){let r=rr.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 wkn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(c,d,s){let u=kWa(d);if(!u)throw new Error("header name must be a non-empty string");let l=rr.findKey(n,u);(!l||n[l]===void 0||s===!0||s===void 0&&n[l]!==!1)&&(n[l||d]=G7o(c))}let o=(c,d)=>rr.forEach(c,(s,u)=>a(s,u,d));if(rr.isPlainObject(t)||t instanceof this.constructor)o(t,r);else if(rr.isString(t)&&(t=t.trim())&&!aYM(t))o(IT_(t),r);else if(rr.isObject(t)&&rr.isIterable(t)){let c={},d,s;for(let u of t){if(!rr.isArray(u))throw TypeError("Object iterator must return a key-value pair");c[s=u[0]]=(d=c[s])?rr.isArray(d)?[...d,u[1]]:[d,u[1]]:u[1]}o(c,r)}else t!=null&&a(r,t,i);return this}get(t,r){if(t=kWa(t),t){let i=rr.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return nYM(n);if(rr.isFunction(r))return r.call(this,n,i);if(rr.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=kWa(t),t){let i=rr.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||Vwc(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(o){if(o=kWa(o),o){let c=rr.findKey(i,o);c&&(!r||Vwc(i,i[c],c,r))&&(delete i[c],n=!0)}}return rr.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||Vwc(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return rr.forEach(this,(n,a)=>{let o=rr.findKey(i,a);if(o){r[o]=G7o(n),delete r[a];return}let c=t?oYM(a):String(a).trim();c!==a&&delete r[a],r[c]=G7o(n),i[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return rr.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&rr.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(`
|
|
1150
1150
|
`)}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[CT_]=this[CT_]={accessors:{}}).accessors,n=this.prototype;function a(o){let c=kWa(o);i[c]||(uYM(n,o),i[c]=!0)}return rr.isArray(t)?t.forEach(a):a(t),this}};wkn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);rr.reduceDescriptors(wkn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});rr.freezeMethods(wkn);var nD=wkn;function e5a(e,t){let r=this||jkn,i=t||r,n=nD.from(i.headers),a=i.data;return rr.forEach(e,function(c){a=c.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function t5a(e){return!!(e&&e.__CANCEL__)}function qT_(e,t,r){Ba.call(this,e??"canceled",Ba.ERR_CANCELED,t,r),this.name="CanceledError"}rr.inherits(qT_,Ba,{__CANCEL__:!0});var ove=qT_;function JJt(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Ba("Request failed with status code "+r.status,[Ba.ERR_BAD_REQUEST,Ba.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function Wwc(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Gwc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function C_n(e,t,r){let i=!Wwc(t);return e&&(i||r==!1)?Gwc(e,t):t}var iR_=ce(Hwc(),1),nR_=ce(require("http"),1),aR_=ce(require("https"),1),oR_=ce(require("util"),1),uR_=ce(LT_(),1),DFi=ce(require("zlib"),1);var R_n="1.12.2";function o5a(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var jYM=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function nEc(e,t,r){let i=r&&r.Blob||om.classes.Blob,n=o5a(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=jYM.exec(e);if(!a)throw new Ba("Invalid URL",Ba.ERR_INVALID_URL);let o=a[1],c=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),c?"base64":"utf8");if(t){if(!i)throw new Ba("Blob is not supported",Ba.ERR_NOT_SUPPORT);return new i([s],{type:o})}return s}throw new Ba("Unsupported protocol "+n,Ba.ERR_NOT_SUPPORT)}var N_n=ce(require("stream"),1);var VT_=ce(require("stream"),1);var aEc=Symbol("internals"),oEc=class extends VT_.default.Transform{constructor(t){t=rr.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!rr.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[aEc]={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[aEc];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[aEc],a=n.maxRate,o=this.readableHighWaterMark,c=n.timeWindow,d=1e3/c,s=a/d,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)})}},uEc=oEc;var sR_=require("events");var GT_=ce(require("util"),1),HT_=require("stream");var{asyncIterator:WT_}=Symbol,wYM=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[WT_]?yield*e[WT_]():yield e},H7o=wYM;var EYM=om.ALPHABET.ALPHA_DIGIT+"-_",u5a=typeof TextEncoder=="function"?new TextEncoder:new GT_.default.TextEncoder,z_n=`\r
|
|
1151
1151
|
`,SYM=u5a.encode(z_n),MYM=2,sEc=class{constructor(t,r){let{escapeName:i}=this.constructor,n=rr.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${z_n}`;n?r=u5a.encode(String(r).replace(/\r?\n|\r\n?/g,z_n)):a+=`Content-Type: ${r.type||"application/octet-stream"}${z_n}`,this.headers=u5a.encode(a+z_n),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+MYM,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;rr.isTypedArray(t)?yield t:yield*H7o(t),yield SYM}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},DYM=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+om.generateString(n,EYM)}=r||{};if(!rr.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=u5a.encode("--"+a+z_n),c=u5a.encode("--"+a+"--"+z_n),d=c.byteLength,s=Array.from(e.entries()).map(([l,p])=>{let _=new sEc(l,p);return d+=_.size,_});d+=o.byteLength*s.length,d=rr.toFiniteNumber(d);let u={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(u["Content-Length"]=d),t&&t(u),HT_.Readable.from((async function*(){for(let l of s)yield o,yield*l.encode();yield c})())},xT_=DYM;var KT_=ce(require("stream"),1),cEc=class extends KT_.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)}},JT_=cEc;var BYM=(e,t)=>rr.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,$T_=BYM;function IYM(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(d){let s=Date.now(),u=i[a];o||(o=s),r[n]=d,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 YT_=IYM;function CYM(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 XT_=CYM;var MFi=(e,t,r=3)=>{let i=0,n=YT_(50,250);return XT_(a=>{let o=a.loaded,c=a.lengthComputable?a.total:void 0,d=o-i,s=n(d),u=o<=c;i=o;let l={loaded:o,total:c,progress:c?o/c:void 0,bytes:d,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)},Skn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},Mkn=e=>(...t)=>rr.asap(()=>e(...t));function lEc(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,d=o-1,s=p=>p>=2&&i.charCodeAt(p-2)===37&&i.charCodeAt(p-1)===51&&(i.charCodeAt(p)===68||i.charCodeAt(p)===100);d>=0&&(i.charCodeAt(d)===61?(c++,d--):s(d)&&(c++,d-=3)),c===1&&d>=0&&(i.charCodeAt(d)===61||s(d))&&c++;let l=Math.floor(a/4)*3-(c||0);return l>0?l:0}return Buffer.byteLength(i,"utf8")}var ZT_={flush:DFi.default.constants.Z_SYNC_FLUSH,finishFlush:DFi.default.constants.Z_SYNC_FLUSH},qYM={flush:DFi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:DFi.default.constants.BROTLI_OPERATION_FLUSH},kT_=rr.isFunction(DFi.default.createBrotliDecompress),{http:TYM,https:RYM}=uR_.default,zYM=/https:?/,eR_=om.protocols.map(e=>e+":"),tR_=(e,[t,r])=>(e.on("end",r).on("error",r),t);function NYM(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function cR_(e,t,r){let i=t;if(!i&&i!==!1){let n=iR_.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){cR_(a,t,a.href)}}var FYM=typeof process<"u"&&rr.kindOf(process)==="process",QYM=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},o=d=>{a(d),t(d)},c=d=>{a(d,!0),r(d)};e(o,c,d=>i=d).catch(c)}),UYM=({address:e,family:t})=>{if(!rr.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},rR_=(e,t)=>UYM(rr.isObject(e)?e:{address:e,family:t}),lR_=FYM&&function(t){return QYM(async function(i,n,a){let{data:o,lookup:c,family:d}=t,{responseType:s,responseEncoding:u}=t,l=t.method.toUpperCase(),p,_=!1,h;if(c){let ee=$T_(c,Pe=>rr.isArray(Pe)?Pe:[Pe]);c=(Pe,ve,G)=>{ee(Pe,ve,(H,Ee,ue)=>{if(H)return G(H);let Oe=rr.isArray(Ee)?Ee.map(Qe=>rR_(Qe)):[rR_(Ee,ue)];ve.all?G(H,Oe):G(H,Oe[0].address,Oe[0].family)})}}let y=new sR_.EventEmitter,b=()=>{t.cancelToken&&t.cancelToken.unsubscribe(v),t.signal&&t.signal.removeEventListener("abort",v),y.removeAllListeners()};a((ee,Pe)=>{p=!0,Pe&&(_=!0,b())});function v(ee){y.emit("abort",!ee||ee.type?new ove(null,t,h):ee)}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=C_n(t.baseURL,t.url,t.allowAbsoluteUrls),A=new URL(O,om.hasBrowserEnv?om.origin:void 0),g=A.protocol||eR_[0];if(g==="data:"){if(t.maxContentLength>-1){let Pe=String(t.url||O||"");if(lEc(Pe)>t.maxContentLength)return n(new Ba("maxContentLength size of "+t.maxContentLength+" exceeded",Ba.ERR_BAD_RESPONSE,t))}let ee;if(l!=="GET")return JJt(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{ee=nEc(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Pe){throw Ba.from(Pe,Ba.ERR_BAD_REQUEST,t)}return s==="text"?(ee=ee.toString(u),(!u||u==="utf8")&&(ee=rr.stripBOM(ee))):s==="stream"&&(ee=N_n.default.Readable.from(ee)),JJt(i,n,{data:ee,status:200,statusText:"OK",headers:new nD,config:t})}if(eR_.indexOf(g)===-1)return n(new Ba("Unsupported protocol "+g,Ba.ERR_BAD_REQUEST,t));let m=nD.from(t.headers).normalize();m.set("User-Agent","axios/"+R_n,!1);let{onUploadProgress:j,onDownloadProgress:M}=t,w=t.maxRate,D,B;if(rr.isSpecCompliantForm(o)){let ee=m.getContentType(/boundary=([-_\w\d]{10,70})/i);o=xT_(o,Pe=>{m.set(Pe)},{tag:`axios-${R_n}-boundary`,boundary:ee&&ee[1]||void 0})}else if(rr.isFormData(o)&&rr.isFunction(o.getHeaders)){if(m.set(o.getHeaders()),!m.hasContentLength())try{let ee=await oR_.default.promisify(o.getLength).call(o);Number.isFinite(ee)&&ee>=0&&m.setContentLength(ee)}catch{}}else if(rr.isBlob(o)||rr.isFile(o))o.size&&m.setContentType(o.type||"application/octet-stream"),m.setContentLength(o.size||0),o=N_n.default.Readable.from(H7o(o));else if(o&&!rr.isStream(o)){if(!Buffer.isBuffer(o))if(rr.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else if(rr.isString(o))o=Buffer.from(o,"utf-8");else return n(new Ba("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Ba.ERR_BAD_REQUEST,t));if(m.setContentLength(o.length,!1),t.maxBodyLength>-1&&o.length>t.maxBodyLength)return n(new Ba("Request body larger than maxBodyLength limit",Ba.ERR_BAD_REQUEST,t))}let R=rr.toFiniteNumber(m.getContentLength());rr.isArray(w)?(D=w[0],B=w[1]):D=B=w,o&&(j||D)&&(rr.isStream(o)||(o=N_n.default.Readable.from(o,{objectMode:!1})),o=N_n.default.pipeline([o,new uEc({maxRate:rr.toFiniteNumber(D)})],rr.noop),j&&o.on("progress",tR_(o,Skn(R,MFi(Mkn(j),!1,3)))));let N;if(t.auth){let ee=t.auth.username||"",Pe=t.auth.password||"";N=ee+":"+Pe}if(!N&&A.username){let ee=A.username,Pe=A.password;N=ee+":"+Pe}N&&m.delete("authorization");let z;try{z=I_n(A.pathname+A.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(ee){let Pe=new Error(ee.message);return Pe.config=t,Pe.url=t.url,Pe.exists=!0,n(Pe)}m.set("Accept-Encoding","gzip, compress, deflate"+(kT_?", br":""),!1);let F={path:z,method:l,headers:m.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:N,protocol:g,family:d,beforeRedirect:NYM,beforeRedirects:{}};!rr.isUndefined(c)&&(F.lookup=c),t.socketPath?F.socketPath=t.socketPath:(F.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,F.port=A.port,cR_(F,t.proxy,g+"//"+A.hostname+(A.port?":"+A.port:"")+F.path));let U,x=zYM.test(F.protocol);if(F.agent=x?t.httpsAgent:t.httpAgent,t.transport?U=t.transport:t.maxRedirects===0?U=x?aR_.default:nR_.default:(t.maxRedirects&&(F.maxRedirects=t.maxRedirects),t.beforeRedirect&&(F.beforeRedirects.config=t.beforeRedirect),U=x?RYM:TYM),t.maxBodyLength>-1?F.maxBodyLength=t.maxBodyLength:F.maxBodyLength=1/0,t.insecureHTTPParser&&(F.insecureHTTPParser=t.insecureHTTPParser),h=U.request(F,function(Pe){if(h.destroyed)return;let ve=[Pe],G=+Pe.headers["content-length"];if(M||B){let Qe=new uEc({maxRate:rr.toFiniteNumber(B)});M&&Qe.on("progress",tR_(Qe,Skn(G,MFi(Mkn(M),!0,3)))),ve.push(Qe)}let H=Pe,Ee=Pe.req||h;if(t.decompress!==!1&&Pe.headers["content-encoding"])switch((l==="HEAD"||Pe.statusCode===204)&&delete Pe.headers["content-encoding"],(Pe.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":ve.push(DFi.default.createUnzip(ZT_)),delete Pe.headers["content-encoding"];break;case"deflate":ve.push(new JT_),ve.push(DFi.default.createUnzip(ZT_)),delete Pe.headers["content-encoding"];break;case"br":kT_&&(ve.push(DFi.default.createBrotliDecompress(qYM)),delete Pe.headers["content-encoding"])}H=ve.length>1?N_n.default.pipeline(ve,rr.noop):ve[0];let ue=N_n.default.finished(H,()=>{ue(),b()}),Oe={status:Pe.statusCode,statusText:Pe.statusMessage,headers:new nD(Pe.headers),config:t,request:Ee};if(s==="stream")Oe.data=H,JJt(i,n,Oe);else{let Qe=[],se=0;H.on("data",function($e){Qe.push($e),se+=$e.length,t.maxContentLength>-1&&se>t.maxContentLength&&(_=!0,H.destroy(),n(new Ba("maxContentLength size of "+t.maxContentLength+" exceeded",Ba.ERR_BAD_RESPONSE,t,Ee)))}),H.on("aborted",function(){if(_)return;let $e=new Ba("stream has been aborted",Ba.ERR_BAD_RESPONSE,t,Ee);H.destroy($e),n($e)}),H.on("error",function($e){h.destroyed||n(Ba.from($e,null,t,Ee))}),H.on("end",function(){try{let $e=Qe.length===1?Qe[0]:Buffer.concat(Qe);s!=="arraybuffer"&&($e=$e.toString(u),(!u||u==="utf8")&&($e=rr.stripBOM($e))),Oe.data=$e}catch($e){return n(Ba.from($e,null,t,Oe.request,Oe))}JJt(i,n,Oe)})}y.once("abort",Qe=>{H.destroyed||(H.emit("error",Qe),H.destroy())})}),y.once("abort",ee=>{n(ee),h.destroy(ee)}),h.on("error",function(Pe){n(Ba.from(Pe,null,t,h))}),h.on("socket",function(Pe){Pe.setKeepAlive(!0,1e3*60)}),t.timeout){let ee=parseInt(t.timeout,10);if(Number.isNaN(ee)){n(new Ba("error trying to parse `config.timeout` to int",Ba.ERR_BAD_OPTION_VALUE,t,h));return}h.setTimeout(ee,function(){if(p)return;let ve=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",G=t.transitional||Pkn;t.timeoutErrorMessage&&(ve=t.timeoutErrorMessage),n(new Ba(ve,G.clarifyTimeoutError?Ba.ETIMEDOUT:Ba.ECONNABORTED,t,h)),v()})}if(rr.isStream(o)){let ee=!1,Pe=!1;o.on("end",()=>{ee=!0}),o.once("error",ve=>{Pe=!0,h.destroy(ve)}),o.on("close",()=>{!ee&&!Pe&&v(new ove("Request stream has been aborted",t,h))}),o.pipe(h)}else h.end(o)})};var fR_=om.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,om.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(om.origin),om.navigator&&/(msie|trident)/i.test(om.navigator.userAgent)):()=>!0;var dR_=om.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let o=[e+"="+encodeURIComponent(t)];rr.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),rr.isString(i)&&o.push("path="+i),rr.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 pR_=e=>e instanceof nD?{...e}:e;function l3t(e,t){t=t||{};let r={};function i(s,u,l,p){return rr.isPlainObject(s)&&rr.isPlainObject(u)?rr.merge.call({caseless:p},s,u):rr.isPlainObject(u)?rr.merge({},u):rr.isArray(u)?u.slice():u}function n(s,u,l,p){if(rr.isUndefined(u)){if(!rr.isUndefined(s))return i(void 0,s,l,p)}else return i(s,u,l,p)}function a(s,u){if(!rr.isUndefined(u))return i(void 0,u)}function o(s,u){if(rr.isUndefined(u)){if(!rr.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 d={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(pR_(s),pR_(u),l,!0)};return rr.forEach(Object.keys({...e,...t}),function(u){let l=d[u]||n,p=l(e[u],t[u],u);rr.isUndefined(p)&&l!==c||(r[u]=p)}),r}var x7o=e=>{let t=l3t({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=nD.from(o),t.url=I_n(C_n(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),rr.isFormData(r)){if(om.hasStandardBrowserEnv||om.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(rr.isFunction(r.getHeaders)){let d=r.getHeaders(),s=["content-type","content-length"];Object.entries(d).forEach(([u,l])=>{s.includes(u.toLowerCase())&&o.set(u,l)})}}if(om.hasStandardBrowserEnv&&(i&&rr.isFunction(i)&&(i=i(t)),i||i!==!1&&fR_(t.url))){let d=n&&a&&dR_.read(a);d&&o.set(n,d)}return t};var LYM=typeof XMLHttpRequest<"u",_R_=LYM&&function(e){return new Promise(function(r,i){let n=x7o(e),a=n.data,o=nD.from(n.headers).normalize(),{responseType:c,onUploadProgress:d,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=nD.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};JJt(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 Ba("Request aborted",Ba.ECONNABORTED,e,b)),b=null)},b.onerror=function(g){let m=g&&g.message?g.message:"Network Error",j=new Ba(m,Ba.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||Pkn;n.timeoutErrorMessage&&(g=n.timeoutErrorMessage),i(new Ba(g,m.clarifyTimeoutError?Ba.ETIMEDOUT:Ba.ECONNABORTED,e,b)),b=null},a===void 0&&o.setContentType(null),"setRequestHeader"in b&&rr.forEach(o.toJSON(),function(g,m){b.setRequestHeader(m,g)}),rr.isUndefined(n.withCredentials)||(b.withCredentials=!!n.withCredentials),c&&c!=="json"&&(b.responseType=n.responseType),s&&([p,h]=MFi(s,!0),b.addEventListener("progress",p)),d&&b.upload&&([l,_]=MFi(d),b.upload.addEventListener("progress",l),b.upload.addEventListener("loadend",_)),(n.cancelToken||n.signal)&&(u=A=>{b&&(i(!A||A.type?new ove(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=o5a(n.url);if(O&&om.protocols.indexOf(O)===-1){i(new Ba("Unsupported protocol "+O+":",Ba.ERR_BAD_REQUEST,e));return}b.send(a||null)})};var VYM=(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 Ba?u:new ove(u instanceof Error?u.message:u))}},o=t&&setTimeout(()=>{o=null,a(new Ba(`timeout ${t} of ms exceeded`,Ba.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:d}=i;return d.unsubscribe=()=>rr.asap(c),d}},hR_=VYM;var WYM=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},GYM=async function*(e,t){for await(let r of HYM(e))yield*WYM(r,t)},HYM=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()}},fEc=(e,t,r,i)=>{let n=GYM(e,t),a=0,o,c=d=>{o||(o=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:u}=await n.next();if(s){c(),d.close();return}let l=u.byteLength;if(r){let p=a+=l;r(p)}d.enqueue(new Uint8Array(u))}catch(s){throw c(s),s}},cancel(d){return c(d),n.return()}},{highWaterMark:2})};var yR_=64*1024,{isFunction:K7o}=rr,xYM=(({Request:e,Response:t})=>({Request:e,Response:t}))(rr.global),{ReadableStream:bR_,TextEncoder:vR_}=rr.global,gR_=(e,...t)=>{try{return!!e(...t)}catch{return!1}},KYM=e=>{e=rr.merge.call({skipUndefined:!0},xYM,e);let{fetch:t,Request:r,Response:i}=e,n=t?K7o(t):typeof fetch=="function",a=K7o(r),o=K7o(i);if(!n)return!1;let c=n&&K7o(bR_),d=n&&(typeof vR_=="function"?(h=>y=>h.encode(y))(new vR_):async h=>new Uint8Array(await new r(h).arrayBuffer())),s=a&&c&&gR_(()=>{let h=!1,y=new r(om.origin,{body:new bR_,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!y}),u=o&&c&&gR_(()=>rr.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 Ba(`Response type '${h}' is not supported`,Ba.ERR_NOT_SUPPORT,b)})});let p=async h=>{if(h==null)return 0;if(rr.isBlob(h))return h.size;if(rr.isSpecCompliantForm(h))return(await new r(om.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(rr.isArrayBufferView(h)||rr.isArrayBuffer(h))return h.byteLength;if(rr.isURLSearchParams(h)&&(h=h+""),rr.isString(h))return(await d(h)).byteLength},_=async(h,y)=>{let b=rr.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:w,withCredentials:D="same-origin",fetchOptions:B}=x7o(h),R=t||fetch;M=M?(M+"").toLowerCase():"text";let N=hR_([O,A&&A.toAbortSignal()],g),z=null,F=N&&N.unsubscribe&&(()=>{N.unsubscribe()}),U;try{if(j&&s&&b!=="get"&&b!=="head"&&(U=await _(w,v))!==0){let H=new r(y,{method:"POST",body:v,duplex:"half"}),Ee;if(rr.isFormData(v)&&(Ee=H.headers.get("content-type"))&&w.setContentType(Ee),H.body){let[ue,Oe]=Skn(U,MFi(Mkn(j)));v=fEc(H.body,yR_,ue,Oe)}}rr.isString(D)||(D=D?"include":"omit");let x=a&&"credentials"in r.prototype,ee={...B,signal:N,method:b.toUpperCase(),headers:w.normalize().toJSON(),body:v,duplex:"half",credentials:x?D:void 0};z=a&&new r(y,ee);let Pe=await(a?R(z,B):R(y,ee)),ve=u&&(M==="stream"||M==="response");if(u&&(m||ve&&F)){let H={};["status","statusText","headers"].forEach(Qe=>{H[Qe]=Pe[Qe]});let Ee=rr.toFiniteNumber(Pe.headers.get("content-length")),[ue,Oe]=m&&Skn(Ee,MFi(Mkn(m),!0))||[];Pe=new i(fEc(Pe.body,yR_,ue,()=>{Oe&&Oe(),F&&F()}),H)}M=M||"text";let G=await l[rr.findKey(l,M)||"text"](Pe,h);return!ve&&F&&F(),await new Promise((H,Ee)=>{JJt(H,Ee,{data:G,headers:nD.from(Pe.headers),status:Pe.status,statusText:Pe.statusText,config:h,request:z})})}catch(x){throw F&&F(),x&&x.name==="TypeError"&&/Load failed|fetch/i.test(x.message)?Object.assign(new Ba("Network Error",Ba.ERR_NETWORK,h,z),{cause:x.cause||x}):Ba.from(x,x&&x.code,h,z)}}},JYM=new Map,dEc=e=>{let t=e?e.env:{},{fetch:r,Request:i,Response:n}=t,a=[i,n,r],o=a.length,c=o,d,s,u=JYM;for(;c--;)d=a[c],s=u.get(d),s===void 0&&u.set(d,s=c?new Map:KYM(t)),u=s;return s},zE9=dEc();var pEc={http:lR_,xhr:_R_,fetch:{get:dEc}};rr.forEach(pEc,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var OR_=e=>`- ${e}`,YYM=e=>rr.isFunction(e)||e===null||e===!1,J7o={getAdapter:(e,t)=>{e=rr.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,!YYM(i)&&(n=pEc[(c=String(i)).toLowerCase()],n===void 0))throw new Ba(`Unknown adapter '${c}'`);if(n&&(rr.isFunction(n)||(n=n.get(t))))break;a[c||"#"+o]=n}if(!n){let o=Object.entries(a).map(([d,s])=>`adapter ${d} `+(s===!1?"is not supported by the environment":"is not available in the build")),c=r?o.length>1?`since :
|
|
@@ -1389,7 +1389,7 @@ ${g}${O}${m}${Ona}`});function Qsu({message:e,error:t,logger:r,logLevel:i=yc.Err
|
|
|
1389
1389
|
Run ${It.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
1390
1390
|
Run ${It.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),H7i(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function J4c({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!drh(e))return;let n=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let o=a.sort((c,d)=>c.generatorName.localeCompare(d.generatorName)||c.currentVersion.localeCompare(d.currentVersion));for(let c of o)n+=`
|
|
1391
1391
|
${await NID(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+It.dim(c.currentVersion)+It.reset(" \u2192 ")+It.green(c.latestVersion);return n+=`
|
|
1392
|
-
`,i?H7i(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function NID(e){let r=await new frh.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 FID({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await _rh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=xGi(u.name,l),_=await FVt({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 _rh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let l=xGi(s.name,u),p=await FVt({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function _rh({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 eve({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?yN(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function hrh(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 d=U$(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function Wsu({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await FID({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...hrh(s,d,t.logger));else o.push(...hrh(c.versions,void 0,t.logger))}return o}var OHa=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 jna=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var $4c=(()=>{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})(),yrh=typeof globalThis.AbortController=="function",brh=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",vrh=typeof globalThis.ReadableStream=="function",grh=typeof globalThis.FormData=="function",Gsu=["get","post","put","patch","head","delete"],QID=()=>{};QID();var Orh={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Hsu=2147483647,Arh=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,xsu=Symbol("stop"),mrh={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Prh={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 UID=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Arh,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},jrh=(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))}}))},wrh=(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(jrh(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},Erh=(e,t,r)=>{if(!e.body)return e;let i=UID(r??e.body);return new Request(e,{duplex:"half",body:jrh(e.body,i,t)})};var wna=e=>e!==null&&typeof e=="object";var AHa=(...e)=>{for(let t of e)if((!wna(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Z4c({},...e)},Y4c=(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 Ksu(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Z4c(e[r]??[],t[r]??[])}var X4c=(e={},t={})=>({beforeRequest:Ksu(e,t,"beforeRequest"),beforeRetry:Ksu(e,t,"beforeRetry"),afterResponse:Ksu(e,t,"afterResponse"),beforeError:Ksu(e,t,"beforeError")}),Z4c=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(wna(n)){for(let[a,o]of Object.entries(n))wna(o)&&a in t&&(o=Z4c(t[a],o)),t={...t,[a]:o};wna(n.hooks)&&(i=X4c(i,n.hooks),t.hooks=i),wna(n.headers)&&(r=Y4c(r,n.headers),t.headers=r)}return t};var Mrh=e=>Gsu.includes(e)?e.toUpperCase():e,LID=["get","put","head","delete","options","trace"],VID=[408,413,429,500,502,503,504],WID=[413,429,503],Srh={limit:2,methods:LID,statusCodes:VID,afterStatusCodes:WID,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Drh=(e={})=>{if(typeof e=="number")return{...Srh,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{...Srh,...e}};async function k4c(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new jna(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function eLc(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 Brh=(e,t)=>{let r={};for(let i in t)!(i in Prh)&&!(i in mrh)&&!(i in e)&&(r[i]=t[i]);return r},Irh=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 mHa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Hsu)throw new RangeError(`The \`timeout\` option cannot be greater than ${Hsu}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new OHa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!vrh)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return wrh(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,d=[];c&&!c.bodyUsed&&d.push(c.body?.cancel()),i.request.bodyUsed||d.push(i.request.body?.cancel()),await Promise.all(d)});for(let[c,d]of Object.entries(Orh))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);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:Y4c(this._input.headers,r.headers),hooks:X4c({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Mrh(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:Drh(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(yrh&&brh){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($4c&&(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),Irh(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);(grh&&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(!$4c)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=Erh(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof jna)throw t;if(t instanceof OHa){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),Hsu);if(this._retryCount<1)throw r;await eLc(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})===xsu)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=Brh(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):k4c(this._originalRequest,t,this.abortController,this._options)}};var tLc=e=>{let t=(r,i)=>mHa.create(r,AHa(e,i));for(let r of Gsu)t[r]=(i,n)=>mHa.create(i,AHa(e,n,{method:r}));return t.create=r=>tLc(AHa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),tLc(AHa(e,r))),t.stop=xsu,t},GID=tLc(),Crh=GID;var tih=ce(eih(),1);function oLc(e){let t=(0,tih.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var $ih=ce(Jih(),1),Yih=ce(Sbe(),1),gLc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},OLc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function ALc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??oLc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,$ih.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await Crh(o,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new gLc(e):l}if(t.allVersions)return s;let u=new OLc(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=Yih.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 MHa(e,t){let{version:r}=await ALc(e.toLowerCase(),t);return r}async function QKi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:MHa(e.packageName,{version:t?"prerelease":"latest"})}var Xih=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],acu=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=yc.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Vsu(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.31.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${It.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new YS}failWithoutThrowing(t,r){this.didSucceed=!1,Qsu({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await gkn()).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 prh({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1392
|
+
`,i?H7i(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function NID(e){let r=await new frh.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 FID({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await _rh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,l)=>{c.versions[s]==null&&(c.versions[s]={});let p=xGi(u.name,l),_=await FVt({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 _rh({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let l=xGi(s.name,u),p=await FVt({generatorName:l,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function _rh({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 eve({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?yN(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function hrh(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 d=U$(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function Wsu({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await FID({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...hrh(s,d,t.logger));else o.push(...hrh(c.versions,void 0,t.logger))}return o}var OHa=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 jna=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var $4c=(()=>{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})(),yrh=typeof globalThis.AbortController=="function",brh=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",vrh=typeof globalThis.ReadableStream=="function",grh=typeof globalThis.FormData=="function",Gsu=["get","post","put","patch","head","delete"],QID=()=>{};QID();var Orh={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Hsu=2147483647,Arh=new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,xsu=Symbol("stop"),mrh={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Prh={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 UID=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[r,i]of e)t+=Arh,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},jrh=(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))}}))},wrh=(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(jrh(e.body,r,t),{status:e.status,statusText:e.statusText,headers:e.headers})},Erh=(e,t,r)=>{if(!e.body)return e;let i=UID(r??e.body);return new Request(e,{duplex:"half",body:jrh(e.body,i,t)})};var wna=e=>e!==null&&typeof e=="object";var AHa=(...e)=>{for(let t of e)if((!wna(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Z4c({},...e)},Y4c=(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 Ksu(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Z4c(e[r]??[],t[r]??[])}var X4c=(e={},t={})=>({beforeRequest:Ksu(e,t,"beforeRequest"),beforeRetry:Ksu(e,t,"beforeRetry"),afterResponse:Ksu(e,t,"afterResponse"),beforeError:Ksu(e,t,"beforeError")}),Z4c=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(wna(n)){for(let[a,o]of Object.entries(n))wna(o)&&a in t&&(o=Z4c(t[a],o)),t={...t,[a]:o};wna(n.hooks)&&(i=X4c(i,n.hooks),t.hooks=i),wna(n.headers)&&(r=Y4c(r,n.headers),t.headers=r)}return t};var Mrh=e=>Gsu.includes(e)?e.toUpperCase():e,LID=["get","put","head","delete","options","trace"],VID=[408,413,429,500,502,503,504],WID=[413,429,503],Srh={limit:2,methods:LID,statusCodes:VID,afterStatusCodes:WID,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Drh=(e={})=>{if(typeof e=="number")return{...Srh,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{...Srh,...e}};async function k4c(e,t,r,i){return new Promise((n,a)=>{let o=setTimeout(()=>{r&&r.abort(),a(new jna(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function eLc(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 Brh=(e,t)=>{let r={};for(let i in t)!(i in Prh)&&!(i in mrh)&&!(i in e)&&(r[i]=t[i]);return r},Irh=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 mHa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Hsu)throw new RangeError(`The \`timeout\` option cannot be greater than ${Hsu}`);await Promise.resolve();let c=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(c.clone()));s instanceof globalThis.Response&&(c=s)}if(i._decorateResponse(c),!c.ok&&i._options.throwHttpErrors){let d=new OHa(c,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!vrh)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return wrh(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,d=[];c&&!c.bodyUsed&&d.push(c.body?.cancel()),i.request.bodyUsed||d.push(i.request.body?.cancel()),await Promise.all(d)});for(let[c,d]of Object.entries(Orh))c==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(o[c]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);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:Y4c(this._input.headers,r.headers),hooks:X4c({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Mrh(r.method??this._input.method??"GET"),prefixUrl:String(r.prefixUrl||""),retry:Drh(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(yrh&&brh){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($4c&&(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),Irh(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);(grh&&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(!$4c)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=Erh(this.request,this._options.onUploadProgress,this._options.body))}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof jna)throw t;if(t instanceof OHa){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),Hsu);if(this._retryCount<1)throw r;await eLc(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})===xsu)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=Brh(this.request,this._options);return this._originalRequest=this.request,this.request=this._originalRequest.clone(),this._options.timeout===!1?this._options.fetch(this._originalRequest,t):k4c(this._originalRequest,t,this.abortController,this._options)}};var tLc=e=>{let t=(r,i)=>mHa.create(r,AHa(e,i));for(let r of Gsu)t[r]=(i,n)=>mHa.create(i,AHa(e,n,{method:r}));return t.create=r=>tLc(AHa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),tLc(AHa(e,r))),t.stop=xsu,t},GID=tLc(),Crh=GID;var tih=ce(eih(),1);function oLc(e){let t=(0,tih.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var $ih=ce(Jih(),1),Yih=ce(Sbe(),1),gLc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},OLc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function ALc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??oLc(n),o=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),c=(0,$ih.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,c&&(d.authorization=`${c.type} ${c.token}`);let s;try{s=await Crh(o,{headers:d,keepalive:!0}).json()}catch(l){throw l?.response?.status===404?new gLc(e):l}if(t.allVersions)return s;let u=new OLc(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=Yih.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 MHa(e,t){let{version:r}=await ALc(e.toLowerCase(),t);return r}async function QKi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:MHa(e.packageName,{version:t?"prerelease":"latest"})}var Xih=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],acu=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=yc.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Vsu(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.31.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${It.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new YS}failWithoutThrowing(t,r){this.didSucceed=!1,Qsu({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await gkn()).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 prh({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1393
1393
|
`)||(r+=`
|
|
1394
1394
|
`),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=I2s(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 _Ha(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 YS}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await gkn()).sendEvent(t)}logger=zHt((t,...r)=>this.log(t,...r));stderr=zHt((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=Zih(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?Zih(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=Xih[this.numTasks++%Xih.length],o=It.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===jw.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=>hGi.indexOf(n.level)>=hGi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===yc.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 QKi({cliEnvironment:this.environment,includePreReleases:t}),i=U$(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await Wsu({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await z4c({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:It.yellow("?"),style:{answer:n=>It.cyan(n),message:n=>It.bold(n),highlight:n=>It.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
|
|
1395
1395
|
Cancelled by user.`),new YS):i}}async getInput(t){return await C4c({message:t.message,default:t.default})}};function Zih(e){return`[${e}]:`}var L3t=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 ocu(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)=>ocu.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 kih(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(d=>(c=d,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 enh(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 tnh=Function.bind,rnh=tnh.bind(tnh);function inh(e,t,r){let i=rnh(enh,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]=rnh(kih,null).apply(null,a)})}function YCD(){let e=Symbol("Singular"),t={registry:{}},r=ocu.bind(null,t,e);return inh(r,t,e),r}function XCD(){let e={registry:{}},t=ocu.bind(null,e);return inh(t,e),t}var nnh={Singular:YCD,Collection:XCD};var ZCD="0.0.0-development",kCD=`octokit-endpoint.js/${ZCD} ${AN()}`,eqD={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":kCD},mediaType:{format:""}};function tqD(e){return e?Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{}):{}}function rqD(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 unh(e,t){let r=Object.assign({},e);return Object.keys(t).forEach(i=>{rqD(t[i])?i in e?r[i]=unh(e[i],t[i]):Object.assign(r,{[i]:t[i]}):Object.assign(r,{[i]:t[i]})}),r}function anh(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function PLc(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=tqD(r.headers),anh(r),anh(r.headers);let i=unh(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 iqD(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 nqD=/\{[^{}}]+\}/g;function aqD(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function oqD(e){let t=e.match(nqD);return t?t.map(aqD).reduce((r,i)=>r.concat(i),[]):[]}function onh(e,t){let r={__proto__:null};for(let i of Object.keys(e))t.indexOf(i)===-1&&(r[i]=e[i]);return r}function snh(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 qna(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}function DHa(e,t,r){return t=e==="+"||e==="#"?snh(t):qna(t),r?qna(r)+"="+t:t}function Cna(e){return e!=null}function mLc(e){return e===";"||e==="&"||e==="?"}function uqD(e,t,r,i){var n=e[r],a=[];if(Cna(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(DHa(t,n,mLc(t)?r:""));else if(i==="*")Array.isArray(n)?n.filter(Cna).forEach(function(o){a.push(DHa(t,o,mLc(t)?r:""))}):Object.keys(n).forEach(function(o){Cna(n[o])&&a.push(DHa(t,n[o],o))});else{let o=[];Array.isArray(n)?n.filter(Cna).forEach(function(c){o.push(DHa(t,c))}):Object.keys(n).forEach(function(c){Cna(n[c])&&(o.push(qna(c)),o.push(DHa(t,n[c].toString())))}),mLc(t)?a.push(qna(r)+"="+o.join(",")):o.length!==0&&a.push(o.join(","))}else t===";"?Cna(n)&&a.push(qna(r)):n===""&&(t==="&"||t==="?")?a.push(qna(r)+"="):n===""&&a.push("");return a}function sqD(e){return{expand:cqD.bind(null,e)}}function cqD(e,t){var r=["+","#",".","/",";","?","&"];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(i,n,a){if(n){let c="",d=[];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);d.push(uqD(t,c,u[1],u[2]||u[3]))}),c&&c!=="+"){var o=",";return c==="?"?o="&":c!=="#"&&(o=c),(d.length!==0?c:"")+d.join(o)}else return d.join(",")}else return snh(a)}),e==="/"?e:e.replace(/\/$/,"")}function cnh(e){let t=e.method.toUpperCase(),r=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),i=Object.assign({},e.headers),n,a=onh(e,["method","baseUrl","url","headers","request","mediaType"]),o=oqD(r);r=sqD(r).expand(a),/^http/.test(r)||(r=e.baseUrl+r);let c=Object.keys(e).filter(u=>o.includes(u)).concat("baseUrl"),d=onh(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=iqD(r,d):"data"in d?n=d.data:Object.keys(d).length&&(n=d),!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 lqD(e,t,r){return cnh(PLc(e,t,r))}function lnh(e,t){let r=PLc(e,t),i=lqD.bind(null,r);return Object.assign(i,{DEFAULTS:r,defaults:lnh.bind(null,r),merge:PLc.bind(null,r),parse:cnh})}var fnh=lnh(null,eqD);var bnh=ce(hnh(),1);var V3t=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 fqD="10.0.6",dqD={headers:{"user-agent":`octokit-request.js/${fqD} ${AN()}`}};function pqD(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 ynh(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=pqD(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 V3t(p,500,{request:e});throw _.cause=l,_}let c=o.status,d=o.url,s={};for(let[l,p]of o.headers)s[l]=p;let u={url:d,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 V3t(o.statusText,c,{response:u,request:e})}if(c===304)throw u.data=await jLc(o),new V3t("Not modified",c,{response:u,request:e});if(c>=400)throw u.data=await jLc(o),new V3t(hqD(u.data),c,{response:u,request:e});return u.data=i?await jLc(o):o.body,u}async function jLc(e){let t=e.headers.get("content-type");if(!t)return e.text().catch(()=>"");let r=(0,bnh.safeParse)(t);if(_qD(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 _qD(e){return e.type==="application/json"||e.type==="application/scim+json"}function hqD(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 wLc(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 ynh(r.parse(o));let c=(d,s)=>ynh(r.parse(r.merge(d,s)));return Object.assign(c,{endpoint:r,defaults:wLc.bind(null,r)}),o.request.hook(c,o)},{endpoint:r,defaults:wLc.bind(null,r)})}var MA=wLc(fnh,dqD);var yqD="0.0.0-development";function bqD(e){return`Request failed due to following response errors:
|
|
@@ -1781,7 +1781,7 @@ A valid API configuration was not found at the path: fern/apis/${t.apiName}.
|
|
|
1781
1781
|
Learn more about project structure:
|
|
1782
1782
|
https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`:`Failed to load API Definition referenced in docs.
|
|
1783
1783
|
Learn more about project structure:
|
|
1784
|
-
https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`;throw new Error(r)}async toRootNode(){let t=Rt.V1.SlugGenerator.init(Rt.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Rt.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return Tln(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Rt.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??KE(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,o=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:o}}async toVersionedNode(t,r){let i=this.#e.get("versioned"),n=t.versions[0];if(n?.hidden===!0)throw new Error(`The default version "${n.version}" cannot be hidden. Please set a non-hidden version as the first version in your versions list, or remove the hidden flag from the default version.`);return{id:i,type:"versioned",children:await Promise.all(t.versions.map((a,o)=>this.toVersionNode(a,r,o===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(o=>this.toProductNode(o,i)))}}async toProductNode(t,r){if(t.type==="internal"){let i=r.setProductSlug(t.slug??KE(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:gt(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Rt.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}else return{type:"productLink",id:this.#e.get(t.product),productId:Rt.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",href:yG.Url(t.href??""),target:t.target,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,viewers:t.viewers,orphaned:t.orphaned}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??KE(t.version)),o=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Rt.VersionId(t.version),title:t.version,slug:a.get(),child:o,default:i,availability:t.availability!=null?odB(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(c=>this.toNavigationChild({prefix:n,item:c,parentSlug:i}))),o=[];return a.forEach(c=>{if(c.type==="apiReference"){o.push(c);return}if(c.type==="section"&&!c.collapsed){o.push(c);return}let d=o.length>0?o[o.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},o.push(s)),s.children.push(c)}),{type:"sidebarRoot",id:n,children:o}}async toSidebarRootNodeWithVariants(t,r,i){let n=this.#e.get(`${t}/root`);return{type:"sidebarRoot",id:n,children:[{type:"varianted",id:n,children:await Promise.all(r.map(a=>this.toVariantNode(a,n,i)))}]}}async toVariantNode(t,r,i){let n=this.#e.get(`${r}/variant/${t.slug??KE(t.title)}`),a=i.apply({urlSlug:t.slug??KE(t.title),skipUrlSlug:t.skipUrlSlug}),o=await Promise.all(t.layout.map(c=>this.toVariantChild(c,n,a)));return{type:"variant",id:n,variantId:Rt.V1.VariantId(t.title),subtitle:t.subtitle??"",default:t.default??!1,image:void 0,children:o,title:t.title,slug:a.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,pointsTo:void 0}}async toVariantChild(t,r,i){return Tln(t)._visit({page:async n=>this.toPageNode({item:n,parentSlug:i}),apiSection:async n=>this.toApiSectionNode({item:n,parentSlug:i}),section:async n=>this.toSectionNode({prefix:r,item:n,parentSlug:i}),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i)})}async toNavigationChild({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){return Tln(r)._visit({page:async o=>this.toPageNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),apiSection:async o=>this.toApiSectionNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),section:async o=>this.toSectionNode({prefix:t,item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),link:async o=>this.toLinkNode(o),changelog:async o=>this.toChangelogNode(o,i,n)})}async toApiSectionNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=CMh(t.snippetsConfiguration),o,c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),d=this.parsedDocsConfig.experimental?.openapiParserV3,s=d==null||d;if(s)try{o=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1})}catch{}let u;if(t.tagDescriptionPages&&s)try{let b=await this.getOpenApiWorkspaceForApiSection(t).getOpenAPIIr({context:this.taskContext});b.tags.tagsById&&(u=Object.fromEntries(Object.entries(b.tags.tagsById).filter(([v,O])=>O.description&&O.description.trim().length>0).map(([v,O])=>[v,{id:String(O.id),description:O.description}])))}catch(y){this.taskContext.logger.warn("Failed to extract OpenAPI tags for tag description pages",String(y))}o==null&&(o=lS({workspace:c,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new cS(this.taskContext,c)})),this.docsWorkspace.config.settings?.substituteEnvVars&&(o=FT(o,{onError:y=>this.taskContext.failAndThrow(`Error substituting environment variables in API spec: ${y}`)},{substituteAsEmpty:!1}));let l=await this.registerApi({ir:o,snippetsConfig:a,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName,workspace:c}),p=UKa({ir:o,apiDefinitionId:l,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext}),_=new Hgu(t,p,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,this.collectedFileIds,c,i,n??t.availability,u),h=_.getTagDescriptionContent();for(let[y,b]of h.entries()){let v=y.split("/").pop()||y,O=Ze.of(v),A=b;this.docsWorkspace.config.settings?.substituteEnvVars&&(A=FT(b,{onError:g=>this.taskContext.logger.error(`Error in tag description environment variable substitution: ${g}`)},{substituteAsEmpty:!1})),this.rawMarkdownFiles[O]=A,this.parsedDocsConfig.pages[O]=A}return _.get()}async toChangelogNode(t,r,i){return new Mvn(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Rt.V1.Url(t.url),icon:this.resolveIconFileId(t.icon),target:t.target}}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Rt.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??KE(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Rt.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??KE(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,l=n||r.hidden;return{id:d,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:l,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(p=>this.toNavigationChild({prefix:d,item:p,parentSlug:s,hideChildren:l,parentAvailability:r.availability??a}))),authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return Tln(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new Mvn(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Rt.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??KE(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??KE(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):yG.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(As),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:yG.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return Tln(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:yG.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function adB(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${mR(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function odB(e){switch(e){case"beta":return Rt.V1.NavigationV1Availability.Beta;case"deprecated":return Rt.V1.NavigationV1Availability.Deprecated;case"ga":return Rt.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Rt.V1.NavigationV1Availability.Stable;default:gt(e)}}async function dL(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof sS?t:null))).filter(As)}async function jxc(e,t,r){if(e instanceof LEe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof sS))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});return pH({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var oc={};Zt(oc,{AlgoliaSearchIndex:()=>ZMh,ApiDefinitionId:()=>gDh,ApiId:()=>PDh,Availability:()=>FDh,DocsConfigId:()=>jDh,EndpointId:()=>EDh,EndpointPathLiteral:()=>zDh,EnvironmentId:()=>wDh,FileId:()=>IDh,HttpMethod:()=>NDh,IndexSegmentId:()=>kMh,JqString:()=>qDh,OrgId:()=>ADh,PageId:()=>BDh,PayloadLocation:()=>fBh,PropertyKey:()=>TDh,PullRequestState:()=>oBh,RoleId:()=>RDh,TokenId:()=>mDh,TypeId:()=>DDh,Url:()=>CDh,VersionId:()=>ODh,WebSocketId:()=>SDh,WebhookId:()=>MDh,algolia:()=>wxc,api:()=>Rxc,commons:()=>zxc,diff:()=>QDh,docs:()=>Hxc,generators:()=>Kxc,git:()=>Jxc,navigation:()=>Xxc,sdks:()=>kxc,snippets:()=>cBh,snippetsFactory:()=>lBh,templates:()=>eKc,tokens:()=>dBh});var wxc={};Zt(wxc,{AlgoliaSearchIndex:()=>ZMh,IndexSegmentId:()=>kMh});function ZMh(e){return e}function kMh(e){return e}var Rxc={};Zt(Rxc,{latest:()=>Mxc,v1:()=>Txc});var Mxc={};Zt(Mxc,{AuthSchemeId:()=>eDh,WebhookHttpMethod:()=>nDh,auth:()=>Exc,commons:()=>tDh,endpoint:()=>rDh,type_:()=>iDh,webhook:()=>Sxc,websocket:()=>aDh});var Exc={};Zt(Exc,{AuthSchemeId:()=>eDh});function eDh(e){return e}var tDh={};var rDh={};var iDh={};var Sxc={};Zt(Sxc,{WebhookHttpMethod:()=>nDh});var nDh={Get:"GET",Post:"POST"};var aDh={};var Txc={};Zt(Txc,{SubpackageId:()=>hDh,WebSocketMessageId:()=>yDh,WebSocketMessageOrigin:()=>bDh,WebhookHttpMethod:()=>vDh,commons:()=>qxc,db:()=>Dxc,read:()=>Ixc,register:()=>Cxc});var Dxc={};Zt(Dxc,{endpoint:()=>oDh});var oDh={};var Ixc={};Zt(Ixc,{SupportedLanguage:()=>uDh,endpoint:()=>Bxc,type_:()=>sDh,webhook:()=>cDh,websocket:()=>lDh});var Bxc={};Zt(Bxc,{SupportedLanguage:()=>uDh});var uDh={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var sDh={};var cDh={};var lDh={};var Cxc={};Zt(Cxc,{SourceId:()=>udB,endpoint:()=>fDh,type_:()=>dDh,webhook:()=>pDh,websocket:()=>_Dh});var fDh={};var dDh={};var pDh={};var _Dh={};function udB(e){return e}var qxc={};Zt(qxc,{SubpackageId:()=>hDh,WebSocketMessageId:()=>yDh,WebSocketMessageOrigin:()=>bDh,WebhookHttpMethod:()=>vDh});function hDh(e){return e}function yDh(e){return e}var bDh={Client:"client",Server:"server"};var vDh={Get:"GET",Post:"POST"};var zxc={};Zt(zxc,{ApiDefinitionId:()=>gDh,ApiId:()=>PDh,Availability:()=>FDh,DocsConfigId:()=>jDh,EndpointId:()=>EDh,EndpointPathLiteral:()=>zDh,EnvironmentId:()=>wDh,FileId:()=>IDh,HttpMethod:()=>NDh,JqString:()=>qDh,OrgId:()=>ADh,PageId:()=>BDh,PropertyKey:()=>TDh,RoleId:()=>RDh,TokenId:()=>mDh,TypeId:()=>DDh,Url:()=>CDh,VersionId:()=>ODh,WebSocketId:()=>SDh,WebhookId:()=>MDh});function gDh(e){return e}function ODh(e){return e}function ADh(e){return e}function mDh(e){return e}function PDh(e){return e}function jDh(e){return e}function wDh(e){return e}function EDh(e){return e}function SDh(e){return e}function MDh(e){return e}function DDh(e){return e}function BDh(e){return e}function IDh(e){return e}function CDh(e){return e}function qDh(e){return e}function TDh(e){return e}function RDh(e){return e}function zDh(e){return e}var NDh={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var FDh={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var QDh={};var Hxc={};Zt(Hxc,{latest:()=>Qxc,v1:()=>Wxc,v2:()=>Gxc});var Qxc={};Zt(Qxc,{Layout:()=>LDh,MdxEngine:()=>sdB,TwitterCardSetting:()=>VDh,commons:()=>UDh,frontmatter:()=>Nxc,seo:()=>Fxc});var sdB={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var UDh={};var Nxc={};Zt(Nxc,{Layout:()=>LDh});var LDh={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var Fxc={};Zt(Fxc,{TwitterCardSetting:()=>VDh});var VDh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Wxc={};Zt(Wxc,{commons:()=>Vxc,db:()=>WDh,read:()=>GDh,write:()=>Uxc});var WDh={};var GDh={};var Uxc={};Zt(Uxc,{DocsRegistrationId:()=>ldB,FilePath:()=>cdB});function cdB(e){return e}function ldB(e){return e}var Vxc={};Zt(Vxc,{ContentAlignment:()=>JDh,FontDisplay:()=>kDh,FontStyle:()=>ZDh,HeaderPosition:()=>$Dh,JsScriptStrategy:()=>XDh,ProgrammingLanguage:()=>HDh,SearchbarPlacement:()=>xDh,TabsPlacement:()=>KDh,TwitterCardSetting:()=>YDh,commons:()=>Lxc});var Lxc={};Zt(Lxc,{ContentAlignment:()=>JDh,FontDisplay:()=>kDh,FontStyle:()=>ZDh,HeaderPosition:()=>$Dh,JsScriptStrategy:()=>XDh,ProgrammingLanguage:()=>HDh,SearchbarPlacement:()=>xDh,TabsPlacement:()=>KDh,TwitterCardSetting:()=>YDh});var HDh={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var xDh={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var KDh={Header:"HEADER",Sidebar:"SIDEBAR"};var JDh={Center:"CENTER",Left:"LEFT"};var $Dh={Fixed:"FIXED",Absolute:"ABSOLUTE"};var YDh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var XDh={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var ZDh={Normal:"normal",Italic:"italic"};var kDh={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Gxc={};Zt(Gxc,{read:()=>eBh,write:()=>tBh});var eBh={};var tBh={};var Kxc={};Zt(Kxc,{ChangelogEntryType:()=>iBh,GeneratorId:()=>fdB,GeneratorLanguage:()=>ddB,ReleaseType:()=>nBh,cli:()=>rBh,commons:()=>xxc,versions:()=>aBh});var rBh={};var xxc={};Zt(xxc,{ChangelogEntryType:()=>iBh,ReleaseType:()=>nBh});var iBh={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var nBh={Ga:"GA",Rc:"RC"};var aBh={};function fdB(e){return e}var ddB={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Jxc={};Zt(Jxc,{PullRequestState:()=>oBh});var oBh={Open:"open",Closed:"closed",Merged:"merged"};var Xxc={};Zt(Xxc,{latest:()=>$xc,v1:()=>Yxc});var $xc={};Zt($xc,{NodeId:()=>hdB,ProductId:()=>ydB,Slug:()=>pdB,TabId:()=>_dB});function pdB(e){return e}function _dB(e){return e}function hdB(e){return e}function ydB(e){return e}var Yxc={};Zt(Yxc,{NavigationV1Availability:()=>AdB,NodeId:()=>gdB,ProductId:()=>OdB,Slug:()=>bdB,TabId:()=>vdB});function bdB(e){return e}function vdB(e){return e}function gdB(e){return e}function OdB(e){return e}var AdB={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var kxc={};Zt(kxc,{Language:()=>uBh,VersionBump:()=>sBh,versions:()=>Zxc});var Zxc={};Zt(Zxc,{Language:()=>uBh,VersionBump:()=>sBh});var uBh={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var sBh={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var cBh={};var lBh={};var eKc={};Zt(eKc,{PayloadLocation:()=>fBh});var fBh={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var dBh={};var eOu=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Lo(e){return e!=null}var _Bh=ce(eQa(),1);var pBh=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function QYt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,_Bh.default)(e,{special:pBh}).replace(/V\s(\d)/g,"V$1")}function hBh({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let o=[...n,a],c=oc.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:QYt(a)},n.push(a)})}),r}var tOu=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function yBh(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var ho=class extends tOu{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((o,c)=>o===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${yBh(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},pC=class extends ho{},oY=class extends pC{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var bBh="x-fern-base-path",vBh="x-fern-availability",rOu="x-fern-sdk-group-name",gBh="x-fern-global-headers",OBh="x-fern-sdk-method-name";var ABh="x-fern-webhook",mBh="x-fern-access-token-locator",PBh="x-fern-basic",jBh="x-fern-username-variable-name",wBh="x-fern-password-variable-name",EBh="x-fern-bearer",SBh="x-fern-token-variable-name",MBh="x-fern-header",DBh="x-fern-header-variable-name",BBh="x-fern-server-name",IBh="x-fern-examples";var iOu=class extends ho{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[BBh]}convert(){if(this.serverName!=null)return this.serverName}};var nOu=class extends ho{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new iOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:oc.EnvironmentId(t),baseUrl:this.url}}};function v$i(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),o=(t??[]).filter(c=>!a.has(c.url)).map((c,d)=>new nOu({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...o]}function xv(e){return typeof e=="object"&&Lo(e)&&"$ref"in e&&typeof e.$ref=="string"}function pL(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(xv(n)&&(n=pL(n,t,r)),n)}function aOu(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return xv(r)?pL(r,t,void 0):r}var mIh=ce(ZS());var oOu=class extends ho{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[PBh];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var uOu=class extends ho{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[wBh]}convert(){return this.passwordVariableName}};var sOu=class extends ho{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[jBh]}convert(){return this.usernameVariableName}};var cOu=class extends ho{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[EBh];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var lOu=class extends ho{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[SBh]}convert(){return this.tokenVariableName}};function CBh(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var qBh="x-bearer-format",TBh="x-code-samples",RBh="x-codeSamples";var fOu=class extends ho{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[qBh]}convert(){return this.bearerFormat}};var dOu=class extends ho{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[MBh];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var pOu=class extends ho{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[DBh]}convert(){return this.headerVariableName}};function zBh(e){return e.type==="apiKey"}var Uua=class extends ho{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){zBh(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new dOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new pOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new fOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function _Ou(e){return e}function hOu(e){return e==="__proto__"}function yOu(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function Lua(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function LKa(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(LKa).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function bOu(e){if(Array.isArray(e))return e.map(Lua);if(typeof e=="symbol")return[e];e=LKa(e);let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",o=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:o?c==='"'||c==="'"?a=c:c==="]"?(o=!1,t.push(n),n=""):n+=c:c==="["?(o=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function VKa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(hOu(t))return r;let i=e[t];return i===void 0?yOu(t)?VKa(e,bOu(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=Lua(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return mdB(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),hOu(t))return r;let i=e[t];return i===void 0?r:i}}}function mdB(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||hOu(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function NBh(e){return function(t){return VKa(t,e)}}function FBh(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function vOu(e){return e==null||typeof e!="object"&&typeof e!="function"}function tKc(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function iKc(e,t,r){return typeof r!="function"?iKc(e,t,()=>{}):rKc(e,t,function i(n,a,o,c,d,s){let u=r(n,a,o,c,d,s);return u!==void 0?!!u:rKc(n,a,i,s)},new Map)}function rKc(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return PdB(e,t,r,i);case"function":return Object.keys(t).length>0?rKc(e,{...t},r,i):tKc(e,t);default:return FBh(e)?typeof t=="string"?t==="":!0:tKc(e,t)}}function PdB(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return QBh(e,t,r,i);if(t instanceof Map)return jdB(e,t,r,i);if(t instanceof Set)return wdB(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i?.has(t))return i.get(t)===e;i?.set(t,e);try{for(let a=0;a<n.length;a++){let o=n[a];if(!vOu(e)&&!(o in e)||t[o]===void 0&&e[o]!==void 0||t[o]===null&&e[o]!==null||!r(e[o],t[o],o,e,t,i))return!1}return!0}finally{i?.delete(t)}}function jdB(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let o=e.get(n);if(r(o,a,n,e,t,i)===!1)return!1}return!0}function QBh(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let o=t[a],c=!1;for(let d=0;d<e.length;d++){if(n.has(d))continue;let s=e[d],u=!1;if(r(s,o,a,e,t,i)&&(u=!0),u){n.add(d),c=!0;break}}if(!c)return!1}return!0}function wdB(e,t,r,i){return t.size===0?!0:e instanceof Set?QBh([...e],[...t],r,i):!1}function gOu(e,t){return iKc(e,t,()=>{})}function UBh(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function OOu(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}var LBh="[object RegExp]",AOu="[object String]",mOu="[object Number]",POu="[object Boolean]",jOu="[object Arguments]",VBh="[object Symbol]",WBh="[object Date]",GBh="[object Map]",HBh="[object Set]",xBh="[object Array]";var KBh="[object ArrayBuffer]",JBh="[object Object]";var $Bh="[object DataView]",YBh="[object Uint8Array]",XBh="[object Uint8ClampedArray]",ZBh="[object Uint16Array]",kBh="[object Uint32Array]";var eIh="[object Int8Array]",tIh="[object Int16Array]",rIh="[object Int32Array]";var iIh="[object Float32Array]",nIh="[object Float64Array]";function aIh(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function oIh(e,t){return g$i(e,void 0,e,new Map,t)}function g$i(e,t,r,i=new Map,n=void 0){let a=n?.(e,t,r,i);if(a!==void 0)return a;if(vOu(e))return e;if(i.has(e))return i.get(e);if(Array.isArray(e)){let o=new Array(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=g$i(e[c],c,r,i,n);return Object.hasOwn(e,"index")&&(o.index=e.index),Object.hasOwn(e,"input")&&(o.input=e.input),o}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){let o=new RegExp(e.source,e.flags);return o.lastIndex=e.lastIndex,o}if(e instanceof Map){let o=new Map;i.set(e,o);for(let[c,d]of e)o.set(c,g$i(d,c,r,i,n));return o}if(e instanceof Set){let o=new Set;i.set(e,o);for(let c of e)o.add(g$i(c,void 0,r,i,n));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(aIh(e)){let o=new(Object.getPrototypeOf(e)).constructor(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=g$i(e[c],c,r,i,n);return o}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){let o=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return i.set(e,o),v8t(o,e,r,i,n),o}if(typeof File<"u"&&e instanceof File){let o=new File([e],e.name,{type:e.type});return i.set(e,o),v8t(o,e,r,i,n),o}if(typeof Blob<"u"&&e instanceof Blob){let o=new Blob([e],{type:e.type});return i.set(e,o),v8t(o,e,r,i,n),o}if(e instanceof Error){let o=new e.constructor;return i.set(e,o),o.message=e.message,o.name=e.name,o.stack=e.stack,o.cause=e.cause,v8t(o,e,r,i,n),o}if(e instanceof Boolean){let o=new Boolean(e.valueOf());return i.set(e,o),v8t(o,e,r,i,n),o}if(e instanceof Number){let o=new Number(e.valueOf());return i.set(e,o),v8t(o,e,r,i,n),o}if(e instanceof String){let o=new String(e.valueOf());return i.set(e,o),v8t(o,e,r,i,n),o}if(typeof e=="object"&&EdB(e)){let o=Object.create(Object.getPrototypeOf(e));return i.set(e,o),v8t(o,e,r,i,n),o}return e}function v8t(e,t,r=e,i,n){let a=[...Object.keys(t),...UBh(t)];for(let o=0;o<a.length;o++){let c=a[o],d=Object.getOwnPropertyDescriptor(e,c);(d==null||d.writable)&&(e[c]=g$i(t[c],c,r,i,n))}}function EdB(e){switch(OOu(e)){case jOu:case xBh:case KBh:case $Bh:case POu:case WBh:case iIh:case nIh:case eIh:case tIh:case rIh:case GBh:case mOu:case JBh:case LBh:case HBh:case AOu:case VBh:case YBh:case XBh:case ZBh:case kBh:return!0;default:return!1}}function uIh(e){return g$i(e,void 0,e,new Map,void 0)}function sIh(e){return e=uIh(e),t=>gOu(t,e)}function cIh(e,t){return oIh(e,(r,i,n,a)=>{let o=t?.(r,i,n,a);if(o!==void 0)return o;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case mOu:case AOu:case POu:{let c=new e.constructor(e?.valueOf());return v8t(c,e),c}case jOu:{let c={};return v8t(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function lIh(e){return cIh(e)}var SdB=/^(?:0|[1-9]\d*)$/;function fIh(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return SdB.test(e)}}function dIh(e){return e!==null&&typeof e=="object"&&OOu(e)==="[object Arguments]"}function pIh(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&yOu(t)&&e?.[t]==null?r=bOu(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||dIh(i))&&fIh(a)&&a<i.length))return!1;i=i[a]}return!0}function _Ih(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=Lua(e);break}}return t=lIh(t),function(r){let i=VKa(r,e);return i===void 0?pIh(r,e):t===void 0?i===void 0:gOu(i,t)}}function hIh(e){if(e==null)return _Ou;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?_Ih(e[0],e[1]):sIh(e);case"string":case"symbol":case"number":return NBh(e)}}function yIh(e,t){let r={},i=Object.keys(e);for(let n=0;n<i.length;n++){let a=i[n],o=e[a];r[a]=t(o,a,e)}return r}function wOu(e,t=_Ou){return e==null?{}:yIh(e,hIh(t))}function bIh(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var MdB=new RegExp("\\p{Lu}?\\p{Ll}+|[0-9]+|\\p{Lu}+(?!\\p{Ll})|\\p{Emoji_Presentation}|\\p{Extended_Pictographic}|\\p{L}+","gu");function vIh(e){return Array.from(e.match(MdB)??[])}function gIh(e){let t=vIh(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>bIh(n)).join("")}`}function OIh(e){return typeof e!="string"&&(e=LKa(e)),e.replace(/['\u2019]/g,"")}function g8t(e){return gIh(OIh(e))}function HP(e){if(e!=null)return Array.isArray(e)?e:[e]}function EOu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:o}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${DdB(o)}${BdB(e)}.${IdB(i,n,a,c)}`}function DdB(e){return e?"webhook_":"endpoint_"}function BdB(e){return e!=null?HP(e)?.map(t=>g8t(t)).join("/"):""}function IdB(e,t,r,i){return e||t||g8t(r??"")||g8t(i??"")}function AIh(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var SOu=class extends ho{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[mBh],this.accessTokenLocator!=null&&(AIh(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var MOu=class extends ho{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new Uua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new SOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=EOu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:oc.EndpointId(r),accessTokenLocator:oc.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var Vua=class extends ho{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new oOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new sOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new uOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new cOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new lOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{CBh(this.input)?(this.authScheme="header",this.headerAuthNode=new Uua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new MOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new mIh.UnreachableCaseError(this.authScheme);return}}};var Wua=class extends ho{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=aOu(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new Vua({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(Lo))}};var DOu=class extends ho{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[bBh],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function PIh(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function jIh(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function Gua(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>HP(n.convert())?.map(o=>((t!=null&&!t.includes(i)||t==null&&!PIh(n))&&(o=jIh(o,o.type==="enum"?o.default:void 0)),{key:oc.PropertyKey(i),valueShape:o,description:n.description,availability:n.availability?.convert()})).filter(Lo)).filter(Lo).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]])}function BOu(e,t){return xv(e)?pL(e,t,void 0):e}function O$i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function wIh(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function EIh(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var SIh=ce(ZS());var nKc=["decimal","decimal128","double-int","double","float","sf-decimal"],aKc=["int16","int32","int64","int8","sf-integer","uint8"],oKc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],uKc=["beta","pre-release","in-development","generally-available","deprecated"];function _C(e,t){return xv(e)?pL(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var ZEe=class extends ho{availability;constructor(t){super(t),this.safeParse()}parse(){if(_C(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[vBh];r!=null&&(uKc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${uKc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return oc.Availability.Beta;case"in-development":return oc.Availability.InDevelopment;case"generally-available":return oc.Availability.GenerallyAvailable;case"deprecated":return oc.Availability.Deprecated;case void 0:return;default:new SIh.UnreachableCaseError(this.availability);return}}};var COu=ce(ZS());function MIh(e){return typeof e=="object"&&e!=null&&"language"in e}function DIh(e){return typeof e=="object"&&e!=null&&"sdk"in e}function BIh(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function IIh(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function IOu(e){return typeof e=="object"&&e!=null&&"event"in e}function sKc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(IOu)}function A$i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function CIh(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var qOu=class extends ho{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[IBh]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let o=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return A$i(o)?[n,{type:"filenameWithData",filename:o.filename,data:oc.FileId(o.data)}]:o!=null?[n,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>A$i(c)))return[n,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:oc.FileId(c.data)}))}];if(o.every(c=>typeof c=="string"))return[n,{type:"filenames",value:o}]}return}case"property":return[n,{type:"json",value:o}];case void 0:return;default:new COu.UnreachableCaseError(a.multipartType);return}}).filter(Lo))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=CIh(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new COu.UnreachableCaseError(n.contentType);break}let o;switch(i.contentType){case"application/json":{BIh(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{sKc(r.response)&&(o={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!sKc(r.response)&&IIh(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new COu.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(l=>{MIh(l)?l.language!=null&&(c[l.language]??=[],c[l.language]?.push({name:l.name,language:l.language,install:l.install,code:l.code,generated:!1,description:l.docs})):DIh(l)&&l.sdk!=null&&(c[l.sdk]??=[],c[l.sdk]?.push({name:l.name,language:l.sdk,install:void 0,code:l.code,generated:!1,description:l.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([l,p])=>[oc.PropertyKey(l),p])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,p])=>[oc.PropertyKey(l),p])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([l,p])=>[oc.PropertyKey(l),p]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(u).length>0?u:void 0,requestBody:a,responseBody:o,snippets:c}}))}};var WKa=class extends ho{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[rOu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>oc.api.v1.SubpackageId(g8t(r)))}};var TOu=class extends ho{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[OBh]}convert(){return this.sdkMethodName}};var ROu=class extends ho{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[ABh]}convert(){return this.isWebhook}};var zOu=class extends ho{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[TBh]??[],...this.input[RBh]??[]],this.codeSamples.forEach(t=>{[...Object.values(oc.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var Dvn=ce(ZS());function cKc(e,t){return xv(e)?pL(e,t,void 0):e}function qIh(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var yF="",UYt=class extends ho{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(A$i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>A$i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new Dvn.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=cKc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=cKc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new Dvn.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(IOu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new Dvn.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return A$i(n)?[r,{type:"filenameWithData",filename:n.filename,data:oc.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>A$i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:oc.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new Dvn.UnreachableCaseError(i.multipartType);return}}).filter(Lo))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new Dvn.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new Dvn.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([o,c])=>[o,c.example({includeOptionals:!1,override:o})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(Lo));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(Lo));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:qIh(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?QYt(this.name):this.summary!=null?QYt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function TIh(e,t){return xv(e)?pL(e,t,void 0):e}var KIh=ce(ZS());var RIh="#/components/schemas/";function Hua(e){if(e.$ref.startsWith(RIh))return e.$ref.replace(RIh,"")}function BUi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function m$i(e){return typeof e.type=="string"&&e.type==="array"}function zIh(e){return e.type==="boolean"}function NIh(e){return e.type==="integer"}function P$i(e){return!Array.isArray(e.type)&&!m$i(e)}function FIh(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||P$i(t)||m$i(t))}function QIh(e){return"nullable"in e&&typeof e.nullable=="boolean"}function UIh(e){return e.type==="null"}function LIh(e){return e.type==="number"}function lKc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function VIh(e){return e.type==="string"}var NOu=class extends oY{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new ew({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return HP(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var FOu=class extends pC{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new ZEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var QOu=class extends oY{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new ew({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Lo)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>HP(n.convert())?.map(o=>({displayName:n.name,shape:o,description:n.description,availability:n.availability?.convert()}))).filter(Lo).reduce((n,a)=>n.flatMap(o=>a.length>0?a.map(c=>[...o,c]):[[...o]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(BUi).filter(Lo):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function UOu(e){return e!=null&&e.length>0?e:[void 0]}var xua=class extends oY{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new ew({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new ew({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(xv(t))return Hua(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new ew({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Lo))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return Gua(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:HP(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(Lo)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>UOu(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>oc.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=_C(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,o])=>[a,new ew({input:o,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var LOu=class extends oY{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>_C(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>_C(t,this.context.document)?.type!=="null"?new ew({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Lo);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=_C({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new ew({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(Lo);return this.isNullable&&n!=null?n.map(BUi).filter(Lo):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:oc.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>HP(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??QYt(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(Lo)).filter(Lo)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>HP(n.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?QYt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(o.type==="alias"&&o.value.type==="id"?QYt(o.value.id):c),shape:o,description:n.description,availability:n.availability?.convert()}}).filter(Lo)).filter(Lo)}:void 0,i=this.isNullable?BUi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var VOu=class extends pC{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var j$i=class extends pC{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(xv(r)){let n=_C(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(Lo),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var WIh=ce(ZS());function CdB(e){return aKc.includes(e)}var WOu=class extends pC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(CdB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${aKc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new WIh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var GOu=class extends pC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return BUi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var GIh=ce(ZS());function qdB(e){return nKc.includes(e)}var HOu=class extends pC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(qdB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${nKc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new GIh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var HIh=ce(ZS());function TdB(e){return oKc.includes(e)}var xOu=class extends pC{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new HIh.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(TdB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${oKc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new j$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var xIh=ce(ZS());var KOu=class extends pC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,xIh.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var Bvn=class extends oY{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=Hua(this.input);let t=_C(this.input,this.context.document);t?.enum!=null&&P$i(t)&&(this.maybeEnumConverterNode=new j$i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:oc.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=_C(this.input,this.context.document);if(r!=null)return new ew({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var ew=class e extends oY{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new ZEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),P$i(this.input)&&QIh(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),xv(this.input)){let t=Hua(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new Bvn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new FOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(FIh(this.input))this.typeShapeNode=new QOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(P$i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new LOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(lKc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new xua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(P$i(this.input)&&this.input.enum!=null)this.typeShapeNode=new j$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":lKc(this.input)&&(this.typeShapeNode=new xua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":m$i(this.input)&&(this.typeShapeNode=new NOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":zIh(this.input)&&(this.typeShapeNode=new VOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":NIh(this.input)&&(this.typeShapeNode=new WOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":LIh(this.input)&&(this.typeShapeNode=new HOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":VIh(this.input)&&(this.typeShapeNode=new xOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":UIh(this.input)&&(this.typeShapeNode=new GOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new KIh.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new xua({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new KOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!xv(this.input)&&(!m$i(this.input)&&this.input==null||m$i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=HP(t)?.map(i=>this.nullable?BUi(i):i).filter(Lo);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function w$i(e){if(e!=null)return Gua(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Lo))}var LYt=class extends pC{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;xv(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new ZEe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new ew({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=TIh(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function JIh(e,t){return xv(e)?pL(e,t,void 0):e}var fKc=ce(ZS());function JOu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[oc.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var $Ih=ce(y2s(),1),Kua=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,o){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=o}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=$Ih.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function RdB(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var $Ou=class extends ho{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new ew({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),RdB(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(xv(r)?n=aOu(r.$ref,this.context.document):n=r,n!=null)return[t,new Vua({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Lo)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[oc.api.latest.AuthSchemeId(t),i]}).filter(Lo)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=HP(r.convert());return n==null?[t,void 0]:[oc.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Lo(r))):void 0}}};var YOu=class extends ew{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=_C(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${xv(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=_C(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var XOu=class extends ho{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=_C(this.input.schema,this.context.document);this.availability=new ZEe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=xv(this.input.schema)?new Bvn({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=Kua.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new ew({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,o])=>{if(o!=null)return[a,new YOu({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Lo))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[yF]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[yF]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:HP(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=g8t([this.method,this.path,this.contentType,"request"].join("_"));return JOu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:oc.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new fKc.UnreachableCaseError(n);return}}).filter(Lo)}convert(){if(this.schema instanceof Bvn)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:oc.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:oc.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=HP(n.convert()),o=n.multipartType;return a?.map(c=>({type:o,key:oc.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new fKc.UnreachableCaseError(n.multipartType),[]}}).filter(Lo).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var ZOu=class extends ho{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=JIh(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new XOu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>HP(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Lo)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>HP(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Lo)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var YIh={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function XIh(e,t){if(xv(e)){let r=pL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var kOu=ce(ZS());var ZIh="application/json";var kIh="application/octet-stream";function eCh(e,t){return e===t||t===yF||e===yF}var GKa=class extends ho{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,o,c,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=o,this.requests=c,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,o]of Object.entries(n?.examples??{}))for(let[c,d]of Object.entries(r))for(let s of d)eCh(c,a)&&(i.add(c),this.examples?.push(new UYt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,O$i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[o,c]of r){if(a===i){let[d,s,u]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(l=>new UYt({input:{requestExample:u,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,O$i(s,o),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,o]=r[r.length-1]??[void 0,void 0],[c,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(o??[void 0]).map(u=>new UYt({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,O$i(d,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,o]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new UYt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,O$i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[yF];if(a!=null)for(let o of a)this.examples?.push(new UYt({input:{requestExample:n,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,O$i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=Kua.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=ZIh,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new ew({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=kIh,this.contentSubtype=_C(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new ew({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=wOu(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[yF]??=[],r[yF]=[{value:this.input.example}]);let i=_C(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=wOu(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[yF]??=[],r[yF]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[yF]??=[],r[yF]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([d])=>!n.has(d)&&d!==yF).map(([d,s])=>[c,d,s]));let o=Object.entries(r).filter(([c,d])=>!n.has(c)&&Lo(d)&&c!==yF);Object.keys(r).every(c=>c===yF)||this.matchExamplesByIndex(a,o),!n.has(yF)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return HP(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new kOu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return HP(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=g8t([this.method,this.path,this.statusCode,"response"].join("_"));return JOu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:oc.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new kOu.UnreachableCaseError(i);return}}).filter(Lo)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new kOu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var HKa=class extends ho{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,o){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=o,this.safeParse()}parse(t){this.description=this.input.description;let r=XIh(this.input,this.context.document);if(r==null){this.context.errors.error({message:xv(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new LYt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new GKa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new GKa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(Lo)}};var eAu=class extends ho{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new HKa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new HKa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return UOu(w$i(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(o=>(o.examples??[]).map(c=>c.convert()).filter(Lo))})))}).filter(Lo)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=HP(n?.convert());if(n!=null)return a?.map(o=>({statusCode:parseInt(t),shape:o,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??YIh[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let d=c.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(Lo)})).filter(Lo)})).filter(Lo)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var E$i=class extends ho{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new UYt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,O$i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new ZEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=v$i(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new ROu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(xv(i)){let a=BOu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new LYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new LYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new LYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new zOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new ZOu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new eAu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,o])=>{this.pushEmptyResponseExample(o,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new Wua({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new WKa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new WKa({input:{[rOu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new TOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>EOu({namespace:HP(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(Lo),this.xFernExamplesNode=new qOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(Lo)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:oc.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(u=>u.convert()).filter(Lo),n=EIh(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:wIh(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:oc.WebhookId(u),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[l]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(p=>p.value.toString())??[],queryParameters:w$i(this.queryParameters)?.flat(),headers:w$i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Lo)}}).filter(Lo);let a=this.servers?.map(u=>u.convert()).filter(Lo),o=this.convertPathToPathParts();if(o==null)return;let c,d=this.auth?.convert();d!=null&&(c=Object.keys(d));let s=t?.flatMap(u=>u.headers).filter(Lo);return this.endpointIds.map((u,l)=>({id:oc.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(p=>oc.api.v1.SubpackageId(p)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(p=>oc.api.latest.AuthSchemeId(p)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:w$i(this.pathParameters)?.flat(),queryParameters:w$i(this.queryParameters)?.flat(),requestHeaders:w$i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(p=>p.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var Jua=class extends ho{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=v$i(t,this.input.servers,this.context,this.accessPath),o=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new E$i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:o,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new E$i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:o,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new E$i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:o,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new E$i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:o,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new E$i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:o,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(Lo)}};function tAu(e){return"payloads"in e}var rAu=class extends ho{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new Jua({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:v$i(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Lo)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{tAu(a)?r[oc.WebhookId(a.id)]=a:t[oc.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var iAu=class extends ho{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[gBh]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||BOu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new LYt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return Gua(this.globalHeaders,this.requiredProperties)?.flat()}};function tCh(e,t){if(xv(e)){let r=pL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var nAu=class extends ho{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let o=tCh(a,this.context.document);if(o!=null)return new Jua({input:o,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Lo)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{tAu(i)&&(t[oc.WebhookId(i.id)]=i)}),t),{})}};var aAu=class extends ho{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=v$i(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new Wua({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new DOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new rAu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new nAu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new $Ou({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new iAu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=ave(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=hBh({endpoints:i,webhookEndpoints:n}),{types:o,auths:c}=this.components?.convert()??{};return{id:oc.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...o,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};async function dKc(e,t){if(e instanceof LEe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof sS))return;let r=new u8t(e.absoluteFilePath),i=await WEe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let o of n){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new eOu,generatedTypes:{}},d=new aAu({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=C2s(a,d.convert())}return a}var gLh=ce(hKc(),1),OLh=ce(KAu(),1),bPu=require("fs/promises"),ALh=ce(require("http"),1),mLh=ce(require("path"),1);var azh=require("events"),ZAu=ce(require("fs"),1),Uvn=ce(require("path"),1);var LRh=ce(require("os"),1),VRh=300,q$i=20,_Ja=1e7,WRh=LRh.default.platform();var iOB=WRh==="darwin",RJc=WRh==="win32",T$i=iOB||RJc,GRh=3e3,HRh=2e4,zJc=1250;var HYt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(HYt||(HYt={}));var Qvn;(function(e){e.CHANGE="change",e.RENAME="rename"})(Qvn||(Qvn={}));var hJa;(function(e){e.CHANGE="change",e.ERROR="error"})(hJa||(hJa={}));var tf;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(tf||(tf={}));var yH;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(yH||(yH={}));var nOB=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let g=Date.now(),m=g-d,j=g-s,M=m>=t||j>=a;return[g,M]},l=g=>{if(s=g,!o)return;let m=o;o=void 0,e.apply(void 0,m)},p=()=>{O(0)},_=()=>{c&&(p(),l(Date.now()))},h=g=>{if(s=g,i)return l(g)},y=g=>{if(n&&o)return l(g);o=void 0},b=()=>{c=void 0;let[g,m]=u();return m?y(g):v(g)},v=g=>{let m=g-d,j=g-s,M=t-m,w=a-j,D=Math.min(M,w);return O(D)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},A=(...g)=>{let[m,j]=u(),M=!!c;if(o=g,d=m,(j||!c)&&O(t),j)return M?l(m):h(m)};return A.cancel=p,A.flush=_,A},JAu=nOB;var UJc=ce(require("fs"),1),YAu=ce(require("path"),1);var iA=ce(require("fs"),1),_L=require("util");var CUi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},xYt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var NJc=ce(require("process"),1),xRh=NJc.default.getuid?!NJc.default.getuid():!1,KRh=1e4,lY=()=>{};var yJa={isChangeErrorOk:e=>{if(!yJa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!xRh&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!yJa.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!yJa.isNodeError(e))throw e;if(!yJa.isChangeErrorOk(e))throw e}},hC=yJa;var FJc=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=KRh,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},JRh=new FJc;var qUi=(e,t)=>function(i){return function n(...a){return JRh.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},TUi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var aOB={attempt:{chmod:CUi((0,_L.promisify)(iA.default.chmod),hC.onChangeError),chown:CUi((0,_L.promisify)(iA.default.chown),hC.onChangeError),close:CUi((0,_L.promisify)(iA.default.close),lY),fsync:CUi((0,_L.promisify)(iA.default.fsync),lY),mkdir:CUi((0,_L.promisify)(iA.default.mkdir),lY),realpath:CUi((0,_L.promisify)(iA.default.realpath),lY),stat:CUi((0,_L.promisify)(iA.default.stat),lY),unlink:CUi((0,_L.promisify)(iA.default.unlink),lY),chmodSync:xYt(iA.default.chmodSync,hC.onChangeError),chownSync:xYt(iA.default.chownSync,hC.onChangeError),closeSync:xYt(iA.default.closeSync,lY),existsSync:xYt(iA.default.existsSync,lY),fsyncSync:xYt(iA.default.fsync,lY),mkdirSync:xYt(iA.default.mkdirSync,lY),realpathSync:xYt(iA.default.realpathSync,lY),statSync:xYt(iA.default.statSync,lY),unlinkSync:xYt(iA.default.unlinkSync,lY)},retry:{close:qUi((0,_L.promisify)(iA.default.close),hC.isRetriableError),fsync:qUi((0,_L.promisify)(iA.default.fsync),hC.isRetriableError),open:qUi((0,_L.promisify)(iA.default.open),hC.isRetriableError),readFile:qUi((0,_L.promisify)(iA.default.readFile),hC.isRetriableError),rename:qUi((0,_L.promisify)(iA.default.rename),hC.isRetriableError),stat:qUi((0,_L.promisify)(iA.default.stat),hC.isRetriableError),write:qUi((0,_L.promisify)(iA.default.write),hC.isRetriableError),writeFile:qUi((0,_L.promisify)(iA.default.writeFile),hC.isRetriableError),closeSync:TUi(iA.default.closeSync,hC.isRetriableError),fsyncSync:TUi(iA.default.fsyncSync,hC.isRetriableError),openSync:TUi(iA.default.openSync,hC.isRetriableError),readFileSync:TUi(iA.default.readFileSync,hC.isRetriableError),renameSync:TUi(iA.default.renameSync,hC.isRetriableError),statSync:TUi(iA.default.statSync,hC.isRetriableError),writeSync:TUi(iA.default.writeSync,hC.isRetriableError),writeFileSync:TUi(iA.default.writeFileSync,hC.isRetriableError)}},$Rh=aOB;var $Au=ce(require("fs"),1),bJa=ce(require("path"),1);var QJc=()=>{};var oOB=()=>{let e=QJc,t=QJc,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},YRh=oOB;var uOB=()=>{let{promise:e,resolve:t,isPending:r}=YRh(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},XRh=uOB;var ZRh={then:e=>{e()}};var kRh=e=>Array.isArray(e)?e:[e],ezh=e=>typeof e=="function";var sOB=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=kRh(a).map(G=>ezh(G)?G:H=>G.test(H)),c=G=>o.some(H=>H(G)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],l=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,O={},A={},g=new Set,m={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:l,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:A},{promise:M,increment:w,decrement:D}=XRh(),B=0,R=(G,H,Ee,ue)=>{g.has(H)||B>=n||(B+=1,G.directories.push(H),G.directoriesNames.add(Ee),u.push(H),l.add(Ee),p.propertyIsEnumerable(Ee)||(p[Ee]=[]),p[Ee].push(H),g.add(H),!(ue>=i)&&(B>=n||ee(H,ue+1)))},N=(G,H,Ee)=>{g.has(H)||B>=n||(B+=1,G.files.push(H),G.filesNames.add(Ee),_.push(H),h.add(Ee),y.propertyIsEnumerable(Ee)||(y[Ee]=[]),y[Ee].push(H),g.add(H))},z=(G,H,Ee,ue)=>{g.has(H)||B>=n||(B+=1,G.symlinks.push(H),G.symlinksNames.add(Ee),b.push(H),v.add(Ee),O.propertyIsEnumerable(Ee)||(O[Ee]=[]),O[Ee].push(H),g.add(H),r&&(ue>=i||B>=n||Pe(H,ue+1)))},F=(G,H,Ee,ue,Oe)=>{d.aborted||c(H)||(ue.isDirectory()?R(G,H,Ee,Oe):ue.isFile()?N(G,H,Ee):ue.isSymbolicLink()&&z(G,H,Ee,Oe))},U=(G,H,Ee,ue)=>{if(d.aborted)return;let Oe=H===bJa.default.sep?"":bJa.default.sep,Qe=Ee.name,se=`${H}${Oe}${Qe}`;c(se)||(Ee.isDirectory()?R(G,se,Qe,ue):Ee.isFile()?N(G,se,Qe):Ee.isSymbolicLink()&&z(G,se,Qe,ue))},x=(G,H,Ee,ue)=>{for(let Oe=0,Qe=Ee.length;Oe<Qe;Oe++)U(G,H,Ee[Oe],ue)},ee=(G,H)=>{d.aborted||H>i||B>=n||(w(),$Au.default.readdir(G,{withFileTypes:!0},(Ee,ue)=>{if(Ee||d.aborted||!ue.length)return D();(s(ue)||ZRh).then(()=>{let Qe=A[G]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};x(Qe,G,ue,H),D()})}))},Pe=(G,H)=>{w(),$Au.default.realpath(G,(Ee,ue)=>{if(Ee||d.aborted)return D();$Au.default.stat(ue,(Oe,Qe)=>{if(Oe||d.aborted)return D();let se=bJa.default.basename(ue),ne=A[G]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};F(ne,ue,se,Qe,H),D()})})};return(async(G,H=1)=>(G=bJa.default.normalize(G),g.add(G),ee(G,H),await M,d.aborted?m:j))(e)},tzh=sOB;var KYt={lang:{debounce:JAu,attempt:e=>{try{return e()}catch(t){return KYt.lang.castError(t)}},castArray:e=>KYt.lang.isArray(e)?e:[e],castError:e=>KYt.lang.isError(e)?e:KYt.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(KYt.lang.isNaN(e))return KYt.lang.isNaN(t);if(KYt.lang.isPrimitive(e)||KYt.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(YAu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?UJc.default.realpathSync.native(e):UJc.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===YAu.default.sep&&t.length-e.length>YAu.default.sep.length,poll:(e,t=HRh)=>$Rh.retry.stat(t)(e,{bigint:!0}).catch(KYt.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await tzh(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Fp=KYt;var XAu=ce(require("path"),1);var LJc=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Fp.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=VRh){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),l=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(l)},o=Fp.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===tf.CHANGE&&c===tf.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===tf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===tf.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??q$i:Math.min(1,this.options.depth??q$i),o=this.options.limit??_Ja,[c,d]=await Fp.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())Fp.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(tf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!T$i&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(tf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(tf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(XAu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(tf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(XAu.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(tf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===tf.ADD?this.onTargetAdd(i):r===tf.ADD_DIR?this.onTargetAddDir(i):r===tf.CHANGE?this.onTargetChange(i):r===tf.UNLINK?this.onTargetUnlink(i):r===tf.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=Qvn.CHANGE,r){if(this.watcher.isClosed())return;let i=XAu.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){RJc&&t.code==="EPERM"?this.onWatcherChange(Qvn.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(hJa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(hJa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Qvn.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&T$i&&this.options.native!==!1?this.options.depth??q$i:Math.min(1,this.options.depth??q$i),i=this.options.limit??_Ja,[n,a]=await Fp.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(Qvn.CHANGE,c,t)}))}}},rzh=LJc;var bH={interval:100,intervalId:void 0,fns:new Map,init:()=>{bH.intervalId||(bH.intervalId=setInterval(bH.resolve,bH.interval))},reset:()=>{bH.intervalId&&(clearInterval(bH.intervalId),delete bH.intervalId)},add:(e,t)=>{bH.fns.set(e,Date.now()+t),bH.init()},remove:e=>{bH.fns.delete(e)},resolve:()=>{if(!bH.fns.size)return bH.reset();let e=Date.now();for(let[t,r]of bH.fns)r>=e||(bH.remove(t),t())}},vJa=bH;var gJa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=zJc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let l=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(l&&l!==n){if(Fp.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),vJa.remove(s)},s=()=>{d(),c()};vJa.add(s,r);let u=()=>{let l=o.unlink.get(i);if(!l)return;d();let p=l();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=zJc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),vJa.remove(s)},s=()=>{d(),c()};vJa.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,tf.ADD,HYt.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,tf.ADD_DIR,HYt.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,tf.UNLINK,HYt.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,tf.UNLINK_DIR,HYt.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};gJa.DIR_EVENTS={add:tf.ADD_DIR,rename:tf.RENAME_DIR,unlink:tf.UNLINK_DIR};gJa.FILE_EVENTS={add:tf.ADD,change:tf.CHANGE,rename:tf.RENAME,unlink:tf.UNLINK};var izh=gJa;var VJc=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Fp.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Fp.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(Fp.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(Fp.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Fp.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Fp.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},WJc=VJc;var GJc=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},nzh=GJc;var HJc=class{constructor(){this.inos={},this.paths=new WJc,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await Fp.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new nzh(i)}reset(){this.inos={},this.paths=new WJc,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,tf.ADD,n),[tf.ADD];if(n.isDirectory())return this.updateIno(t,tf.ADD_DIR,n),[tf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,tf.UNLINK,i),[tf.UNLINK];if(i.isDirectory())return this.updateIno(t,tf.UNLINK_DIR,i),[tf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,tf.CHANGE,n),[tf.CHANGE]);if(n.isDirectory())return this.updateIno(t,tf.UNLINK,i),this.updateIno(t,tf.ADD_DIR,n),[tf.UNLINK,tf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,tf.UNLINK_DIR,i),this.updateIno(t,tf.ADD,n),[tf.UNLINK_DIR,tf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,tf.UNLINK_DIR,i),this.updateIno(t,tf.ADD_DIR,n),[tf.UNLINK_DIR,tf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?HYt.FILE:HYt.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},xJc=HJc;var KJc=class e extends azh.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(yH.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(yH.CLOSE,n)),this._readyWait=new Promise(n=>this.on(yH.READY,n)),this._locker=new izh(this),this._roots=new Set,this._poller=new xJc,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Fp.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(yH.CLOSE))}error(t){if(this.isClosed())return!1;let r=Fp.lang.castError(t);return this.emit(yH.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(yH.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(yH.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Fp.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Fp.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)Fp.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new rzh(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Fp.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=Uvn.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??q$i))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&T$i&&u.options.native!==!1)))return!0;if(!T$i)break;let s=Uvn.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Fp.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||T$i&&r.native!==!1?r:{...r,recursive:!1},u={watcher:ZAu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},l=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=Uvn.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,l)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||T$i&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??q$i,c=r.limit??_Ja,[d]=await Fp.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=Fp.fs.getDepth(t);for(let l of d){let p=Fp.fs.getDepth(l),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([l],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(yH.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(yH.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=Uvn.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new xJc,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return Fp.lang.noop;if(this.pollerExists(t,r))return Fp.lang.noop;let n={...r,interval:r.pollingInterval??GRh},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(yH.CLOSE,c),ZAu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(yH.CLOSE,c),ZAu.default.unwatchFile(t,i)};return Fp.lang.attempt(o),()=>Fp.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=Fp.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Fp.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=Uvn.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Fp.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=Uvn.default.dirname(t);return(await Fp.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Fp.lang.noop){if(Fp.lang.isFunction(t))return this.watch([],{},t);if(Fp.lang.isUndefined(t))return this.watch([],r,i);if(Fp.lang.isFunction(r))return this.watch(t,{},r);if(Fp.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Fp.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Fp.lang.noop&&this.on(yH.ALL,i),r.readdirMap=void 0,this.ready())}},kAu=KJc;zXo();var lsa=require("fs/promises"),ozh=require("os"),uzh=ce(require("path"),1),cOB=".fern",lOB="logs";function fOB(){return"cli@3.31.0"}var OJa=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Ct(Cr.of((0,ozh.homedir)()),Ze.of(cOB)),r=Ct(t,Ze.of(lOB));await ji(r)||await(0,lsa.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Ct(r,Ze.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${uzh.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
1784
|
+
https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`;throw new Error(r)}async toRootNode(){let t=Rt.V1.SlugGenerator.init(Rt.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Rt.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return Tln(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Rt.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??KE(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,o=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:o}}async toVersionedNode(t,r){let i=this.#e.get("versioned"),n=t.versions[0];if(n?.hidden===!0)throw new Error(`The default version "${n.version}" cannot be hidden. Please set a non-hidden version as the first version in your versions list, or remove the hidden flag from the default version.`);return{id:i,type:"versioned",children:await Promise.all(t.versions.map((a,o)=>this.toVersionNode(a,r,o===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(o=>this.toProductNode(o,i)))}}async toProductNode(t,r){if(t.type==="internal"){let i=r.setProductSlug(t.slug??KE(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:gt(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Rt.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}else return{type:"productLink",id:this.#e.get(t.product),productId:Rt.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",href:yG.Url(t.href??""),target:t.target,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,viewers:t.viewers,orphaned:t.orphaned}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??KE(t.version)),o=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Rt.VersionId(t.version),title:t.version,slug:a.get(),child:o,default:i,availability:t.availability!=null?odB(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(c=>this.toNavigationChild({prefix:n,item:c,parentSlug:i}))),o=[];return a.forEach(c=>{if(c.type==="apiReference"){o.push(c);return}if(c.type==="section"&&!c.collapsed){o.push(c);return}let d=o.length>0?o[o.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},o.push(s)),s.children.push(c)}),{type:"sidebarRoot",id:n,children:o}}async toSidebarRootNodeWithVariants(t,r,i){let n=this.#e.get(`${t}/root`);return{type:"sidebarRoot",id:n,children:[{type:"varianted",id:n,children:await Promise.all(r.map(a=>this.toVariantNode(a,n,i)))}]}}async toVariantNode(t,r,i){let n=this.#e.get(`${r}/variant/${t.slug??KE(t.title)}`),a=i.apply({urlSlug:t.slug??KE(t.title),skipUrlSlug:t.skipUrlSlug}),o=await Promise.all(t.layout.map(c=>this.toVariantChild(c,n,a)));return{type:"variant",id:n,variantId:Rt.V1.VariantId(t.title),subtitle:t.subtitle??"",default:t.default??!1,image:void 0,children:o,title:t.title,slug:a.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,pointsTo:void 0}}async toVariantChild(t,r,i){return Tln(t)._visit({page:async n=>this.toPageNode({item:n,parentSlug:i}),apiSection:async n=>this.toApiSectionNode({item:n,parentSlug:i}),section:async n=>this.toSectionNode({prefix:r,item:n,parentSlug:i}),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i)})}async toNavigationChild({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){return Tln(r)._visit({page:async o=>this.toPageNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),apiSection:async o=>this.toApiSectionNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),section:async o=>this.toSectionNode({prefix:t,item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),link:async o=>this.toLinkNode(o),changelog:async o=>this.toChangelogNode(o,i,n)})}async toApiSectionNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=CMh(t.snippetsConfiguration),o,c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),d=this.parsedDocsConfig.experimental?.openapiParserV3,s=d==null||d;if(s)try{o=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1})}catch{}let u;if(t.tagDescriptionPages&&s)try{let b=await this.getOpenApiWorkspaceForApiSection(t).getOpenAPIIr({context:this.taskContext});b.tags.tagsById&&(u=Object.fromEntries(Object.entries(b.tags.tagsById).filter(([v,O])=>O.description&&O.description.trim().length>0).map(([v,O])=>[v,{id:String(O.id),description:O.description}])))}catch(y){this.taskContext.logger.warn("Failed to extract OpenAPI tags for tag description pages",String(y))}o==null&&(o=lS({workspace:c,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new cS(this.taskContext,c)})),this.docsWorkspace.config.settings?.substituteEnvVars&&(o=FT(o,{onError:y=>this.taskContext.failAndThrow(`Error substituting environment variables in API spec: ${y}`)},{substituteAsEmpty:!1}));let l=await this.registerApi({ir:o,snippetsConfig:a,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName,workspace:c}),p=UKa({ir:o,apiDefinitionId:l,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext}),_=new Hgu(t,p,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,this.collectedFileIds,c,i,n??t.availability,u),h=_.getTagDescriptionContent();for(let[y,b]of h.entries()){let v=y.split("/").pop()||y,O=Ze.of(v),A=b;this.docsWorkspace.config.settings?.substituteEnvVars&&(A=FT(b,{onError:g=>this.taskContext.logger.error(`Error in tag description environment variable substitution: ${g}`)},{substituteAsEmpty:!1})),this.rawMarkdownFiles[O]=A,this.parsedDocsConfig.pages[O]=A}return _.get()}async toChangelogNode(t,r,i){return new Mvn(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Rt.V1.Url(t.url),icon:this.resolveIconFileId(t.icon),target:t.target}}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Rt.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??KE(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Rt.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??KE(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,l=n||r.hidden;return{id:d,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:l,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(p=>this.toNavigationChild({prefix:d,item:p,parentSlug:s,hideChildren:l,parentAvailability:r.availability??a}))),authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return Tln(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new Mvn(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Rt.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??KE(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??KE(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):yG.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(As),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:yG.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return Tln(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:yG.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function adB(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${mR(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function odB(e){switch(e){case"beta":return Rt.V1.NavigationV1Availability.Beta;case"deprecated":return Rt.V1.NavigationV1Availability.Deprecated;case"ga":return Rt.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Rt.V1.NavigationV1Availability.Stable;default:gt(e)}}async function dL(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof sS?t:null))).filter(As)}async function jxc(e,t,r){if(e instanceof LEe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof sS))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});return pH({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:{oauth:!0},context:t})}var oc={};Zt(oc,{AlgoliaSearchIndex:()=>ZMh,ApiDefinitionId:()=>gDh,ApiId:()=>PDh,Availability:()=>FDh,DocsConfigId:()=>jDh,EndpointId:()=>EDh,EndpointPathLiteral:()=>zDh,EnvironmentId:()=>wDh,FileId:()=>IDh,HttpMethod:()=>NDh,IndexSegmentId:()=>kMh,JqString:()=>qDh,OrgId:()=>ADh,PageId:()=>BDh,PayloadLocation:()=>fBh,PropertyKey:()=>TDh,PullRequestState:()=>oBh,RoleId:()=>RDh,TokenId:()=>mDh,TypeId:()=>DDh,Url:()=>CDh,VersionId:()=>ODh,WebSocketId:()=>SDh,WebhookId:()=>MDh,algolia:()=>wxc,api:()=>Rxc,commons:()=>zxc,diff:()=>QDh,docs:()=>Hxc,generators:()=>Kxc,git:()=>Jxc,navigation:()=>Xxc,sdks:()=>kxc,snippets:()=>cBh,snippetsFactory:()=>lBh,templates:()=>eKc,tokens:()=>dBh});var wxc={};Zt(wxc,{AlgoliaSearchIndex:()=>ZMh,IndexSegmentId:()=>kMh});function ZMh(e){return e}function kMh(e){return e}var Rxc={};Zt(Rxc,{latest:()=>Mxc,v1:()=>Txc});var Mxc={};Zt(Mxc,{AuthSchemeId:()=>eDh,WebhookHttpMethod:()=>nDh,auth:()=>Exc,commons:()=>tDh,endpoint:()=>rDh,type_:()=>iDh,webhook:()=>Sxc,websocket:()=>aDh});var Exc={};Zt(Exc,{AuthSchemeId:()=>eDh});function eDh(e){return e}var tDh={};var rDh={};var iDh={};var Sxc={};Zt(Sxc,{WebhookHttpMethod:()=>nDh});var nDh={Get:"GET",Post:"POST"};var aDh={};var Txc={};Zt(Txc,{SubpackageId:()=>hDh,WebSocketMessageId:()=>yDh,WebSocketMessageOrigin:()=>bDh,WebhookHttpMethod:()=>vDh,commons:()=>qxc,db:()=>Dxc,read:()=>Ixc,register:()=>Cxc});var Dxc={};Zt(Dxc,{endpoint:()=>oDh});var oDh={};var Ixc={};Zt(Ixc,{SupportedLanguage:()=>uDh,endpoint:()=>Bxc,type_:()=>sDh,webhook:()=>cDh,websocket:()=>lDh});var Bxc={};Zt(Bxc,{SupportedLanguage:()=>uDh});var uDh={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var sDh={};var cDh={};var lDh={};var Cxc={};Zt(Cxc,{SourceId:()=>udB,endpoint:()=>fDh,type_:()=>dDh,webhook:()=>pDh,websocket:()=>_Dh});var fDh={};var dDh={};var pDh={};var _Dh={};function udB(e){return e}var qxc={};Zt(qxc,{SubpackageId:()=>hDh,WebSocketMessageId:()=>yDh,WebSocketMessageOrigin:()=>bDh,WebhookHttpMethod:()=>vDh});function hDh(e){return e}function yDh(e){return e}var bDh={Client:"client",Server:"server"};var vDh={Get:"GET",Post:"POST"};var zxc={};Zt(zxc,{ApiDefinitionId:()=>gDh,ApiId:()=>PDh,Availability:()=>FDh,DocsConfigId:()=>jDh,EndpointId:()=>EDh,EndpointPathLiteral:()=>zDh,EnvironmentId:()=>wDh,FileId:()=>IDh,HttpMethod:()=>NDh,JqString:()=>qDh,OrgId:()=>ADh,PageId:()=>BDh,PropertyKey:()=>TDh,RoleId:()=>RDh,TokenId:()=>mDh,TypeId:()=>DDh,Url:()=>CDh,VersionId:()=>ODh,WebSocketId:()=>SDh,WebhookId:()=>MDh});function gDh(e){return e}function ODh(e){return e}function ADh(e){return e}function mDh(e){return e}function PDh(e){return e}function jDh(e){return e}function wDh(e){return e}function EDh(e){return e}function SDh(e){return e}function MDh(e){return e}function DDh(e){return e}function BDh(e){return e}function IDh(e){return e}function CDh(e){return e}function qDh(e){return e}function TDh(e){return e}function RDh(e){return e}function zDh(e){return e}var NDh={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var FDh={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var QDh={};var Hxc={};Zt(Hxc,{latest:()=>Qxc,v1:()=>Wxc,v2:()=>Gxc});var Qxc={};Zt(Qxc,{Layout:()=>LDh,MdxEngine:()=>sdB,TwitterCardSetting:()=>VDh,commons:()=>UDh,frontmatter:()=>Nxc,seo:()=>Fxc});var sdB={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var UDh={};var Nxc={};Zt(Nxc,{Layout:()=>LDh});var LDh={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var Fxc={};Zt(Fxc,{TwitterCardSetting:()=>VDh});var VDh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Wxc={};Zt(Wxc,{commons:()=>Vxc,db:()=>WDh,read:()=>GDh,write:()=>Uxc});var WDh={};var GDh={};var Uxc={};Zt(Uxc,{DocsRegistrationId:()=>ldB,FilePath:()=>cdB});function cdB(e){return e}function ldB(e){return e}var Vxc={};Zt(Vxc,{ContentAlignment:()=>JDh,FontDisplay:()=>kDh,FontStyle:()=>ZDh,HeaderPosition:()=>$Dh,JsScriptStrategy:()=>XDh,ProgrammingLanguage:()=>HDh,SearchbarPlacement:()=>xDh,TabsPlacement:()=>KDh,TwitterCardSetting:()=>YDh,commons:()=>Lxc});var Lxc={};Zt(Lxc,{ContentAlignment:()=>JDh,FontDisplay:()=>kDh,FontStyle:()=>ZDh,HeaderPosition:()=>$Dh,JsScriptStrategy:()=>XDh,ProgrammingLanguage:()=>HDh,SearchbarPlacement:()=>xDh,TabsPlacement:()=>KDh,TwitterCardSetting:()=>YDh});var HDh={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var xDh={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var KDh={Header:"HEADER",Sidebar:"SIDEBAR"};var JDh={Center:"CENTER",Left:"LEFT"};var $Dh={Fixed:"FIXED",Absolute:"ABSOLUTE"};var YDh={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var XDh={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var ZDh={Normal:"normal",Italic:"italic"};var kDh={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var Gxc={};Zt(Gxc,{read:()=>eBh,write:()=>tBh});var eBh={};var tBh={};var Kxc={};Zt(Kxc,{ChangelogEntryType:()=>iBh,GeneratorId:()=>fdB,GeneratorLanguage:()=>ddB,ReleaseType:()=>nBh,cli:()=>rBh,commons:()=>xxc,versions:()=>aBh});var rBh={};var xxc={};Zt(xxc,{ChangelogEntryType:()=>iBh,ReleaseType:()=>nBh});var iBh={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var nBh={Ga:"GA",Rc:"RC"};var aBh={};function fdB(e){return e}var ddB={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var Jxc={};Zt(Jxc,{PullRequestState:()=>oBh});var oBh={Open:"open",Closed:"closed",Merged:"merged"};var Xxc={};Zt(Xxc,{latest:()=>$xc,v1:()=>Yxc});var $xc={};Zt($xc,{NodeId:()=>hdB,ProductId:()=>ydB,Slug:()=>pdB,TabId:()=>_dB});function pdB(e){return e}function _dB(e){return e}function hdB(e){return e}function ydB(e){return e}var Yxc={};Zt(Yxc,{NavigationV1Availability:()=>AdB,NodeId:()=>gdB,ProductId:()=>OdB,Slug:()=>bdB,TabId:()=>vdB});function bdB(e){return e}function vdB(e){return e}function gdB(e){return e}function OdB(e){return e}var AdB={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var kxc={};Zt(kxc,{Language:()=>uBh,VersionBump:()=>sBh,versions:()=>Zxc});var Zxc={};Zt(Zxc,{Language:()=>uBh,VersionBump:()=>sBh});var uBh={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var sBh={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var cBh={};var lBh={};var eKc={};Zt(eKc,{PayloadLocation:()=>fBh});var fBh={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var dBh={};var eOu=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Lo(e){return e!=null}var _Bh=ce(eQa(),1);var pBh=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function QYt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,_Bh.default)(e,{special:pBh}).replace(/V\s(\d)/g,"V$1")}function hBh({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let o=[...n,a],c=oc.api.v1.SubpackageId(o.join("."));r[c]={id:c,name:a,displayName:QYt(a)},n.push(a)})}),r}var tOu=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function yBh(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var ho=class extends tOu{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((o,c)=>o===this.accessPath[this.accessPath.length-a.length+c])||this.accessPath.push(...a)}r.logger.debug(`Processing ${yBh(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},pC=class extends ho{},oY=class extends pC{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var bBh="x-fern-base-path",vBh="x-fern-availability",rOu="x-fern-sdk-group-name",gBh="x-fern-global-headers",OBh="x-fern-sdk-method-name";var ABh="x-fern-webhook",mBh="x-fern-access-token-locator",PBh="x-fern-basic",jBh="x-fern-username-variable-name",wBh="x-fern-password-variable-name",EBh="x-fern-bearer",SBh="x-fern-token-variable-name",MBh="x-fern-header",DBh="x-fern-header-variable-name",BBh="x-fern-server-name",IBh="x-fern-examples";var iOu=class extends ho{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[BBh]}convert(){if(this.serverName!=null)return this.serverName}};var nOu=class extends ho{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new iOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:oc.EnvironmentId(t),baseUrl:this.url}}};function v$i(e,t,r,i){let n=e??[],a=new Set(n.map(c=>c.url)),o=(t??[]).filter(c=>!a.has(c.url)).map((c,d)=>new nOu({input:c,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...o]}function xv(e){return typeof e=="object"&&Lo(e)&&"$ref"in e&&typeof e.$ref=="string"}function pL(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(xv(n)&&(n=pL(n,t,r)),n)}function aOu(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return xv(r)?pL(r,t,void 0):r}var mIh=ce(ZS());var oOu=class extends ho{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[PBh];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var uOu=class extends ho{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[wBh]}convert(){return this.passwordVariableName}};var sOu=class extends ho{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[jBh]}convert(){return this.usernameVariableName}};var cOu=class extends ho{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[EBh];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var lOu=class extends ho{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[SBh]}convert(){return this.tokenVariableName}};function CBh(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var qBh="x-bearer-format",TBh="x-code-samples",RBh="x-codeSamples";var fOu=class extends ho{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[qBh]}convert(){return this.bearerFormat}};var dOu=class extends ho{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[MBh];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var pOu=class extends ho{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[DBh]}convert(){return this.headerVariableName}};function zBh(e){return e.type==="apiKey"}var Uua=class extends ho{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){zBh(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new dOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new pOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new fOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function _Ou(e){return e}function hOu(e){return e==="__proto__"}function yOu(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function Lua(e){return typeof e=="string"||typeof e=="symbol"?e:Object.is(e?.valueOf?.(),-0)?"-0":String(e)}function LKa(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(LKa).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function bOu(e){if(Array.isArray(e))return e.map(Lua);if(typeof e=="symbol")return[e];e=LKa(e);let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",o=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let c=e[i];a?c==="\\"&&i+1<r?(i++,n+=e[i]):c===a?a="":n+=c:o?c==='"'||c==="'"?a=c:c==="]"?(o=!1,t.push(n),n=""):n+=c:c==="["?(o=!0,n&&(t.push(n),n="")):c==="."?n&&(t.push(n),n=""):n+=c,i++}return n&&t.push(n),t}function VKa(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(hOu(t))return r;let i=e[t];return i===void 0?yOu(t)?VKa(e,bOu(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=Lua(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return mdB(e,t,r);if(Object.is(t?.valueOf(),-0)?t="-0":t=String(t),hOu(t))return r;let i=e[t];return i===void 0?r:i}}}function mdB(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null||hOu(t[n]))return r;i=i[t[n]]}return i===void 0?r:i}function NBh(e){return function(t){return VKa(t,e)}}function FBh(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function vOu(e){return e==null||typeof e!="object"&&typeof e!="function"}function tKc(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function iKc(e,t,r){return typeof r!="function"?iKc(e,t,()=>{}):rKc(e,t,function i(n,a,o,c,d,s){let u=r(n,a,o,c,d,s);return u!==void 0?!!u:rKc(n,a,i,s)},new Map)}function rKc(e,t,r,i){if(t===e)return!0;switch(typeof t){case"object":return PdB(e,t,r,i);case"function":return Object.keys(t).length>0?rKc(e,{...t},r,i):tKc(e,t);default:return FBh(e)?typeof t=="string"?t==="":!0:tKc(e,t)}}function PdB(e,t,r,i){if(t==null)return!0;if(Array.isArray(t))return QBh(e,t,r,i);if(t instanceof Map)return jdB(e,t,r,i);if(t instanceof Set)return wdB(e,t,r,i);let n=Object.keys(t);if(e==null)return n.length===0;if(n.length===0)return!0;if(i?.has(t))return i.get(t)===e;i?.set(t,e);try{for(let a=0;a<n.length;a++){let o=n[a];if(!vOu(e)&&!(o in e)||t[o]===void 0&&e[o]!==void 0||t[o]===null&&e[o]!==null||!r(e[o],t[o],o,e,t,i))return!1}return!0}finally{i?.delete(t)}}function jdB(e,t,r,i){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[n,a]of t.entries()){let o=e.get(n);if(r(o,a,n,e,t,i)===!1)return!1}return!0}function QBh(e,t,r,i){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let n=new Set;for(let a=0;a<t.length;a++){let o=t[a],c=!1;for(let d=0;d<e.length;d++){if(n.has(d))continue;let s=e[d],u=!1;if(r(s,o,a,e,t,i)&&(u=!0),u){n.add(d),c=!0;break}}if(!c)return!1}return!0}function wdB(e,t,r,i){return t.size===0?!0:e instanceof Set?QBh([...e],[...t],r,i):!1}function gOu(e,t){return iKc(e,t,()=>{})}function UBh(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function OOu(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}var LBh="[object RegExp]",AOu="[object String]",mOu="[object Number]",POu="[object Boolean]",jOu="[object Arguments]",VBh="[object Symbol]",WBh="[object Date]",GBh="[object Map]",HBh="[object Set]",xBh="[object Array]";var KBh="[object ArrayBuffer]",JBh="[object Object]";var $Bh="[object DataView]",YBh="[object Uint8Array]",XBh="[object Uint8ClampedArray]",ZBh="[object Uint16Array]",kBh="[object Uint32Array]";var eIh="[object Int8Array]",tIh="[object Int16Array]",rIh="[object Int32Array]";var iIh="[object Float32Array]",nIh="[object Float64Array]";function aIh(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function oIh(e,t){return g$i(e,void 0,e,new Map,t)}function g$i(e,t,r,i=new Map,n=void 0){let a=n?.(e,t,r,i);if(a!==void 0)return a;if(vOu(e))return e;if(i.has(e))return i.get(e);if(Array.isArray(e)){let o=new Array(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=g$i(e[c],c,r,i,n);return Object.hasOwn(e,"index")&&(o.index=e.index),Object.hasOwn(e,"input")&&(o.input=e.input),o}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){let o=new RegExp(e.source,e.flags);return o.lastIndex=e.lastIndex,o}if(e instanceof Map){let o=new Map;i.set(e,o);for(let[c,d]of e)o.set(c,g$i(d,c,r,i,n));return o}if(e instanceof Set){let o=new Set;i.set(e,o);for(let c of e)o.add(g$i(c,void 0,r,i,n));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(aIh(e)){let o=new(Object.getPrototypeOf(e)).constructor(e.length);i.set(e,o);for(let c=0;c<e.length;c++)o[c]=g$i(e[c],c,r,i,n);return o}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){let o=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return i.set(e,o),v8t(o,e,r,i,n),o}if(typeof File<"u"&&e instanceof File){let o=new File([e],e.name,{type:e.type});return i.set(e,o),v8t(o,e,r,i,n),o}if(typeof Blob<"u"&&e instanceof Blob){let o=new Blob([e],{type:e.type});return i.set(e,o),v8t(o,e,r,i,n),o}if(e instanceof Error){let o=new e.constructor;return i.set(e,o),o.message=e.message,o.name=e.name,o.stack=e.stack,o.cause=e.cause,v8t(o,e,r,i,n),o}if(e instanceof Boolean){let o=new Boolean(e.valueOf());return i.set(e,o),v8t(o,e,r,i,n),o}if(e instanceof Number){let o=new Number(e.valueOf());return i.set(e,o),v8t(o,e,r,i,n),o}if(e instanceof String){let o=new String(e.valueOf());return i.set(e,o),v8t(o,e,r,i,n),o}if(typeof e=="object"&&EdB(e)){let o=Object.create(Object.getPrototypeOf(e));return i.set(e,o),v8t(o,e,r,i,n),o}return e}function v8t(e,t,r=e,i,n){let a=[...Object.keys(t),...UBh(t)];for(let o=0;o<a.length;o++){let c=a[o],d=Object.getOwnPropertyDescriptor(e,c);(d==null||d.writable)&&(e[c]=g$i(t[c],c,r,i,n))}}function EdB(e){switch(OOu(e)){case jOu:case xBh:case KBh:case $Bh:case POu:case WBh:case iIh:case nIh:case eIh:case tIh:case rIh:case GBh:case mOu:case JBh:case LBh:case HBh:case AOu:case VBh:case YBh:case XBh:case ZBh:case kBh:return!0;default:return!1}}function uIh(e){return g$i(e,void 0,e,new Map,void 0)}function sIh(e){return e=uIh(e),t=>gOu(t,e)}function cIh(e,t){return oIh(e,(r,i,n,a)=>{let o=t?.(r,i,n,a);if(o!==void 0)return o;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case mOu:case AOu:case POu:{let c=new e.constructor(e?.valueOf());return v8t(c,e),c}case jOu:{let c={};return v8t(c,e),c.length=e.length,c[Symbol.iterator]=e[Symbol.iterator],c}default:return}})}function lIh(e){return cIh(e)}var SdB=/^(?:0|[1-9]\d*)$/;function fIh(e,t=Number.MAX_SAFE_INTEGER){switch(typeof e){case"number":return Number.isInteger(e)&&e>=0&&e<t;case"symbol":return!1;case"string":return SdB.test(e)}}function dIh(e){return e!==null&&typeof e=="object"&&OOu(e)==="[object Arguments]"}function pIh(e,t){let r;if(Array.isArray(t)?r=t:typeof t=="string"&&yOu(t)&&e?.[t]==null?r=bOu(t):r=[t],r.length===0)return!1;let i=e;for(let n=0;n<r.length;n++){let a=r[n];if((i==null||!Object.hasOwn(i,a))&&!((Array.isArray(i)||dIh(i))&&fIh(a)&&a<i.length))return!1;i=i[a]}return!0}function _Ih(e,t){switch(typeof e){case"object":{Object.is(e?.valueOf(),-0)&&(e="-0");break}case"number":{e=Lua(e);break}}return t=lIh(t),function(r){let i=VKa(r,e);return i===void 0?pIh(r,e):t===void 0?i===void 0:gOu(i,t)}}function hIh(e){if(e==null)return _Ou;switch(typeof e){case"function":return e;case"object":return Array.isArray(e)&&e.length===2?_Ih(e[0],e[1]):sIh(e);case"string":case"symbol":case"number":return NBh(e)}}function yIh(e,t){let r={},i=Object.keys(e);for(let n=0;n<i.length;n++){let a=i[n],o=e[a];r[a]=t(o,a,e)}return r}function wOu(e,t=_Ou){return e==null?{}:yIh(e,hIh(t))}function bIh(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var MdB=new RegExp("\\p{Lu}?\\p{Ll}+|[0-9]+|\\p{Lu}+(?!\\p{Ll})|\\p{Emoji_Presentation}|\\p{Extended_Pictographic}|\\p{L}+","gu");function vIh(e){return Array.from(e.match(MdB)??[])}function gIh(e){let t=vIh(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>bIh(n)).join("")}`}function OIh(e){return typeof e!="string"&&(e=LKa(e)),e.replace(/['\u2019]/g,"")}function g8t(e){return gIh(OIh(e))}function HP(e){if(e!=null)return Array.isArray(e)?e:[e]}function EOu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:o}){if(t==null)return;let c=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&c==null))return`${DdB(o)}${BdB(e)}.${IdB(i,n,a,c)}`}function DdB(e){return e?"webhook_":"endpoint_"}function BdB(e){return e!=null?HP(e)?.map(t=>g8t(t)).join("/"):""}function IdB(e,t,r,i){return e||t||g8t(r??"")||g8t(i??"")}function AIh(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var SOu=class extends ho{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[mBh],this.accessTokenLocator!=null&&(AIh(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var MOu=class extends ho{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new Uua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new SOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=EOu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:oc.EndpointId(r),accessTokenLocator:oc.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var Vua=class extends ho{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new oOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new sOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new uOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new cOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new lOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{CBh(this.input)?(this.authScheme="header",this.headerAuthNode=new Uua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new MOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new mIh.UnreachableCaseError(this.authScheme);return}}};var Wua=class extends ho{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=aOu(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new Vua({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(Lo))}};var DOu=class extends ho{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[bBh],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function PIh(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function jIh(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function Gua(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>HP(n.convert())?.map(o=>((t!=null&&!t.includes(i)||t==null&&!PIh(n))&&(o=jIh(o,o.type==="enum"?o.default:void 0)),{key:oc.PropertyKey(i),valueShape:o,description:n.description,availability:n.availability?.convert()})).filter(Lo)).filter(Lo).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]])}function BOu(e,t){return xv(e)?pL(e,t,void 0):e}function O$i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function wIh(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function EIh(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var SIh=ce(ZS());var nKc=["decimal","decimal128","double-int","double","float","sf-decimal"],aKc=["int16","int32","int64","int8","sf-integer","uint8"],oKc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],uKc=["beta","pre-release","in-development","generally-available","deprecated"];function _C(e,t){return xv(e)?pL(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var ZEe=class extends ho{availability;constructor(t){super(t),this.safeParse()}parse(){if(_C(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[vBh];r!=null&&(uKc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${uKc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return oc.Availability.Beta;case"in-development":return oc.Availability.InDevelopment;case"generally-available":return oc.Availability.GenerallyAvailable;case"deprecated":return oc.Availability.Deprecated;case void 0:return;default:new SIh.UnreachableCaseError(this.availability);return}}};var COu=ce(ZS());function MIh(e){return typeof e=="object"&&e!=null&&"language"in e}function DIh(e){return typeof e=="object"&&e!=null&&"sdk"in e}function BIh(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function IIh(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function IOu(e){return typeof e=="object"&&e!=null&&"event"in e}function sKc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(IOu)}function A$i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function CIh(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var qOu=class extends ho{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[IBh]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let o=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return A$i(o)?[n,{type:"filenameWithData",filename:o.filename,data:oc.FileId(o.data)}]:o!=null?[n,{type:"filename",value:o}]:void 0;case"files":{if(Array.isArray(o)){if(o.every(c=>A$i(c)))return[n,{type:"filenamesWithData",value:o.map(c=>({filename:c.filename,data:oc.FileId(c.data)}))}];if(o.every(c=>typeof c=="string"))return[n,{type:"filenames",value:o}]}return}case"property":return[n,{type:"json",value:o}];case void 0:return;default:new COu.UnreachableCaseError(a.multipartType);return}}).filter(Lo))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=CIh(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new COu.UnreachableCaseError(n.contentType);break}let o;switch(i.contentType){case"application/json":{BIh(r.response)&&(o={type:"json",value:r.response.body});break}case"text/event-stream":{sKc(r.response)&&(o={type:"sse",value:r.response.stream.map(l=>({event:l.event,data:l.data}))});break}case"application/octet-stream":!sKc(r.response)&&IIh(r.response)&&(o={type:"stream",value:r.response.stream});break;case void 0:break;default:new COu.UnreachableCaseError(i.contentType);break}let c={};r["code-samples"]?.forEach(l=>{MIh(l)?l.language!=null&&(c[l.language]??=[],c[l.language]?.push({name:l.name,language:l.language,install:l.install,code:l.code,generated:!1,description:l.docs})):DIh(l)&&l.sdk!=null&&(c[l.sdk]??=[],c[l.sdk]?.push({name:l.name,language:l.sdk,install:void 0,code:l.code,generated:!1,description:l.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([l,p])=>[oc.PropertyKey(l),p])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([l,p])=>[oc.PropertyKey(l),p])),u=Object.fromEntries(Object.entries(r.headers??{}).map(([l,p])=>[oc.PropertyKey(l),p]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(u).length>0?u:void 0,requestBody:a,responseBody:o,snippets:c}}))}};var WKa=class extends ho{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[rOu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>oc.api.v1.SubpackageId(g8t(r)))}};var TOu=class extends ho{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[OBh]}convert(){return this.sdkMethodName}};var ROu=class extends ho{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[ABh]}convert(){return this.isWebhook}};var zOu=class extends ho{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[TBh]??[],...this.input[RBh]??[]],this.codeSamples.forEach(t=>{[...Object.values(oc.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var Dvn=ce(ZS());function cKc(e,t){return xv(e)?pL(e,t,void 0):e}function qIh(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var yF="",UYt=class extends ho{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(A$i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>A$i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new Dvn.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=cKc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=cKc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new Dvn.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(IOu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new Dvn.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return A$i(n)?[r,{type:"filenameWithData",filename:n.filename,data:oc.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>A$i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:oc.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new Dvn.UnreachableCaseError(i.multipartType);return}}).filter(Lo))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new Dvn.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new Dvn.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([o,c])=>[o,c.example({includeOptionals:!1,override:o})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(Lo));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([o,c])=>c.required||c.inputExample!=null?[o,c.example({includeOptionals:!1,override:o})]:void 0).filter(Lo));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:qIh(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?QYt(this.name):this.summary!=null?QYt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function TIh(e,t){return xv(e)?pL(e,t,void 0):e}var KIh=ce(ZS());var RIh="#/components/schemas/";function Hua(e){if(e.$ref.startsWith(RIh))return e.$ref.replace(RIh,"")}function BUi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function m$i(e){return typeof e.type=="string"&&e.type==="array"}function zIh(e){return e.type==="boolean"}function NIh(e){return e.type==="integer"}function P$i(e){return!Array.isArray(e.type)&&!m$i(e)}function FIh(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||P$i(t)||m$i(t))}function QIh(e){return"nullable"in e&&typeof e.nullable=="boolean"}function UIh(e){return e.type==="null"}function LIh(e){return e.type==="number"}function lKc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function VIh(e){return e.type==="string"}var NOu=class extends oY{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new ew({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return HP(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var FOu=class extends pC{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new ZEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var QOu=class extends oY{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new ew({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Lo)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>HP(n.convert())?.map(o=>({displayName:n.name,shape:o,description:n.description,availability:n.availability?.convert()}))).filter(Lo).reduce((n,a)=>n.flatMap(o=>a.length>0?a.map(c=>[...o,c]):[[...o]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(BUi).filter(Lo):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function UOu(e){return e!=null&&e.length>0?e:[void 0]}var xua=class extends oY{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new ew({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new ew({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(xv(t))return Hua(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new ew({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Lo))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return Gua(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:HP(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(Lo)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>UOu(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>oc.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=_C(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,o])=>[a,new ew({input:o,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var LOu=class extends oY{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>_C(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>_C(t,this.context.document)?.type!=="null"?new ew({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Lo);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=_C({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new ew({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(Lo);return this.isNullable&&n!=null?n.map(BUi).filter(Lo):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:oc.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>HP(a.convert())?.map(c=>{if(!(c==null||c.type!=="object"))return{discriminantValue:n,displayName:a.name??QYt(n),availability:a.availability?.convert(),description:a.description,...c}}).filter(Lo)).filter(Lo)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>HP(n.convert())?.map(o=>{if(o==null)return;t+=1;let c=o.type==="object"?QYt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(o.type==="alias"&&o.value.type==="id"?QYt(o.value.id):c),shape:o,description:n.description,availability:n.availability?.convert()}}).filter(Lo)).filter(Lo)}:void 0,i=this.isNullable?BUi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var VOu=class extends pC{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var j$i=class extends pC{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(xv(r)){let n=_C(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(Lo),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var WIh=ce(ZS());function CdB(e){return aKc.includes(e)}var WOu=class extends pC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(CdB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${aKc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new WIh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var GOu=class extends pC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return BUi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var GIh=ce(ZS());function qdB(e){return nKc.includes(e)}var HOu=class extends pC{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(qdB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${nKc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new GIh.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var HIh=ce(ZS());function TdB(e){return oKc.includes(e)}var xOu=class extends pC{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new HIh.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(TdB(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${oKc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new j$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var xIh=ce(ZS());var KOu=class extends pC{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,xIh.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var Bvn=class extends oY{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=Hua(this.input);let t=_C(this.input,this.context.document);t?.enum!=null&&P$i(t)&&(this.maybeEnumConverterNode=new j$i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:oc.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=_C(this.input,this.context.document);if(r!=null)return new ew({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var ew=class e extends oY{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new ZEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),P$i(this.input)&&QIh(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),xv(this.input)){let t=Hua(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new Bvn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new FOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(FIh(this.input))this.typeShapeNode=new QOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(P$i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new LOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(lKc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new xua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(P$i(this.input)&&this.input.enum!=null)this.typeShapeNode=new j$i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":lKc(this.input)&&(this.typeShapeNode=new xua({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":m$i(this.input)&&(this.typeShapeNode=new NOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":zIh(this.input)&&(this.typeShapeNode=new VOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":NIh(this.input)&&(this.typeShapeNode=new WOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":LIh(this.input)&&(this.typeShapeNode=new HOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":VIh(this.input)&&(this.typeShapeNode=new xOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":UIh(this.input)&&(this.typeShapeNode=new GOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new KIh.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new xua({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new KOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!xv(this.input)&&(!m$i(this.input)&&this.input==null||m$i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=HP(t)?.map(i=>this.nullable?BUi(i):i).filter(Lo);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function w$i(e){if(e!=null)return Gua(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Lo))}var LYt=class extends pC{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;xv(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new ZEe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new ew({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=TIh(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function JIh(e,t){return xv(e)?pL(e,t,void 0):e}var fKc=ce(ZS());function JOu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[oc.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var $Ih=ce(y2s(),1),Kua=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,o){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=o}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=$Ih.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function RdB(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var $Ou=class extends ho{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new ew({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),RdB(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(xv(r)?n=aOu(r.$ref,this.context.document):n=r,n!=null)return[t,new Vua({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Lo)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[oc.api.latest.AuthSchemeId(t),i]}).filter(Lo)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=HP(r.convert());return n==null?[t,void 0]:[oc.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Lo(r))):void 0}}};var YOu=class extends ew{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=_C(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${xv(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=_C(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var XOu=class extends ho{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=_C(this.input.schema,this.context.document);this.availability=new ZEe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=xv(this.input.schema)?new Bvn({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=Kua.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new ew({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,o])=>{if(o!=null)return[a,new YOu({input:o,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Lo))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[yF]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[yF]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:HP(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=g8t([this.method,this.path,this.contentType,"request"].join("_"));return JOu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:oc.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new fKc.UnreachableCaseError(n);return}}).filter(Lo)}convert(){if(this.schema instanceof Bvn)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:oc.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:oc.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=HP(n.convert()),o=n.multipartType;return a?.map(c=>({type:o,key:oc.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:c,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new fKc.UnreachableCaseError(n.multipartType),[]}}).filter(Lo).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(o=>[...a,o]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var ZOu=class extends ho{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=JIh(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new XOu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>HP(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Lo)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>HP(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Lo)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var YIh={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function XIh(e,t){if(xv(e)){let r=pL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var kOu=ce(ZS());var ZIh="application/json";var kIh="application/octet-stream";function eCh(e,t){return e===t||t===yF||e===yF}var GKa=class extends ho{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,o,c,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=o,this.requests=c,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,o]of Object.entries(n?.examples??{}))for(let[c,d]of Object.entries(r))for(let s of d)eCh(c,a)&&(i.add(c),this.examples?.push(new UYt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,O$i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[o,c]of r){if(a===i){let[d,s,u]=n??[void 0,void 0,void 0];this.examples?.push(...c.map(l=>new UYt({input:{requestExample:u,responseExample:l},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,O$i(s,o),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,o]=r[r.length-1]??[void 0,void 0],[c,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(o??[void 0]).map(u=>new UYt({input:{requestExample:s,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,O$i(d,a),{requestBody:c,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,o]=t[t.length-1]??[void 0,void 0,void 0];for(let[c,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new UYt({input:{requestExample:o,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,O$i(a,c),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[yF];if(a!=null)for(let o of a)this.examples?.push(new UYt({input:{requestExample:n,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,O$i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let c=Kua.parse(t);if(c?.isJSON()||c?.isEventStream())this.contentType=ZIh,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new ew({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(c?.isOctetStream())this.contentType=kIh,this.contentSubtype=_C(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new ew({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=wOu(this.input.examples,c=>[c])),this.input.example!=null&&Object.keys(r).length===0&&(r[yF]??=[],r[yF]=[{value:this.input.example}]);let i=_C(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=wOu(i.examples,c=>[c])),i.example!=null&&Object.keys(r).length===0&&(r[yF]??=[],r[yF]?.push({value:i.example}))),Object.keys(r).length===0){let c=this.schema?.example({includeOptionals:!0,override:void 0});r[yF]??=[],r[yF]?.push(c!=null?{value:c}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let c of this.requests)a.push(...Object.entries(c.examples??{}).filter(([d])=>!n.has(d)&&d!==yF).map(([d,s])=>[c,d,s]));let o=Object.entries(r).filter(([c,d])=>!n.has(c)&&Lo(d)&&c!==yF);Object.keys(r).every(c=>c===yF)||this.matchExamplesByIndex(a,o),!n.has(yF)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return HP(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new kOu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return HP(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=g8t([this.method,this.path,this.statusCode,"response"].join("_"));return JOu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:oc.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new kOu.UnreachableCaseError(i);return}}).filter(Lo)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new kOu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var HKa=class extends ho{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,o){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=o,this.safeParse()}parse(t){this.description=this.input.description;let r=XIh(this.input,this.context.document);if(r==null){this.context.errors.error({message:xv(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new LYt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new GKa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new GKa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(Lo)}};var eAu=class extends ho{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new HKa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new HKa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return UOu(w$i(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(o=>(o.examples??[]).map(c=>c.convert()).filter(Lo))})))}).filter(Lo)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=HP(n?.convert());if(n!=null)return a?.map(o=>({statusCode:parseInt(t),shape:o,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??YIh[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(c=>{let d=c.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(Lo)})).filter(Lo)})).filter(Lo)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var E$i=class extends ho{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new UYt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,O$i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new ZEe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=v$i(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new ROu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(xv(i)){let a=BOu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new LYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new LYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new LYt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new zOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new ZOu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new eAu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,o])=>{this.pushEmptyResponseExample(o,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new Wua({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new WKa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new WKa({input:{[rOu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new TOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>EOu({namespace:HP(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(Lo),this.xFernExamplesNode=new qOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(Lo)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:oc.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(u=>u.convert()).filter(Lo),n=EIh(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(u=>u.examples)??[]])?.map(u=>({...u,snippets:wIh(u.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((u,l)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:oc.WebhookId(u),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[l]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(p=>p.value.toString())??[],queryParameters:w$i(this.queryParameters)?.flat(),headers:w$i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Lo)}}).filter(Lo);let a=this.servers?.map(u=>u.convert()).filter(Lo),o=this.convertPathToPathParts();if(o==null)return;let c,d=this.auth?.convert();d!=null&&(c=Object.keys(d));let s=t?.flatMap(u=>u.headers).filter(Lo);return this.endpointIds.map((u,l)=>({id:oc.EndpointId(u),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[l]?.convert()?.map(p=>oc.api.v1.SubpackageId(p)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:o,auth:c?.map(p=>oc.api.latest.AuthSchemeId(p)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:w$i(this.pathParameters)?.flat(),queryParameters:w$i(this.queryParameters)?.flat(),requestHeaders:w$i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(p=>p.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var Jua=class extends ho{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=v$i(t,this.input.servers,this.context,this.accessPath),o=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new E$i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:o,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new E$i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:o,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new E$i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:o,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new E$i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:o,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new E$i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:o,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(Lo)}};function tAu(e){return"payloads"in e}var rAu=class extends ho{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new Jua({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:v$i(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Lo)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{tAu(a)?r[oc.WebhookId(a.id)]=a:t[oc.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var iAu=class extends ho{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[gBh]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||BOu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new LYt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return Gua(this.globalHeaders,this.requiredProperties)?.flat()}};function tCh(e,t){if(xv(e)){let r=pL(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var nAu=class extends ho{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let o=tCh(a,this.context.document);if(o!=null)return new Jua({input:o,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Lo)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{tAu(i)&&(t[oc.WebhookId(i.id)]=i)}),t),{})}};var aAu=class extends ho{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=v$i(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new Wua({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new DOu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new rAu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new nAu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new $Ou({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new iAu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=ave(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=hBh({endpoints:i,webhookEndpoints:n}),{types:o,auths:c}=this.components?.convert()??{};return{id:oc.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...o,...this.context.generatedTypes},subpackages:a,auths:{...c,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};async function dKc(e,t){if(e instanceof LEe){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof sS))return;let r=new u8t(e.absoluteFilePath),i=await WEe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let o of n){if(o.type!=="openapi")continue;let c={document:o.value,logger:t.logger,errors:new eOu,generatedTypes:{}},d=new aAu({input:o.value,context:c,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=C2s(a,d.convert())}return a}var gLh=ce(hKc(),1),OLh=ce(KAu(),1),bPu=require("fs/promises"),ALh=ce(require("http"),1),mLh=ce(require("path"),1);var azh=require("events"),ZAu=ce(require("fs"),1),Uvn=ce(require("path"),1);var LRh=ce(require("os"),1),VRh=300,q$i=20,_Ja=1e7,WRh=LRh.default.platform();var iOB=WRh==="darwin",RJc=WRh==="win32",T$i=iOB||RJc,GRh=3e3,HRh=2e4,zJc=1250;var HYt;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(HYt||(HYt={}));var Qvn;(function(e){e.CHANGE="change",e.RENAME="rename"})(Qvn||(Qvn={}));var hJa;(function(e){e.CHANGE="change",e.ERROR="error"})(hJa||(hJa={}));var tf;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(tf||(tf={}));var yH;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(yH||(yH={}));var nOB=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let g=Date.now(),m=g-d,j=g-s,M=m>=t||j>=a;return[g,M]},l=g=>{if(s=g,!o)return;let m=o;o=void 0,e.apply(void 0,m)},p=()=>{O(0)},_=()=>{c&&(p(),l(Date.now()))},h=g=>{if(s=g,i)return l(g)},y=g=>{if(n&&o)return l(g);o=void 0},b=()=>{c=void 0;let[g,m]=u();return m?y(g):v(g)},v=g=>{let m=g-d,j=g-s,M=t-m,w=a-j,D=Math.min(M,w);return O(D)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},A=(...g)=>{let[m,j]=u(),M=!!c;if(o=g,d=m,(j||!c)&&O(t),j)return M?l(m):h(m)};return A.cancel=p,A.flush=_,A},JAu=nOB;var UJc=ce(require("fs"),1),YAu=ce(require("path"),1);var iA=ce(require("fs"),1),_L=require("util");var CUi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},xYt=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var NJc=ce(require("process"),1),xRh=NJc.default.getuid?!NJc.default.getuid():!1,KRh=1e4,lY=()=>{};var yJa={isChangeErrorOk:e=>{if(!yJa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!xRh&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!yJa.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!yJa.isNodeError(e))throw e;if(!yJa.isChangeErrorOk(e))throw e}},hC=yJa;var FJc=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=KRh,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},JRh=new FJc;var qUi=(e,t)=>function(i){return function n(...a){return JRh.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},TUi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var aOB={attempt:{chmod:CUi((0,_L.promisify)(iA.default.chmod),hC.onChangeError),chown:CUi((0,_L.promisify)(iA.default.chown),hC.onChangeError),close:CUi((0,_L.promisify)(iA.default.close),lY),fsync:CUi((0,_L.promisify)(iA.default.fsync),lY),mkdir:CUi((0,_L.promisify)(iA.default.mkdir),lY),realpath:CUi((0,_L.promisify)(iA.default.realpath),lY),stat:CUi((0,_L.promisify)(iA.default.stat),lY),unlink:CUi((0,_L.promisify)(iA.default.unlink),lY),chmodSync:xYt(iA.default.chmodSync,hC.onChangeError),chownSync:xYt(iA.default.chownSync,hC.onChangeError),closeSync:xYt(iA.default.closeSync,lY),existsSync:xYt(iA.default.existsSync,lY),fsyncSync:xYt(iA.default.fsync,lY),mkdirSync:xYt(iA.default.mkdirSync,lY),realpathSync:xYt(iA.default.realpathSync,lY),statSync:xYt(iA.default.statSync,lY),unlinkSync:xYt(iA.default.unlinkSync,lY)},retry:{close:qUi((0,_L.promisify)(iA.default.close),hC.isRetriableError),fsync:qUi((0,_L.promisify)(iA.default.fsync),hC.isRetriableError),open:qUi((0,_L.promisify)(iA.default.open),hC.isRetriableError),readFile:qUi((0,_L.promisify)(iA.default.readFile),hC.isRetriableError),rename:qUi((0,_L.promisify)(iA.default.rename),hC.isRetriableError),stat:qUi((0,_L.promisify)(iA.default.stat),hC.isRetriableError),write:qUi((0,_L.promisify)(iA.default.write),hC.isRetriableError),writeFile:qUi((0,_L.promisify)(iA.default.writeFile),hC.isRetriableError),closeSync:TUi(iA.default.closeSync,hC.isRetriableError),fsyncSync:TUi(iA.default.fsyncSync,hC.isRetriableError),openSync:TUi(iA.default.openSync,hC.isRetriableError),readFileSync:TUi(iA.default.readFileSync,hC.isRetriableError),renameSync:TUi(iA.default.renameSync,hC.isRetriableError),statSync:TUi(iA.default.statSync,hC.isRetriableError),writeSync:TUi(iA.default.writeSync,hC.isRetriableError),writeFileSync:TUi(iA.default.writeFileSync,hC.isRetriableError)}},$Rh=aOB;var $Au=ce(require("fs"),1),bJa=ce(require("path"),1);var QJc=()=>{};var oOB=()=>{let e=QJc,t=QJc,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},YRh=oOB;var uOB=()=>{let{promise:e,resolve:t,isPending:r}=YRh(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return(()=>{n(),queueMicrotask(a)})(),{promise:e,isPending:r,increment:n,decrement:a}},XRh=uOB;var ZRh={then:e=>{e()}};var kRh=e=>Array.isArray(e)?e:[e],ezh=e=>typeof e=="function";var sOB=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=kRh(a).map(G=>ezh(G)?G:H=>G.test(H)),c=G=>o.some(H=>H(G)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],l=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,O={},A={},g=new Set,m={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:l,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:A},{promise:M,increment:w,decrement:D}=XRh(),B=0,R=(G,H,Ee,ue)=>{g.has(H)||B>=n||(B+=1,G.directories.push(H),G.directoriesNames.add(Ee),u.push(H),l.add(Ee),p.propertyIsEnumerable(Ee)||(p[Ee]=[]),p[Ee].push(H),g.add(H),!(ue>=i)&&(B>=n||ee(H,ue+1)))},N=(G,H,Ee)=>{g.has(H)||B>=n||(B+=1,G.files.push(H),G.filesNames.add(Ee),_.push(H),h.add(Ee),y.propertyIsEnumerable(Ee)||(y[Ee]=[]),y[Ee].push(H),g.add(H))},z=(G,H,Ee,ue)=>{g.has(H)||B>=n||(B+=1,G.symlinks.push(H),G.symlinksNames.add(Ee),b.push(H),v.add(Ee),O.propertyIsEnumerable(Ee)||(O[Ee]=[]),O[Ee].push(H),g.add(H),r&&(ue>=i||B>=n||Pe(H,ue+1)))},F=(G,H,Ee,ue,Oe)=>{d.aborted||c(H)||(ue.isDirectory()?R(G,H,Ee,Oe):ue.isFile()?N(G,H,Ee):ue.isSymbolicLink()&&z(G,H,Ee,Oe))},U=(G,H,Ee,ue)=>{if(d.aborted)return;let Oe=H===bJa.default.sep?"":bJa.default.sep,Qe=Ee.name,se=`${H}${Oe}${Qe}`;c(se)||(Ee.isDirectory()?R(G,se,Qe,ue):Ee.isFile()?N(G,se,Qe):Ee.isSymbolicLink()&&z(G,se,Qe,ue))},x=(G,H,Ee,ue)=>{for(let Oe=0,Qe=Ee.length;Oe<Qe;Oe++)U(G,H,Ee[Oe],ue)},ee=(G,H)=>{d.aborted||H>i||B>=n||(w(),$Au.default.readdir(G,{withFileTypes:!0},(Ee,ue)=>{if(Ee||d.aborted||!ue.length)return D();(s(ue)||ZRh).then(()=>{let Qe=A[G]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};x(Qe,G,ue,H),D()})}))},Pe=(G,H)=>{w(),$Au.default.realpath(G,(Ee,ue)=>{if(Ee||d.aborted)return D();$Au.default.stat(ue,(Oe,Qe)=>{if(Oe||d.aborted)return D();let se=bJa.default.basename(ue),ne=A[G]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};F(ne,ue,se,Qe,H),D()})})};return(async(G,H=1)=>(G=bJa.default.normalize(G),g.add(G),ee(G,H),await M,d.aborted?m:j))(e)},tzh=sOB;var KYt={lang:{debounce:JAu,attempt:e=>{try{return e()}catch(t){return KYt.lang.castError(t)}},castArray:e=>KYt.lang.isArray(e)?e:[e],castError:e=>KYt.lang.isError(e)?e:KYt.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(KYt.lang.isNaN(e))return KYt.lang.isNaN(t);if(KYt.lang.isPrimitive(e)||KYt.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(YAu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?UJc.default.realpathSync.native(e):UJc.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===YAu.default.sep&&t.length-e.length>YAu.default.sep.length,poll:(e,t=HRh)=>$Rh.retry.stat(t)(e,{bigint:!0}).catch(KYt.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await tzh(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Fp=KYt;var XAu=ce(require("path"),1);var LJc=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Fp.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=VRh){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),l=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(l)},o=Fp.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===tf.CHANGE&&c===tf.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===tf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===tf.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??q$i:Math.min(1,this.options.depth??q$i),o=this.options.limit??_Ja,[c,d]=await Fp.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())Fp.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(tf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!T$i&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(tf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(tf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(XAu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(tf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(XAu.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(tf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===tf.ADD?this.onTargetAdd(i):r===tf.ADD_DIR?this.onTargetAddDir(i):r===tf.CHANGE?this.onTargetChange(i):r===tf.UNLINK?this.onTargetUnlink(i):r===tf.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=Qvn.CHANGE,r){if(this.watcher.isClosed())return;let i=XAu.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){RJc&&t.code==="EPERM"?this.onWatcherChange(Qvn.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(hJa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(hJa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Qvn.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&T$i&&this.options.native!==!1?this.options.depth??q$i:Math.min(1,this.options.depth??q$i),i=this.options.limit??_Ja,[n,a]=await Fp.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(Qvn.CHANGE,c,t)}))}}},rzh=LJc;var bH={interval:100,intervalId:void 0,fns:new Map,init:()=>{bH.intervalId||(bH.intervalId=setInterval(bH.resolve,bH.interval))},reset:()=>{bH.intervalId&&(clearInterval(bH.intervalId),delete bH.intervalId)},add:(e,t)=>{bH.fns.set(e,Date.now()+t),bH.init()},remove:e=>{bH.fns.delete(e)},resolve:()=>{if(!bH.fns.size)return bH.reset();let e=Date.now();for(let[t,r]of bH.fns)r>=e||(bH.remove(t),t())}},vJa=bH;var gJa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=zJc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let l=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(l&&l!==n){if(Fp.fs.getRealPath(n,!0)===l)return;this._watcher.event(a.rename,l,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),vJa.remove(s)},s=()=>{d(),c()};vJa.add(s,r);let u=()=>{let l=o.unlink.get(i);if(!l)return;d();let p=l();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=zJc){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),vJa.remove(s)},s=()=>{d(),c()};vJa.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,tf.ADD,HYt.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,tf.ADD_DIR,HYt.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,tf.UNLINK,HYt.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,tf.UNLINK_DIR,HYt.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};gJa.DIR_EVENTS={add:tf.ADD_DIR,rename:tf.RENAME_DIR,unlink:tf.UNLINK_DIR};gJa.FILE_EVENTS={add:tf.ADD,change:tf.CHANGE,rename:tf.RENAME,unlink:tf.UNLINK};var izh=gJa;var VJc=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Fp.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Fp.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(Fp.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(Fp.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Fp.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Fp.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},WJc=VJc;var GJc=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},nzh=GJc;var HJc=class{constructor(){this.inos={},this.paths=new WJc,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await Fp.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new nzh(i)}reset(){this.inos={},this.paths=new WJc,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,tf.ADD,n),[tf.ADD];if(n.isDirectory())return this.updateIno(t,tf.ADD_DIR,n),[tf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,tf.UNLINK,i),[tf.UNLINK];if(i.isDirectory())return this.updateIno(t,tf.UNLINK_DIR,i),[tf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,tf.CHANGE,n),[tf.CHANGE]);if(n.isDirectory())return this.updateIno(t,tf.UNLINK,i),this.updateIno(t,tf.ADD_DIR,n),[tf.UNLINK,tf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,tf.UNLINK_DIR,i),this.updateIno(t,tf.ADD,n),[tf.UNLINK_DIR,tf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,tf.UNLINK_DIR,i),this.updateIno(t,tf.ADD_DIR,n),[tf.UNLINK_DIR,tf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?HYt.FILE:HYt.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},xJc=HJc;var KJc=class e extends azh.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(yH.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(yH.CLOSE,n)),this._readyWait=new Promise(n=>this.on(yH.READY,n)),this._locker=new izh(this),this._roots=new Set,this._poller=new xJc,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Fp.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(yH.CLOSE))}error(t){if(this.isClosed())return!1;let r=Fp.lang.castError(t);return this.emit(yH.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(yH.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(yH.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Fp.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Fp.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)Fp.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new rzh(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Fp.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=Uvn.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??q$i))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&T$i&&u.options.native!==!1)))return!0;if(!T$i)break;let s=Uvn.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Fp.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||T$i&&r.native!==!1?r:{...r,recursive:!1},u={watcher:ZAu.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},l=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=Uvn.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,l)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||T$i&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??q$i,c=r.limit??_Ja,[d]=await Fp.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=Fp.fs.getDepth(t);for(let l of d){let p=Fp.fs.getDepth(l),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([l],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(yH.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(yH.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=Uvn.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new xJc,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return Fp.lang.noop;if(this.pollerExists(t,r))return Fp.lang.noop;let n={...r,interval:r.pollingInterval??GRh},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(yH.CLOSE,c),ZAu.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(yH.CLOSE,c),ZAu.default.unwatchFile(t,i)};return Fp.lang.attempt(o),()=>Fp.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=Fp.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Fp.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=Uvn.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Fp.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=Uvn.default.dirname(t);return(await Fp.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Fp.lang.noop){if(Fp.lang.isFunction(t))return this.watch([],{},t);if(Fp.lang.isUndefined(t))return this.watch([],r,i);if(Fp.lang.isFunction(r))return this.watch(t,{},r);if(Fp.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Fp.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Fp.lang.noop&&this.on(yH.ALL,i),r.readdirMap=void 0,this.ready())}},kAu=KJc;zXo();var lsa=require("fs/promises"),ozh=require("os"),uzh=ce(require("path"),1),cOB=".fern",lOB="logs";function fOB(){return"cli@3.31.1"}var OJa=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Ct(Cr.of((0,ozh.homedir)()),Ze.of(cOB)),r=Ct(t,Ze.of(lOB));await ji(r)||await(0,lsa.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Ct(r,Ze.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${uzh.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
1785
1785
|
`);await(0,lsa.writeFile)(this.logFilePath,a,"utf-8"),this.initialized=!0}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
|
|
1786
1786
|
`;try{await(0,lsa.appendFile)(this.logFilePath,r,"utf-8")}catch{}}async logFrontendMetrics(t){let r={timestamp:t.timestamp,source:t.source,level:t.level,eventType:this.getEventType(t.payload,t.isAggregate),isAggregate:t.isAggregate,data:t.payload};await this.writeEntry(r)}async logCliMetric(t,r="info"){let i={timestamp:t.timestamp,source:fOB(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(i)}async logCliMemory(){let t=process.memoryUsage(),r={type:"cli_memory",timestamp:new Date().toISOString(),metadata:{heapUsed:t.heapUsed,heapTotal:t.heapTotal,external:t.external,rss:t.rss,heapUsedMB:Math.round(t.heapUsed/1024/1024*100)/100,heapTotalMB:Math.round(t.heapTotal/1024/1024*100)/100,rssMB:Math.round(t.rss/1024/1024*100)/100}};await this.logCliMetric(r)}async logCliReloadStart(){let t={type:"cli_reload_start",timestamp:new Date().toISOString()};await this.logCliMetric(t)}async logCliReloadFinish(t,r){let i={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliDocsGeneration(t,r){let i={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliValidation(t,r){let i={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(i)}getEventType(t,r){return r?"aggregate_summary":"type"in t&&typeof t.type=="string"?t.type:"unknown"}static isMetricsMessage(t){if(typeof t!="object"||t===null)return!1;let r=t;return r.type==="metrics"&&typeof r.timestamp=="string"&&typeof r.source=="string"}};var OYc=ce(r$c(),1),k4h=ce(Gmu(),1),fY=require("fs/promises"),eLh=require("os"),tLh=ce(fG(),1),rLh=ce(X4h(),1),uPu=process.platform==="win32",gYc=It.cyan("[docs]:"),IjB="etag",CjB=23,Z4h=e=>e.padEnd(CjB," "),qjB="preview",TjB="app-preview",RjB="bundle",zjB=".next",NjB="standalone",FjB=".fern",QjB="packages/fern-docs/bundle/.next/server/instrumentation.js",UjB=".npmrc",LjB=".pnpmfile.cjs",VjB="pnpm-workspace.yaml",WjB='Cannot find matching keyid: {"signatures":';function GjB(){return Ct(Cr.of((0,eLh.homedir)()),Ze.of(FjB))}function Ssa({app:e=!1}){return Ct(GjB(),Ze.of(e?TjB:qjB))}function W$i({app:e=!1}){return Ct(Ssa({app:e}),Ze.of(e?zjB:RjB))}function GJa({app:e=!1}){return Ct(W$i({app:e}),Ze.of(NjB))}function HjB({app:e=!1}){return Ct(GJa({app:e}),Ze.of(QjB))}function xjB({app:e=!1}){return Ct(GJa({app:e}),Ze.of(VjB))}function KjB({app:e=!1}){return Ct(GJa({app:e}),Ze.of(LjB))}function JjB({app:e=!1}){return Ct(GJa({app:e}),Ze.of(UjB))}function Kvn(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function $jB({app:e=!1}){return Ct(Ssa({app:e}),Ze.of(IjB))}var YjB=`module.exports = {
|
|
1787
1787
|
hooks: {
|
|
@@ -2014,7 +2014,7 @@ Unable to analyze changes with AI, incrementing PATCH version.
|
|
|
2014
2014
|
If you believe this is an error, please contact support@buildwithfern.com`),orgNotConfiguredForWhitelabel:()=>a.failAndThrow("Your org is not configured for white-labeling. Please reach out to support@buildwithfern.com."),_other:h=>(a.logger.debug(`Failed to create job: ${JSON.stringify(h)}`),a.failAndThrow("Failed to create job. Please try again or contact support@buildwithfern.com for assistance."))})}async function OE5({intermediateRepresentation:e,generatorInvocation:t,job:r,context:i,irVersionOverride:n}){let a=await Upn(t).then(l=>l==null?void 0:"v"+l.toString()),o=n??a,c=o==null?await iBo({intermediateRepresentation:e,context:i,targetGenerator:{name:t.name,version:t.version}}):await _up({intermediateRepresentation:e,context:i,irVersion:o,targetGenerator:{name:t.name,version:t.version}}),d=new KhE.default,s=await pic(c,{onWrite:l=>{i.logger.debug("Wrote IR to disk: "+l)}});d.append("file",s);let u=(0,JhE.default)(avc(),`/api/remote-gen/jobs/${r.jobId}/start`);try{await RB.post(u,d,{headers:d.getHeaders(),maxBodyLength:1/0})}catch(l){let p=l instanceof wR_?l.response?.data:l;i.logger.debug(`POST ${u} failed with ${JSON.stringify(l)}`),i.failAndThrow("Failed to start job",p)}}function AE5(e){if(e?.content?.reason==="status-code"){let t=e.content.body;switch(t?._error){case"IllegalApiNameError":return r9i.FernFiddle.remoteGen.createJobV3.Error.illegalApiNameError();case"IllegalApiVersionError":return r9i.FernFiddle.remoteGen.createJobV3.Error.illegalApiVersionError(t.body);case"GeneratorsDoNotExistError":return r9i.FernFiddle.remoteGen.createJobV3.Error.generatorsDoNotExistError(t.body);case"CannotPublishToNpmScope":return r9i.FernFiddle.remoteGen.createJobV3.Error.cannotPublishToNpmScope(t.body);case"CannotPublishToMavenScope":return r9i.FernFiddle.remoteGen.createJobV3.Error.cannotPublishToMavenGroup(t.body);case"CannotPublishPypiPackage":return r9i.FernFiddle.remoteGen.createJobV3.Error.cannotPublishPypiPackage(t.body);case"InsufficientPermissions":return r9i.FernFiddle.remoteGen.createJobV3.Error.insufficientPermissions(t.body);case"OrgNotConfiguredForWhitelabel":return r9i.FernFiddle.remoteGen.createJobV3.Error.orgNotConfiguredForWhitelabel(t.body)}}return e}function mE5({outputMode:e,generatorInvocation:t,absolutePathToPreview:r,shouldLogS3Url:i}){return e.type==="downloadFiles"||t.absolutePathToLocalSnippets!=null||r!=null||i}var YhE=fFi();var PE5=3;function XhE({job:e,taskId:t,taskHandler:r,context:i}){let n=0,a=async()=>{let o=await YhE.remoteGen.getJobStatus(e.jobId);if(o.ok)return o.body[t];i.logger.debug("Failed to get job status.",JSON.stringify(o.error.content))};return new Promise((o,c)=>{d();async function d(){try{let s=await a();if(s==null)n++,n===PE5&&i.failAndThrow(`Failed to get job status after ${n} attempts.`),setTimeout(d,2e3+1e3*n);else{n=0;let u=await r.processUpdate(s);r.isFinished?o(u):setTimeout(d,2e3)}}catch(s){c(s)}}})}var Pup=ce(Gmu(),1),jup=require("fs"),n9i=require("fs/promises"),WKs=ce(require("path"),1),wup=require("stream/promises");var LKs=ce(eyE(),1);function i9i(e,t,{target:r="stdout",...i}={}){return LKs.default[r]?mna.link(e,t):i.fallback===!1?e:typeof i.fallback=="function"?i.fallback(e,t):`${e} (\u200B${t}\u200B)`}i9i.isSupported=LKs.default.stdout;i9i.stderr=(e,t,r={})=>i9i(e,t,{target:"stderr",...r});i9i.stderr.isSupported=LKs.default.stderr;var GKs=ce(fG(),1),VKs=class{context;generatorInvocation;absolutePathToPreview;lengthOfLastLogs=0;constructor({interactiveTaskContext:t,generatorInvocation:r,absolutePathToPreview:i}){this.context=t,this.generatorInvocation=r,this.absolutePathToPreview=i}async processUpdate(t){t==null&&this.context.failAndThrow("Task is missing on job status");let r=t.packages.map(n=>n.coordinate._visit({npm:a=>`${a.name}@${a.version}`,maven:a=>`${a.group}:${a.artifact}:${a.version}`,pypi:a=>`${a.name} ${a.version}`,ruby:a=>`${a.name}:${a.version}`,nuget:a=>`${a.name} ${a.version}`,crates:a=>`${a.name} ${a.version}`,_other:()=>"<unknown package>"}));t.packages.length>0&&this.#i==null&&(this.#i=t.packages[0]?.coordinate._visit({npm:n=>n.version,maven:n=>n.version,pypi:n=>n.version,ruby:n=>n.version,nuget:n=>n.version,crates:n=>n.version,_other:()=>{}})),this.absolutePathToPreview==null&&this.context.setSubtitle(r.length>0?r.map(n=>`\u25E6 ${n}`).join(`
|
|
2015
2015
|
`):void 0);for(let n of t.logs.slice(this.lengthOfLastLogs))if(this.context.logger.log(SE5(n.level),n.message),this.#i==null){let a=n.message.match(/Tagging release (\d+\.\d+\.\d+)/);a&&(this.#i=a[1])}this.lengthOfLastLogs=t.logs.length;let i=n=>{this.context.logger.debug(`Generated files. ${i9i("View here",n,{fallback:(a,o)=>`${a}: ${o}`})}`)};return await t.status._visit({notStarted:Bt,running:Bt,failed:({message:n,s3PreSignedReadUrl:a})=>{a!=null&&i(a),this.context.failAndThrow(n)},finished:async n=>{if(n.s3PreSignedReadUrlV2!=null){i(n.s3PreSignedReadUrlV2);let a=this.getAbsolutePathToLocalOutput();a!=null&&await wE5({s3PreSignedReadUrl:n.s3PreSignedReadUrlV2,absolutePathToLocalOutput:a,context:this.context})}if(this.absolutePathToPreview==null)for(let a of r)this.context.logger.info(`Published ${a}`);this.#e=!0,this.#t=n.createdSnippets!=null?n.createdSnippets:!1,this.#r=n.snippetsS3PreSignedReadUrl},_other:()=>{this.context.logger.warn("Received unknown update type: "+t.status.type)}}),this.#e?{createdSnippets:this.#t,snippetsS3PreSignedReadUrl:this.#r,actualVersion:this.#i}:void 0}getAbsolutePathToLocalOutput(){return this.absolutePathToPreview!=null?Ct(this.absolutePathToPreview,Ze.of(WKs.default.basename(this.generatorInvocation.name))):this.generatorInvocation.absolutePathToLocalOutput}#e=!1;get isFinished(){return this.#e}#t=!1;get createdSnippets(){return this.#t}#r=void 0;get snippetsS3PreSignedReadUrl(){return this.#r}#i=void 0;get actualVersion(){return this.#i}};async function wE5({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}){try{let i=await ME5(t),n=await DE5(t);i&&n?await BE5({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}):i&&!n?await IE5({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}):await EE5({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}),r.logger.info(It.green(`Downloaded to ${t}`))}catch(i){r.failAndThrow("Failed to download files",i)}}async function EE5({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await RB.get(e,{responseType:"stream"}),i=await GKs.default.dir({prefix:"fern",unsafeCleanup:!0}),n=WKs.default.join(i.path,"output.zip");await(0,wup.pipeline)(r.data,(0,jup.createWriteStream)(n)),await ji(t)&&await(0,n9i.rm)(t,{recursive:!0}),await(0,n9i.mkdir)(t,{recursive:!0}),await(0,Pup.default)(n,t)}function SE5(e){switch(e){case"DEBUG":return yc.Debug;case"INFO":return yc.Info;case"WARN":return yc.Warn;case"ERROR":return yc.Error;default:return yc.Info}}async function ME5(e){let t=Ct(e,Ze.of(gHt));return await ji(t)}async function DE5(e){let t=Ct(e,Ze.of(".git"));return await ji(t)}async function G3(e,t,r){return(await Gv(r.logger,"git",e,{cwd:t,doNotPipeOutput:!0})).stdout}async function BE5({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}){let i=Ct(t,Ze.of(gHt)),n=await ifn({absolutePathToFernignore:i});(await G3(["config","--list"],t,r)).includes("user.name")||(await G3(["config","user.name","fern-api"],t,r),await G3(["config","user.email","info@buildwithfern.com"],t,r)),await G3(["rm","-rf","."],t,r),await tyE({s3PreSignedReadUrl:e,outputPath:t}),await G3(["add","."],t,r),await G3(["reset","--",...n],t,r),await G3(["restore","."],t,r)}async function IE5({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t,context:r}){let i=Cr.of((await GKs.default.dir({})).path),n=Ct(t,Ze.of(gHt)),a=await ifn({absolutePathToFernignore:n});await(0,n9i.cp)(t,i,{recursive:!0}),await G3(["init"],i,r),await G3(["add","."],i,r),(await G3(["config","--list"],i,r)).includes("user.name")||(await G3(["config","user.name","fern-api"],i,r),await G3(["config","user.email","info@buildwithfern.com"],i,r)),await G3(["commit","--allow-empty","-m",'"init"'],i,r),await G3(["rm","-rf","."],i,r),await tyE({s3PreSignedReadUrl:e,outputPath:i}),await G3(["add","."],i,r),await G3(["reset","--",...a],i,r),await G3(["restore","."],i,r),await(0,n9i.rm)(Ct(i,Ze.of(".git")),{recursive:!0}),await(0,n9i.rm)(t,{recursive:!0}),await(0,n9i.cp)(i,t,{recursive:!0})}async function tyE({s3PreSignedReadUrl:e,outputPath:t}){let r=await RB.get(e,{responseType:"stream"}),i=await GKs.default.dir({prefix:"fern",unsafeCleanup:!0}),n=WKs.default.join(i.path,"output.zip");await(0,wup.pipeline)(r.data,(0,jup.createWriteStream)(n)),await(0,Pup.default)(n,t)}var xKs=require("fs/promises"),ryE=ce(fG(),1),CE5="proto.zip",HKs=class{sourceTypes;context;sources;constructor(t,r){this.context=t,this.sources=Object.fromEntries(r.map(i=>[i.id,i])),this.sourceTypes=new Set(Object.values(this.sources).map(i=>i.type))}async uploadSources(t){for(let[r,i]of Object.entries(t)){let n=this.getSourceOrThrow(r);await this.uploadSource(n,i.uploadUrl)}return this.convertFdrSourceUploadsToSourceConfig(t)}async uploadSource(t,r){let i=await this.getUploadCommand(t),n=await(0,xKs.readFile)(i.absoluteFilePath),a=await fetch(r,{method:"PUT",body:n,headers:{"Content-Type":"application/octet-stream"}});await i.cleanup(),a.ok||this.context.failAndThrow(`Failed to upload source file: ${t.absoluteFilePath}. Status: ${a.status}, ${a.statusText}`)}async getUploadCommand(t){if(t.type==="protobuf"){let r=await this.zipSource(t.absoluteFilePath);return{absoluteFilePath:r,cleanup:async()=>{this.context.logger.debug(`Removing ${r}`),await(0,xKs.unlink)(r)}}}return{absoluteFilePath:t.absoluteFilePath,cleanup:async()=>{}}}async zipSource(t){let r=await ryE.default.dir(),i=Ct(Cr.of(r.path),Ze.of(CE5));return this.context.logger.debug(`Zipping source ${t} into ${i}`),await Gv(this.context.logger,"zip",["-r",i,"."],{cwd:t,doNotPipeOutput:!0}),i}convertFdrSourceUploadsToSourceConfig(t){let r=[];for(let[i,n]of Object.entries(t))switch(this.getSourceOrThrow(i).type){case"protobuf":r.push(N$.proto({id:i,protoRootUrl:n.downloadUrl}));continue;case"openapi":r.push(N$.openapi());continue;case"asyncapi":continue}return{sources:r}}getSourceOrThrow(t){let r=this.sources[t];return r==null&&this.context.failAndThrow(`Internal error; server responded with source id "${t}" which does not exist in the workspace.`),r}};async function nyE({projectConfig:e,organization:t,workspace:r,interactiveTaskContext:i,generatorInvocation:n,version:a,audiences:o,shouldLogS3Url:c,token:d,whitelabel:s,irVersionOverride:u,absolutePathToPreview:l,readme:p,fernignorePath:_,dynamicIrOnly:h}){let y=KVt({token:d.value}),b=_n.getPackageName({generatorInvocation:n}),v=l!=null,O=G=>FT(G,{onError:H=>i.failAndThrow(H)},{substituteAsEmpty:v}),A=O(n),g=Axn({apiName:r.definition.rootApiFile.contents.name,organization:t,generatorInvocation:A}),m=a??await TE5({fdr:y,packageName:b,generatorInvocation:n}),j=lS({workspace:r,generationLanguage:n.language,keywords:n.keywords,smartCasing:n.smartCasing,exampleGeneration:{disabled:n.disableExamples,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!1},audiences:o,readme:p,packageName:b,version:m,context:i,sourceResolver:new cS(i,r),dynamicGeneratorConfig:g,generationMetadata:{cliVersion:r.cliVersion,generatorName:n.name,generatorVersion:n.version,generatorConfig:n.config}}),w=await I4({token:d.value}).organization.get(ny.OrganizationId(e.organization));w.ok&&(w.body.isWhitelabled&&(j.readmeConfig==null&&(j.readmeConfig=zE5),j.readmeConfig.whiteLabel=!0),j.selfHosted=w.body.selfHostedSdKs);let D=r.getSources(),B=pH({ir:j,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},context:i}),R=await y.api.v1.register.registerApiDefinition({orgId:di.OrgId(t),apiId:di.ApiId(j.apiName.originalName),definition:B,sources:D.length>0?RE5(D):void 0}),N,z;R.ok&&(N=R.body.apiDefinitionId,z=R.body.sources);let F=new HKs(i,D);if(z==null&&F.sourceTypes.has("protobuf")&&(R.ok||i.failAndThrow(`Failed to register API definition: ${JSON.stringify(R.error.content)}`),i.failAndThrow("Did not successfully upload Protobuf source files.")),z!=null){i.logger.debug("Uploading source files ...");let G=await F.uploadSources(z);i.logger.debug("Setting IR source configuration ..."),j.sourceConfig=G}if(h){if(i.logger.info("Dynamic IR only mode: skipping SDK generation and uploading dynamic IR only"),a==null){i.failAndThrow("Version is required for dynamic IR only mode");return}if(n.language==null){i.failAndThrow("Language is required for dynamic IR only mode");return}if(b==null){i.failAndThrow("Package name is required for dynamic IR only mode");return}try{await iyE({fdr:y,organization:t,version:a,language:n.language,packageName:b,ir:j,smartCasing:n.smartCasing,dynamicGeneratorConfig:g,context:i})}catch(G){i.failAndThrow(`Failed to upload dynamic IR: ${G instanceof Error?G.message:String(G)}`)}return{createdSnippets:!1,snippetsS3PreSignedReadUrl:void 0,actualVersion:a}}let U=await $hE({projectConfig:e,workspace:r,organization:t,generatorInvocation:A,context:i,version:a,intermediateRepresentation:{...j,fdrApiDefinitionId:N,publishConfig:qE5({generatorInvocation:A})},shouldLogS3Url:c,token:d,whitelabel:s!=null?O(s):void 0,irVersionOverride:u,absolutePathToPreview:l,fernignorePath:_});i.logger.debug(`Job ID: ${U.jobId}`);let x=U.taskIds[0];if(x==null){i.failAndThrow("Did not receive a task ID.");return}i.logger.debug(`Task ID: ${x}`);let ee=new VKs({job:U,taskId:x,generatorInvocation:n,interactiveTaskContext:i,absolutePathToPreview:l}),Pe=await XhE({job:U,taskHandler:ee,taskId:x,context:i}),ve=Pe?.actualVersion??m;if(Pe!=null&&ve!=null&&n.language!=null&&b!=null&&!v)try{await iyE({fdr:y,organization:t,version:ve,language:n.language,packageName:b,ir:j,smartCasing:n.smartCasing,dynamicGeneratorConfig:g,context:i})}catch(G){i.logger.warn(`Failed to upload dynamic IR for SDK generation: ${G instanceof Error?G.message:String(G)}`)}return Pe}function qE5({generatorInvocation:e}){return e.outputMode._visit({downloadFiles:()=>{},github:()=>{},githubV2:()=>{},publish:()=>{},publishV2:t=>t._visit({mavenOverride:()=>{},pypiOverride:()=>{},nugetOverride:()=>{},npmOverride:()=>{},rubyGemsOverride:()=>{},cratesOverride:()=>{},postman:r=>{let i;return e.raw?.output?.location==="postman"&&(i=e.raw.output?.["collection-id"]),Or.PublishingConfig.direct({target:Or.PublishTarget.postman({apiKey:r.apiKey,workspaceId:r.workspaceId,collectionId:i})})},_other:()=>{}}),_other:()=>{}})}async function TE5({fdr:e,packageName:t,generatorInvocation:r}){if(r.language==null)return;let i;switch(r.language){case"csharp":i="Csharp";break;case"go":i="Go";break;case"java":i="Java";break;case"python":i="Python";break;case"ruby":i="Ruby";break;case"typescript":i="TypeScript";break;case"php":i="Php";break;case"swift":i="Swift";break;default:return}if(t==null)return;let n=await e.sdks.versions.computeSemanticVersion({githubRepository:r.outputMode.type==="githubV2"?`${r.outputMode.githubV2.owner}/${r.outputMode.githubV2.repo}`:void 0,language:i,package:t});if(n.ok)return n.body.version}function RE5(e){return Object.fromEntries(Object.values(e).map(t=>[t.id,{type:t.type==="protobuf"?"proto":t.type}]))}var zE5={defaultEndpoint:void 0,bannerLink:void 0,introduction:void 0,apiReferenceLink:void 0,apiName:void 0,disabledFeatures:void 0,whiteLabel:void 0,customSections:void 0,features:void 0,exampleStyle:void 0};async function iyE({fdr:e,organization:t,version:r,language:i,packageName:n,ir:a,smartCasing:o,dynamicGeneratorConfig:c,context:d}){d.logger.debug(`Uploading dynamic IR for ${i} SDK...`);let s=await e.api.v1.register.getSdkDynamicIrUploadUrls({orgId:di.OrgId(t),version:r,snippetConfiguration:{[i]:n}});if(!s.ok){d.logger.warn(`Failed to get dynamic IR upload URLs: ${s.error.error}`);return}let u=s.body.uploadUrls[i]?.uploadUrl;if(u==null){d.logger.warn(`No upload URL returned for ${i}`);return}let l=mvn({ir:a,disableExamples:!0,smartCasing:o,generationLanguage:i,generatorConfig:c}),p=JSON.stringify(l),_=await fetch(u,{method:"PUT",body:p,headers:{"Content-Type":"application/octet-stream","Content-Length":p.length.toString()}});_.ok?d.logger.debug(`Uploaded dynamic IR for ${i}:${n} (${r})`):d.logger.warn(`Failed to upload dynamic IR for ${i}: ${_.status}`)}async function Eup({projectConfig:e,organization:t,workspace:r,context:i,generatorGroup:n,version:a,shouldLogS3Url:o,token:c,whitelabel:d,absolutePathToPreview:s,mode:u,fernignorePath:l,dynamicIrOnly:p}){if(n.generators.length===0)return i.logger.warn("No generators specified."),null;let _=[],h=[];return _.push(...n.generators.map(b=>i.runInteractiveTask({name:b.name},async v=>{let O=Aoa(b),A=await r.toFernWorkspace({context:i},O,b.apiOverride?.specs),g=await nyE({projectConfig:e,organization:t,workspace:A,interactiveTaskContext:v,generatorInvocation:{...b,outputMode:b.outputMode._visit({downloadFiles:()=>b.outputMode,github:m=>KKs.FernFiddle.OutputMode.github({...m,makePr:u==="pull-request"}),githubV2:m=>u==="pull-request"?KKs.FernFiddle.OutputMode.githubV2(KKs.FernFiddle.GithubOutputModeV2.pullRequest(m)):b.outputMode,publish:()=>b.outputMode,publishV2:()=>b.outputMode,_other:()=>b.outputMode})},version:a,audiences:n.audiences,shouldLogS3Url:o,token:c,whitelabel:d,readme:b.readme,irVersionOverride:b.irVersionOverride,absolutePathToPreview:s,fernignorePath:l,dynamicIrOnly:p});g!=null&&g.createdSnippets&&(h.push(b),b.absolutePathToLocalSnippets!=null&&g.snippetsS3PreSignedReadUrl!=null&&await xhE({snippetsS3PreSignedReadUrl:g.snippetsS3PreSignedReadUrl,absolutePathToLocalSnippetJSON:b.absolutePathToLocalSnippets,context:v}))}))),(await Promise.all(_)).some(b=>!b)&&i.failAndThrow(),{snippetsProducedBy:h}}var vbE=require("crypto"),nsp=require("fs/promises");var asp=ce(E3a(),1);var rNa=(e,t,r)=>JSON.stringify(e,t,r);function oBo(e,t){return JSON.parse(e,t)}var _r=class e extends Error{constructor({message:t,statusCode:r,body:i,rawResponse:n}){super(NE5({message:t,statusCode:r,body:i})),Object.setPrototypeOf(this,e.prototype),this.statusCode=r,this.body=i,this.rawResponse=n}};function NE5({message:e,statusCode:t,body:r}){let i=[];return e!=null&&i.push(e),t!=null&&i.push(`Status code: ${t.toString()}`),r!=null&&i.push(`Body: ${rNa(r,void 0,2)}`),i.join(`
|
|
2016
2016
|
`)}var Ro=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};var zs=class e extends _r{constructor(t,r){super({message:"UnprocessableEntityError",statusCode:422,body:t,rawResponse:r}),Object.setPrototypeOf(this,e.prototype)}};var FE5={arrayFormat:"indices",encode:!0};function ayE(e,t){if(e===void 0||e===null)return"";let r=String(e);return t?encodeURIComponent(r):r}function Sup(e,t="",r){let i=[];for(let[n,a]of Object.entries(e)){let o=t?`${t}[${n}]`:n;if(a!==void 0)if(Array.isArray(a)){if(a.length===0)continue;for(let c=0;c<a.length;c++){let d=a[c];if(d!==void 0)if(typeof d=="object"&&!Array.isArray(d)&&d!==null){let s=r.arrayFormat==="indices"?`${o}[${c}]`:o;i.push(...Sup(d,s,r))}else{let s=r.arrayFormat==="indices"?`${o}[${c}]`:o,u=r.encode?encodeURIComponent(s):s;i.push(`${u}=${ayE(d,r.encode)}`)}}}else if(typeof a=="object"&&a!==null){if(Object.keys(a).length===0)continue;i.push(...Sup(a,o,r))}else{let c=r.encode?encodeURIComponent(o):o;i.push(`${c}=${ayE(a,r.encode)}`)}}return i}function JKs(e,t){return e==null||typeof e!="object"?"":Sup(e,"",Object.assign(Object.assign({},FE5),t)).join("&")}function oyE(e,t){let r=JKs(t,{arrayFormat:"repeat"});return r?`${e}?${r}`:e}function uyE(e){let t={get bodyUsed(){return e.bodyUsed},stream:()=>e.body,arrayBuffer:e.arrayBuffer.bind(e),blob:e.blob.bind(e)};return"bytes"in e&&typeof e.bytes=="function"&&(t.bytes=e.bytes.bind(e)),t}function syE(e){return e.body!=null}var QE5=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})};function $Ks(e,t){return QE5(this,void 0,void 0,function*(){if(!syE(e))return;switch(t){case"binary-response":return uyE(e);case"blob":return yield e.blob();case"arrayBuffer":return yield e.arrayBuffer();case"sse":return e.body;case"streaming":return e.body;case"text":return yield e.text()}let r=yield e.text();if(r.length>0)try{return oBo(r)}catch{return{ok:!1,error:{reason:"non-json",statusCode:e.status,rawBody:r}}}})}var UE5=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})};function cyE(e){return UE5(this,void 0,void 0,function*(){var t,r,i;let n=(t=e.headers.get("Content-Type"))===null||t===void 0?void 0:t.toLowerCase();if(n==null||n.length===0)return $Ks(e);switch(n.indexOf(";")!==-1&&(n=(i=(r=n.split(";")[0])===null||r===void 0?void 0:r.trim())!==null&&i!==void 0?i:""),n){case"application/hal+json":case"application/json":case"application/ld+json":case"application/problem+json":case"application/vnd.api+json":case"text/json":let a=yield e.text();return a.length>0?oBo(a):void 0;default:if(n.startsWith("application/vnd.")&&n.endsWith("+json")){let o=yield e.text();return o.length>0?oBo(o):void 0}return yield e.text()}})}var LE5=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})};function lyE(){return LE5(this,void 0,void 0,function*(){return fetch})}var VE5=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})};function fyE(e){return VE5(this,arguments,void 0,function*({body:t,type:r}){return r.includes("json")?rNa(t):t})}var WE5="timeout";function dyE(e){let t=new AbortController,r=setTimeout(()=>t.abort(WE5),e);return{signal:t.signal,abortId:r}}function pyE(...e){let t=e.length===1&&Array.isArray(e[0])?e[0]:e,r=new AbortController;for(let i of t){if(i.aborted){r.abort(i?.reason);break}i.addEventListener("abort",()=>r.abort(i?.reason),{signal:r.signal})}return r.signal}var GE5=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},_yE=(e,t,r,i,n,a,o,c,d)=>GE5(void 0,void 0,void 0,function*(){let s=[],u;if(a!=null){let{signal:_,abortId:h}=dyE(a);u=h,s.push(_)}o!=null&&s.push(o);let l=pyE(s),p=yield e(t,{method:r,headers:i,body:n,signal:l,credentials:c?"include":void 0,duplex:d});return u!=null&&clearTimeout(u),p});var uBo;typeof globalThis.Headers<"u"?uBo=globalThis.Headers:uBo=class hyE{constructor(t){if(this.headers=new Map,t)if(t instanceof hyE)t.forEach((r,i)=>this.append(i,r));else if(Array.isArray(t))for(let[r,i]of t)if(typeof r=="string"&&typeof i=="string")this.append(r,i);else throw new TypeError("Each header entry must be a [string, string] tuple");else for(let[r,i]of Object.entries(t))if(typeof i=="string")this.append(r,i);else throw new TypeError("Header values must be strings")}append(t,r){let i=t.toLowerCase(),n=this.headers.get(i)||[];this.headers.set(i,[...n,r])}delete(t){let r=t.toLowerCase();this.headers.delete(r)}get(t){let r=t.toLowerCase(),i=this.headers.get(r);return i?i.join(", "):null}has(t){let r=t.toLowerCase();return this.headers.has(r)}set(t,r){let i=t.toLowerCase();this.headers.set(i,[r])}forEach(t,r){let i=r?t.bind(r):t;this.headers.forEach((n,a)=>i(n.join(", "),a,this))}getSetCookie(){return this.headers.get("set-cookie")||[]}*entries(){for(let[t,r]of this.headers.entries())yield[t,r.join(", ")]}*keys(){yield*this.headers.keys()}*values(){for(let t of this.headers.values())yield t.join(", ")}[Symbol.iterator](){return this.entries()}};var Mup={headers:new uBo,redirected:!1,status:499,statusText:"Client Closed Request",type:"error",url:""},Dup={headers:new uBo,redirected:!1,status:0,statusText:"Unknown Error",type:"error",url:""};function Bup(e){return{headers:e.headers,redirected:e.redirected,status:e.status,statusText:e.statusText,type:e.type,url:e.url}}var HE5=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})};function xE5(e){let t=1+(Math.random()*2-1)*.2;return e*t}function yyE(e){return HE5(this,arguments,void 0,function*(t,r=2){let i=yield t();for(let n=0;n<r&&([408,429].includes(i.status)||i.status>=500);++n){let a=Math.min(1e3*Math.pow(2,n),6e4),o=xE5(a);yield new Promise(c=>setTimeout(c,o)),i=yield t()}return i})}var KE5=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},ei={get:e=>KE5(void 0,void 0,void 0,function*(){return typeof e=="function"?e():e})};var Iup=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})};function JE5(e){return Iup(this,void 0,void 0,function*(){let t={};if(e.body!==void 0&&e.contentType!=null&&(t["Content-Type"]=e.contentType),e.headers==null)return t;for(let[r,i]of Object.entries(e.headers)){let n=yield ei.get(i);if(typeof n=="string"){t[r]=n;continue}n!=null&&(t[r]=`${n}`)}return t})}function $E5(e){return Iup(this,void 0,void 0,function*(){let t=oyE(e.url,e.queryParameters),r=yield fyE({body:e.body,type:e.requestType==="json"?"json":"other"}),i=yield lyE();try{let n=yield yyE(()=>Iup(this,void 0,void 0,function*(){return _yE(i,t,e.method,yield JE5(e),r,e.timeoutMs,e.abortSignal,e.withCredentials,e.duplex)}),e.maxRetries);return n.status>=200&&n.status<400?{ok:!0,body:yield $Ks(n,e.responseType),headers:n.headers,rawResponse:Bup(n)}:{ok:!1,error:{reason:"status-code",statusCode:n.status,body:yield cyE(n)},rawResponse:Bup(n)}}catch(n){return e.abortSignal!=null&&e.abortSignal.aborted?{ok:!1,error:{reason:"unknown",errorMessage:"The user aborted a request"},rawResponse:Mup}:n instanceof Error&&n.name==="AbortError"?{ok:!1,error:{reason:"timeout"},rawResponse:Mup}:n instanceof Error?{ok:!1,error:{reason:"unknown",errorMessage:n.message},rawResponse:Dup}:{ok:!1,error:{reason:"unknown",errorMessage:rNa(n)},rawResponse:Dup}}})}var iu=$E5;var YE5=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},zo=class e extends Promise{constructor(t){super(r=>{r(void 0)}),this.innerPromise=t}static fromFunction(t,...r){return new e(t(...r))}static interceptFunction(t){return(...r)=>e.fromPromise(t(...r))}static fromPromise(t){return new e(t)}static fromExecutor(t){let r=new Promise(t);return new e(r)}static fromResult(t){let r=Promise.resolve(t);return new e(r)}unwrap(){return this.unwrappedPromise||(this.unwrappedPromise=this.innerPromise.then(({data:t})=>t)),this.unwrappedPromise}then(t,r){return this.unwrap().then(t,r)}catch(t){return this.unwrap().catch(t)}finally(t){return this.unwrap().finally(t)}withRawResponse(){return YE5(this,void 0,void 0,function*(){return yield this.innerPromise})}};var YKs=XE5();function XE5(){var e,t,r,i,n;return typeof window<"u"&&typeof window.document<"u"?{type:"browser",version:window.navigator.userAgent}:typeof globalThis<"u"&&((e=globalThis?.navigator)===null||e===void 0?void 0:e.userAgent)==="Cloudflare-Workers"?{type:"workerd"}:typeof EdgeRuntime=="string"?{type:"edge-runtime"}:typeof self=="object"&&typeof self?.importScripts=="function"&&(((t=self.constructor)===null||t===void 0?void 0:t.name)==="DedicatedWorkerGlobalScope"||((r=self.constructor)===null||r===void 0?void 0:r.name)==="ServiceWorkerGlobalScope"||((i=self.constructor)===null||i===void 0?void 0:i.name)==="SharedWorkerGlobalScope")?{type:"web-worker"}:typeof Deno<"u"&&typeof Deno.version<"u"&&typeof Deno.version.deno<"u"?{type:"deno",version:Deno.version.deno}:typeof Bun<"u"&&typeof Bun.version<"u"?{type:"bun",version:Bun.version}:typeof process<"u"&&"version"in process&&!!process.version&&"versions"in process&&!!(!((n=process.versions)===null||n===void 0)&&n.node)?{type:"node",version:process.versions.node,parsedVersion:Number(process.versions.node.split(".")[0])}:typeof navigator<"u"&&navigator?.product==="ReactNative"?{type:"react-native"}:{type:"unknown"}}var Go={};Zt(Go,{join:()=>vyE,toQueryString:()=>JKs});function vyE(e,...t){if(!e)return"";if(t.length===0)return e;if(e.includes("://")){let r;try{r=new URL(e)}catch{return byE(e,...t)}let i=t[t.length-1],n=i&&i.endsWith("/");for(let a of t){let o=OyE(a);o&&(r.pathname=gyE(r.pathname,o))}return n&&!r.pathname.endsWith("/")&&(r.pathname+="/"),r.toString()}return byE(e,...t)}function byE(e,...t){if(t.length===0)return e;let r=e,i=t[t.length-1],n=i&&i.endsWith("/");for(let a of t){let o=OyE(a);o&&(r=gyE(r,o))}return n&&!r.endsWith("/")&&(r+="/"),r}function gyE(e,t){return e.endsWith("/")?e+t:e+"/"+t}function OyE(e){if(!e)return e;let t=0,r=e.length;return e.startsWith("/")&&(t=1),e.endsWith("/")&&(r=e.length-1),t===0&&r===e.length?e:e.slice(t,r)}function Ho(...e){let t={};for(let[r,i]of e.filter(n=>n!=null).flatMap(n=>Object.entries(n)))i!=null?t[r]=i:r in t&&delete t[r];return t}function vu(...e){let t={};for(let[r,i]of e.filter(n=>n!=null).flatMap(n=>Object.entries(n)))i!=null&&(t[r]=i);return t}var gu={Production:"https://fai.buildwithfern.com",Development:"https://fai-dev.buildwithfern.com",Local:"http://localhost:8080"};var mxn=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},XKs=class{constructor(t={}){this._options=t}getAnalyticsHistogram(t,r={},i){return zo.fromPromise(this.__getAnalyticsHistogram(t,r,i))}__getAnalyticsHistogram(t){return mxn(this,arguments,void 0,function*(r,i={},n){var a,o,c;let{start_date:d,end_date:s,group_by:u}=i,l={};d!=null&&(l.start_date=d),s!=null&&(l.end_date=s),u!=null&&(l.group_by=u);let p=Ho((a=this._options)===null||a===void 0?void 0:a.headers,vu({Authorization:yield this._getAuthorizationHeader()}),n?.headers),_=yield iu({url:Go.join((c=(o=yield ei.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ei.get(this._options.environment))!==null&&c!==void 0?c:gu.Production,`analytics/histogram/${encodeURIComponent(r)}`),method:"GET",headers:p,queryParameters:Object.assign(Object.assign({},l),n?.queryParams),timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(_.ok)return{data:_.body,rawResponse:_.rawResponse};if(_.error.reason==="status-code")switch(_.error.statusCode){case 422:throw new zs(_.error.body,_.rawResponse);default:throw new _r({statusCode:_.error.statusCode,body:_.error.body,rawResponse:_.rawResponse})}switch(_.error.reason){case"non-json":throw new _r({statusCode:_.error.statusCode,body:_.error.rawBody,rawResponse:_.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /analytics/histogram/{domain}.");case"unknown":throw new _r({message:_.error.errorMessage,rawResponse:_.rawResponse})}})}generateAllInsights(t={},r){return zo.fromPromise(this.__generateAllInsights(t,r))}__generateAllInsights(){return mxn(this,arguments,void 0,function*(t={},r){var i,n,a;let{start_date:o,end_date:c}=t,d={};o!=null&&(d.start_date=o),c!=null&&(d.end_date=c);let s=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),u=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"analytics/insights/generate_all"),method:"POST",headers:s,queryParameters:Object.assign(Object.assign({},d),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(u.ok)return{data:u.body,rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 422:throw new zs(u.error.body,u.rawResponse);default:throw new _r({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new _r({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /analytics/insights/generate_all.");case"unknown":throw new _r({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}triggerScheduledInsightsGeneration(t){return zo.fromPromise(this.__triggerScheduledInsightsGeneration(t))}__triggerScheduledInsightsGeneration(t){return mxn(this,void 0,void 0,function*(){var r,i,n;let a=Ho((r=this._options)===null||r===void 0?void 0:r.headers,vu({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield iu({url:Go.join((n=(i=yield ei.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ei.get(this._options.environment))!==null&&n!==void 0?n:gu.Production,"analytics/insights/trigger_scheduled"),method:"POST",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new _r({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new _r({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /analytics/insights/trigger_scheduled.");case"unknown":throw new _r({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}getQueryInsights(t,r){return zo.fromPromise(this.__getQueryInsights(t,r))}__getQueryInsights(t,r){return mxn(this,void 0,void 0,function*(){var i,n,a;let o=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,`analytics/insights/${encodeURIComponent(t)}`),method:"GET",headers:o,queryParameters:r?.queryParams,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new zs(c.error.body,c.rawResponse);default:throw new _r({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new _r({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /analytics/insights/{domain}.");case"unknown":throw new _r({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}getSchedulerStatus(t){return zo.fromPromise(this.__getSchedulerStatus(t))}__getSchedulerStatus(t){return mxn(this,void 0,void 0,function*(){var r,i,n;let a=Ho((r=this._options)===null||r===void 0?void 0:r.headers,vu({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield iu({url:Go.join((n=(i=yield ei.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ei.get(this._options.environment))!==null&&n!==void 0?n:gu.Production,"analytics/scheduler/status"),method:"GET",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new _r({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new _r({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /analytics/scheduler/status.");case"unknown":throw new _r({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}getConversationResolution(t,r={},i){return zo.fromPromise(this.__getConversationResolution(t,r,i))}__getConversationResolution(t){return mxn(this,arguments,void 0,function*(r,i={},n){var a,o,c;let{start_date:d,end_date:s}=i,u={};d!=null&&(u.start_date=d),s!=null&&(u.end_date=s);let l=Ho((a=this._options)===null||a===void 0?void 0:a.headers,vu({Authorization:yield this._getAuthorizationHeader()}),n?.headers),p=yield iu({url:Go.join((c=(o=yield ei.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ei.get(this._options.environment))!==null&&c!==void 0?c:gu.Production,`analytics/resolution/${encodeURIComponent(r)}`),method:"GET",headers:l,queryParameters:Object.assign(Object.assign({},u),n?.queryParams),timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(p.ok)return{data:p.body,rawResponse:p.rawResponse};if(p.error.reason==="status-code")switch(p.error.statusCode){case 422:throw new zs(p.error.body,p.rawResponse);default:throw new _r({statusCode:p.error.statusCode,body:p.error.body,rawResponse:p.rawResponse})}switch(p.error.reason){case"non-json":throw new _r({statusCode:p.error.statusCode,body:p.error.rawBody,rawResponse:p.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /analytics/resolution/{domain}.");case"unknown":throw new _r({message:p.error.errorMessage,rawResponse:p.rawResponse})}})}_getAuthorizationHeader(){return mxn(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var AyE=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},ZKs=class{constructor(t={}){this._options=t}postChatCompletion(t,r,i){return zo.fromPromise(this.__postChatCompletion(t,r,i))}__postChatCompletion(t,r,i){return AyE(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`chat/${encodeURIComponent(t)}`),method:"POST",headers:c,contentType:"application/json",queryParameters:i?.queryParams,requestType:"json",body:r,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /chat/{domain}.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}_getAuthorizationHeader(){return AyE(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var myE=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},kKs=class{constructor(t={}){this._options=t}getConversationById(t,r,i){return zo.fromPromise(this.__getConversationById(t,r,i))}__getConversationById(t,r,i){return myE(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`conversation/${encodeURIComponent(t)}/${encodeURIComponent(r)}`),method:"GET",headers:c,queryParameters:i?.queryParams,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /conversation/{domain}/{conversation_id}.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}_getAuthorizationHeader(){return myE(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var Cup=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},eJs=class{constructor(t={}){this._options=t}createDiscordIntegration(t,r){return zo.fromPromise(this.__createDiscordIntegration(t,r))}__createDiscordIntegration(t,r){return Cup(this,void 0,void 0,function*(){var i,n,a;let{domain:o}=t,c={};c.domain=o;let d=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),s=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"discord/install"),method:"POST",headers:d,queryParameters:Object.assign(Object.assign({},c),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new zs(s.error.body,s.rawResponse);default:throw new _r({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new _r({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /discord/install.");case"unknown":throw new _r({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}handleDiscordInstallCallback(t){return zo.fromPromise(this.__handleDiscordInstallCallback(t))}__handleDiscordInstallCallback(t){return Cup(this,void 0,void 0,function*(){var r,i,n;let a=Ho((r=this._options)===null||r===void 0?void 0:r.headers,vu({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield iu({url:Go.join((n=(i=yield ei.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ei.get(this._options.environment))!==null&&n!==void 0?n:gu.Production,"discord/install/callback"),method:"GET",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new _r({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new _r({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /discord/install/callback.");case"unknown":throw new _r({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}_getAuthorizationHeader(){return Cup(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var a9i=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},tJs=class{constructor(t={}){this._options=t}createDocument(t,r,i){return zo.fromPromise(this.__createDocument(t,r,i))}__createDocument(t,r,i){return a9i(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`document/${encodeURIComponent(t)}/create`),method:"POST",headers:c,contentType:"application/json",queryParameters:i?.queryParams,requestType:"json",body:r,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /document/{domain}/create.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}batchCreateDocument(t,r,i){return zo.fromPromise(this.__batchCreateDocument(t,r,i))}__batchCreateDocument(t,r,i){return a9i(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`document/${encodeURIComponent(t)}/batch-create`),method:"POST",headers:c,contentType:"application/json",queryParameters:i?.queryParams,requestType:"json",body:r,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /document/{domain}/batch-create.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}getDocumentById(t,r,i){return zo.fromPromise(this.__getDocumentById(t,r,i))}__getDocumentById(t,r,i){return a9i(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`document/${encodeURIComponent(t)}/${encodeURIComponent(r)}`),method:"GET",headers:c,queryParameters:i?.queryParams,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /document/{domain}/{document_id}.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}updateDocument(t,r,i={},n){return zo.fromPromise(this.__updateDocument(t,r,i,n))}__updateDocument(t,r){return a9i(this,arguments,void 0,function*(i,n,a={},o){var c,d,s;let u=Ho((c=this._options)===null||c===void 0?void 0:c.headers,vu({Authorization:yield this._getAuthorizationHeader()}),o?.headers),l=yield iu({url:Go.join((s=(d=yield ei.get(this._options.baseUrl))!==null&&d!==void 0?d:yield ei.get(this._options.environment))!==null&&s!==void 0?s:gu.Production,`document/${encodeURIComponent(i)}/${encodeURIComponent(n)}`),method:"PATCH",headers:u,contentType:"application/json",queryParameters:o?.queryParams,requestType:"json",body:a,timeoutMs:o?.timeoutInSeconds!=null?o.timeoutInSeconds*1e3:6e4,maxRetries:o?.maxRetries,abortSignal:o?.abortSignal});if(l.ok)return{data:l.body,rawResponse:l.rawResponse};if(l.error.reason==="status-code")switch(l.error.statusCode){case 422:throw new zs(l.error.body,l.rawResponse);default:throw new _r({statusCode:l.error.statusCode,body:l.error.body,rawResponse:l.rawResponse})}switch(l.error.reason){case"non-json":throw new _r({statusCode:l.error.statusCode,body:l.error.rawBody,rawResponse:l.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling PATCH /document/{domain}/{document_id}.");case"unknown":throw new _r({message:l.error.errorMessage,rawResponse:l.rawResponse})}})}deleteDocumentById(t,r,i){return zo.fromPromise(this.__deleteDocumentById(t,r,i))}__deleteDocumentById(t,r,i){return a9i(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`document/${encodeURIComponent(t)}/delete`),method:"DELETE",headers:c,contentType:"application/json",queryParameters:i?.queryParams,requestType:"json",body:r,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling DELETE /document/{domain}/delete.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}batchDeleteDocument(t,r,i){return zo.fromPromise(this.__batchDeleteDocument(t,r,i))}__batchDeleteDocument(t,r,i){return a9i(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`document/${encodeURIComponent(t)}/batch-delete`),method:"DELETE",headers:c,contentType:"application/json",queryParameters:i?.queryParams,requestType:"json",body:r,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling DELETE /document/{domain}/batch-delete.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}getDocuments(t,r={},i){return zo.fromPromise(this.__getDocuments(t,r,i))}__getDocuments(t){return a9i(this,arguments,void 0,function*(r,i={},n){var a,o,c;let{page:d,limit:s}=i,u={};d!=null&&(u.page=d.toString()),s!=null&&(u.limit=s.toString());let l=Ho((a=this._options)===null||a===void 0?void 0:a.headers,vu({Authorization:yield this._getAuthorizationHeader()}),n?.headers),p=yield iu({url:Go.join((c=(o=yield ei.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ei.get(this._options.environment))!==null&&c!==void 0?c:gu.Production,`document/${encodeURIComponent(r)}`),method:"GET",headers:l,queryParameters:Object.assign(Object.assign({},u),n?.queryParams),timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(p.ok)return{data:p.body,rawResponse:p.rawResponse};if(p.error.reason==="status-code")switch(p.error.statusCode){case 422:throw new zs(p.error.body,p.rawResponse);default:throw new _r({statusCode:p.error.statusCode,body:p.error.body,rawResponse:p.rawResponse})}switch(p.error.reason){case"non-json":throw new _r({statusCode:p.error.statusCode,body:p.error.rawBody,rawResponse:p.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /document/{domain}.");case"unknown":throw new _r({message:p.error.errorMessage,rawResponse:p.rawResponse})}})}deleteAllDocuments(t,r){return zo.fromPromise(this.__deleteAllDocuments(t,r))}__deleteAllDocuments(t,r){return a9i(this,void 0,void 0,function*(){var i,n,a;let o=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,`document/${encodeURIComponent(t)}/delete-all`),method:"DELETE",headers:o,queryParameters:r?.queryParams,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new zs(c.error.body,c.rawResponse);default:throw new _r({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new _r({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling DELETE /document/{domain}/delete-all.");case"unknown":throw new _r({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}_getAuthorizationHeader(){return a9i(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var rJs=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},iJs=class{constructor(t={}){this._options=t}createEditingSession(t,r){return zo.fromPromise(this.__createEditingSession(t,r))}__createEditingSession(t,r){return rJs(this,void 0,void 0,function*(){var i,n,a;let o=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"editing-sessions"),method:"POST",headers:o,contentType:"application/json",queryParameters:r?.queryParams,requestType:"json",body:t,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new zs(c.error.body,c.rawResponse);default:throw new _r({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new _r({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /editing-sessions.");case"unknown":throw new _r({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}getEditingSession(t,r){return zo.fromPromise(this.__getEditingSession(t,r))}__getEditingSession(t,r){return rJs(this,void 0,void 0,function*(){var i,n,a;let o=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,`editing-sessions/${encodeURIComponent(t)}`),method:"GET",headers:o,queryParameters:r?.queryParams,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new zs(c.error.body,c.rawResponse);default:throw new _r({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new _r({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /editing-sessions/{editing_id}.");case"unknown":throw new _r({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}updateEditingSession(t,r={},i){return zo.fromPromise(this.__updateEditingSession(t,r,i))}__updateEditingSession(t){return rJs(this,arguments,void 0,function*(r,i={},n){var a,o,c;let d=Ho((a=this._options)===null||a===void 0?void 0:a.headers,vu({Authorization:yield this._getAuthorizationHeader()}),n?.headers),s=yield iu({url:Go.join((c=(o=yield ei.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ei.get(this._options.environment))!==null&&c!==void 0?c:gu.Production,`editing-sessions/${encodeURIComponent(r)}`),method:"PUT",headers:d,contentType:"application/json",queryParameters:n?.queryParams,requestType:"json",body:i,timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new zs(s.error.body,s.rawResponse);default:throw new _r({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new _r({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling PUT /editing-sessions/{editing_id}.");case"unknown":throw new _r({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}_getAuthorizationHeader(){return rJs(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var qup=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},nJs=class{constructor(t={}){this._options=t}createFeedback(t,r,i){return zo.fromPromise(this.__createFeedback(t,r,i))}__createFeedback(t,r,i){return qup(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`feedback/${encodeURIComponent(t)}`),method:"POST",headers:c,contentType:"application/json",queryParameters:i?.queryParams,requestType:"json",body:r,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /feedback/{domain}.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}getFeedbackById(t,r,i){return zo.fromPromise(this.__getFeedbackById(t,r,i))}__getFeedbackById(t,r,i){return qup(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`feedback/${encodeURIComponent(t)}/${encodeURIComponent(r)}`),method:"GET",headers:c,queryParameters:i?.queryParams,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /feedback/{domain}/{conversation_id}.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}_getAuthorizationHeader(){return qup(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var iNa=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},aJs=class{constructor(t={}){this._options=t}createGuidance(t,r,i){return zo.fromPromise(this.__createGuidance(t,r,i))}__createGuidance(t,r,i){return iNa(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`guidance/${encodeURIComponent(t)}/create`),method:"POST",headers:c,contentType:"application/json",queryParameters:i?.queryParams,requestType:"json",body:r,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /guidance/{domain}/create.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}getGuidanceById(t,r,i){return zo.fromPromise(this.__getGuidanceById(t,r,i))}__getGuidanceById(t,r,i){return iNa(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`guidance/${encodeURIComponent(t)}/${encodeURIComponent(r)}`),method:"GET",headers:c,queryParameters:i?.queryParams,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /guidance/{domain}/{guidance_id}.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}deleteGuidanceById(t,r,i){return zo.fromPromise(this.__deleteGuidanceById(t,r,i))}__deleteGuidanceById(t,r,i){return iNa(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`guidance/${encodeURIComponent(t)}/${encodeURIComponent(r)}`),method:"DELETE",headers:c,queryParameters:i?.queryParams,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling DELETE /guidance/{domain}/{guidance_id}.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}update(t,r,i={},n){return zo.fromPromise(this.__update(t,r,i,n))}__update(t,r){return iNa(this,arguments,void 0,function*(i,n,a={},o){var c,d,s;let u=Ho((c=this._options)===null||c===void 0?void 0:c.headers,vu({Authorization:yield this._getAuthorizationHeader()}),o?.headers),l=yield iu({url:Go.join((s=(d=yield ei.get(this._options.baseUrl))!==null&&d!==void 0?d:yield ei.get(this._options.environment))!==null&&s!==void 0?s:gu.Production,`guidance/${encodeURIComponent(i)}/${encodeURIComponent(n)}`),method:"PATCH",headers:u,contentType:"application/json",queryParameters:o?.queryParams,requestType:"json",body:a,timeoutMs:o?.timeoutInSeconds!=null?o.timeoutInSeconds*1e3:6e4,maxRetries:o?.maxRetries,abortSignal:o?.abortSignal});if(l.ok)return{data:l.body,rawResponse:l.rawResponse};if(l.error.reason==="status-code")switch(l.error.statusCode){case 422:throw new zs(l.error.body,l.rawResponse);default:throw new _r({statusCode:l.error.statusCode,body:l.error.body,rawResponse:l.rawResponse})}switch(l.error.reason){case"non-json":throw new _r({statusCode:l.error.statusCode,body:l.error.rawBody,rawResponse:l.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling PATCH /guidance/{domain}/{guidance_id}.");case"unknown":throw new _r({message:l.error.errorMessage,rawResponse:l.rawResponse})}})}getGuidances(t,r={},i){return zo.fromPromise(this.__getGuidances(t,r,i))}__getGuidances(t){return iNa(this,arguments,void 0,function*(r,i={},n){var a,o,c;let{page:d,limit:s}=i,u={};d!=null&&(u.page=d.toString()),s!=null&&(u.limit=s.toString());let l=Ho((a=this._options)===null||a===void 0?void 0:a.headers,vu({Authorization:yield this._getAuthorizationHeader()}),n?.headers),p=yield iu({url:Go.join((c=(o=yield ei.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ei.get(this._options.environment))!==null&&c!==void 0?c:gu.Production,`guidance/${encodeURIComponent(r)}`),method:"GET",headers:l,queryParameters:Object.assign(Object.assign({},u),n?.queryParams),timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(p.ok)return{data:p.body,rawResponse:p.rawResponse};if(p.error.reason==="status-code")switch(p.error.statusCode){case 422:throw new zs(p.error.body,p.rawResponse);default:throw new _r({statusCode:p.error.statusCode,body:p.error.body,rawResponse:p.rawResponse})}switch(p.error.reason){case"non-json":throw new _r({statusCode:p.error.statusCode,body:p.error.rawBody,rawResponse:p.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /guidance/{domain}.");case"unknown":throw new _r({message:p.error.errorMessage,rawResponse:p.rawResponse})}})}_getAuthorizationHeader(){return iNa(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var PyE=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},oJs=class{constructor(t={}){this._options=t}check(t){return zo.fromPromise(this.__check(t))}__check(t){return PyE(this,void 0,void 0,function*(){var r,i,n;let a=Ho((r=this._options)===null||r===void 0?void 0:r.headers,vu({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield iu({url:Go.join((n=(i=yield ei.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ei.get(this._options.environment))!==null&&n!==void 0?n:gu.Production,"health"),method:"GET",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new _r({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new _r({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /health.");case"unknown":throw new _r({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}_getAuthorizationHeader(){return PyE(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var uJs=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},sJs=class{constructor(t={}){this._options=t}reconstructQueryIndex(t,r){return zo.fromPromise(this.__reconstructQueryIndex(t,r))}__reconstructQueryIndex(t,r){return uJs(this,void 0,void 0,function*(){var i,n,a;let o=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,`index/${encodeURIComponent(t)}/reconstruct`),method:"POST",headers:o,queryParameters:r?.queryParams,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new zs(c.error.body,c.rawResponse);default:throw new _r({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new _r({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /index/{domain}/reconstruct.");case"unknown":throw new _r({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}syncIndexToQueryIndex(t,r,i){return zo.fromPromise(this.__syncIndexToQueryIndex(t,r,i))}__syncIndexToQueryIndex(t,r,i){return uJs(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`index/${encodeURIComponent(t)}/sync`),method:"POST",headers:c,contentType:"application/json",queryParameters:i?.queryParams,requestType:"json",body:r,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /index/{domain}/sync.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}getJobStatus(t,r){return zo.fromPromise(this.__getJobStatus(t,r))}__getJobStatus(t,r){return uJs(this,void 0,void 0,function*(){var i,n,a;let o=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,`jobs/${encodeURIComponent(t)}/status`),method:"GET",headers:o,queryParameters:r?.queryParams,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new zs(c.error.body,c.rawResponse);default:throw new _r({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new _r({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /jobs/{job_id}/status.");case"unknown":throw new _r({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}_getAuthorizationHeader(){return uJs(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var Tup=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},cJs=class{constructor(t={}){this._options=t}getMcpSemanticQuery(t,r,i){return zo.fromPromise(this.__getMcpSemanticQuery(t,r,i))}__getMcpSemanticQuery(t,r,i){return Tup(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`mcp/semantic/${encodeURIComponent(t)}`),method:"POST",headers:c,contentType:"application/json",queryParameters:i?.queryParams,requestType:"json",body:r,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /mcp/semantic/{domain}.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}getMcpBmfQuery(t,r,i){return zo.fromPromise(this.__getMcpBmfQuery(t,r,i))}__getMcpBmfQuery(t,r,i){return Tup(this,void 0,void 0,function*(){var n,a,o;let c=Ho((n=this._options)===null||n===void 0?void 0:n.headers,vu({Authorization:yield this._getAuthorizationHeader()}),i?.headers),d=yield iu({url:Go.join((o=(a=yield ei.get(this._options.baseUrl))!==null&&a!==void 0?a:yield ei.get(this._options.environment))!==null&&o!==void 0?o:gu.Production,`mcp/bmf/${encodeURIComponent(t)}`),method:"POST",headers:c,contentType:"application/json",queryParameters:i?.queryParams,requestType:"json",body:r,timeoutMs:i?.timeoutInSeconds!=null?i.timeoutInSeconds*1e3:6e4,maxRetries:i?.maxRetries,abortSignal:i?.abortSignal});if(d.ok)return{data:d.body,rawResponse:d.rawResponse};if(d.error.reason==="status-code")switch(d.error.statusCode){case 422:throw new zs(d.error.body,d.rawResponse);default:throw new _r({statusCode:d.error.statusCode,body:d.error.body,rawResponse:d.rawResponse})}switch(d.error.reason){case"non-json":throw new _r({statusCode:d.error.statusCode,body:d.error.rawBody,rawResponse:d.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /mcp/bmf/{domain}.");case"unknown":throw new _r({message:d.error.errorMessage,rawResponse:d.rawResponse})}})}_getAuthorizationHeader(){return Tup(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var Rup=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},lJs=class{constructor(t={}){this._options=t}createQuery(t,r){return zo.fromPromise(this.__createQuery(t,r))}__createQuery(t,r){return Rup(this,void 0,void 0,function*(){var i,n,a;let{domain:o,body:c}=t,d={};d.domain=o;let s=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),u=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"queries"),method:"POST",headers:s,contentType:"application/json",queryParameters:Object.assign(Object.assign({},d),r?.queryParams),requestType:"json",body:c,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(u.ok)return{data:u.body,rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 422:throw new zs(u.error.body,u.rawResponse);default:throw new _r({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new _r({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /queries.");case"unknown":throw new _r({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}getRecentQueries(t,r={},i){return zo.fromPromise(this.__getRecentQueries(t,r,i))}__getRecentQueries(t){return Rup(this,arguments,void 0,function*(r,i={},n){var a,o,c;let{page:d,limit:s,cutoff_time:u,include_assistant:l,start_date:p,end_date:_}=i,h={};d!=null&&(h.page=d.toString()),s!=null&&(h.limit=s.toString()),u!=null&&(h.cutoff_time=u),l!=null&&(h.include_assistant=l.toString()),p!=null&&(h.start_date=p),_!=null&&(h.end_date=_);let y=Ho((a=this._options)===null||a===void 0?void 0:a.headers,vu({Authorization:yield this._getAuthorizationHeader()}),n?.headers),b=yield iu({url:Go.join((c=(o=yield ei.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ei.get(this._options.environment))!==null&&c!==void 0?c:gu.Production,`queries/${encodeURIComponent(r)}`),method:"GET",headers:y,queryParameters:Object.assign(Object.assign({},h),n?.queryParams),timeoutMs:n?.timeoutInSeconds!=null?n.timeoutInSeconds*1e3:6e4,maxRetries:n?.maxRetries,abortSignal:n?.abortSignal});if(b.ok)return{data:b.body,rawResponse:b.rawResponse};if(b.error.reason==="status-code")switch(b.error.statusCode){case 422:throw new zs(b.error.body,b.rawResponse);default:throw new _r({statusCode:b.error.statusCode,body:b.error.body,rawResponse:b.rawResponse})}switch(b.error.reason){case"non-json":throw new _r({statusCode:b.error.statusCode,body:b.error.rawBody,rawResponse:b.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /queries/{domain}.");case"unknown":throw new _r({message:b.error.errorMessage,rawResponse:b.rawResponse})}})}_getAuthorizationHeader(){return Rup(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var zup=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},fJs=class{constructor(t={}){this._options=t}slackCallback(t,r,i,n,a){return zo.fromPromise(this.__slackCallback(t,r,i,n,a))}__slackCallback(t,r,i,n,a){return zup(this,void 0,void 0,function*(){var o,c,d;let s=Ho((o=this._options)===null||o===void 0?void 0:o.headers,vu({Authorization:yield this._getAuthorizationHeader()}),a?.headers),u=yield iu({url:Go.join((d=(c=yield ei.get(this._options.baseUrl))!==null&&c!==void 0?c:yield ei.get(this._options.environment))!==null&&d!==void 0?d:gu.Production,`scribe/callback/slack/${encodeURIComponent(t)}/${encodeURIComponent(r)}/${encodeURIComponent(i)}`),method:"POST",headers:s,contentType:"application/json",queryParameters:a?.queryParams,requestType:"json",body:n,timeoutMs:a?.timeoutInSeconds!=null?a.timeoutInSeconds*1e3:6e4,maxRetries:a?.maxRetries,abortSignal:a?.abortSignal});if(u.ok)return{data:u.body,rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 422:throw new zs(u.error.body,u.rawResponse);default:throw new _r({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new _r({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /scribe/callback/slack/{team_id}/{channel_id}/{thread_ts}.");case"unknown":throw new _r({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}editCallback(t,r,i,n,a){return zo.fromPromise(this.__editCallback(t,r,i,n,a))}__editCallback(t,r,i,n,a){return zup(this,void 0,void 0,function*(){var o,c,d;let s=Ho((o=this._options)===null||o===void 0?void 0:o.headers,vu({Authorization:yield this._getAuthorizationHeader()}),a?.headers),u=yield iu({url:Go.join((d=(c=yield ei.get(this._options.baseUrl))!==null&&c!==void 0?c:yield ei.get(this._options.environment))!==null&&d!==void 0?d:gu.Production,`scribe/callback/slack/edit/${encodeURIComponent(t)}/${encodeURIComponent(r)}/${encodeURIComponent(i)}`),method:"POST",headers:s,contentType:"application/json",queryParameters:a?.queryParams,requestType:"json",body:n,timeoutMs:a?.timeoutInSeconds!=null?a.timeoutInSeconds*1e3:6e4,maxRetries:a?.maxRetries,abortSignal:a?.abortSignal});if(u.ok)return{data:u.body,rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 422:throw new zs(u.error.body,u.rawResponse);default:throw new _r({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new _r({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /scribe/callback/slack/edit/{team_id}/{channel_id}/{thread_ts}.");case"unknown":throw new _r({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}_getAuthorizationHeader(){return zup(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var gRi=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},dJs=class{constructor(t={}){this._options=t}getSettings(t,r){return zo.fromPromise(this.__getSettings(t,r))}__getSettings(t,r){return gRi(this,void 0,void 0,function*(){var i,n,a;let{domain:o}=t,c={};c.domain=o;let d=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),s=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"settings/ask-ai"),method:"GET",headers:d,queryParameters:Object.assign(Object.assign({},c),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new zs(s.error.body,s.rawResponse);default:throw new _r({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new _r({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /settings/ask-ai.");case"unknown":throw new _r({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}getDocsSettings(t,r){return zo.fromPromise(this.__getDocsSettings(t,r))}__getDocsSettings(t,r){return gRi(this,void 0,void 0,function*(){var i,n,a;let{domain:o}=t,c={};c.domain=o;let d=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),s=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"settings/ask-ai/docs"),method:"GET",headers:d,queryParameters:Object.assign(Object.assign({},c),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new zs(s.error.body,s.rawResponse);default:throw new _r({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new _r({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /settings/ask-ai/docs.");case"unknown":throw new _r({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}getSlackSettings(t,r){return zo.fromPromise(this.__getSlackSettings(t,r))}__getSlackSettings(t,r){return gRi(this,void 0,void 0,function*(){var i,n,a;let{domain:o}=t,c={};c.domain=o;let d=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),s=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"settings/ask-ai/slack"),method:"GET",headers:d,queryParameters:Object.assign(Object.assign({},c),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new zs(s.error.body,s.rawResponse);default:throw new _r({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new _r({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /settings/ask-ai/slack.");case"unknown":throw new _r({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}getDiscordSettings(t,r){return zo.fromPromise(this.__getDiscordSettings(t,r))}__getDiscordSettings(t,r){return gRi(this,void 0,void 0,function*(){var i,n,a;let{domain:o}=t,c={};c.domain=o;let d=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),s=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"settings/ask-ai/discord"),method:"GET",headers:d,queryParameters:Object.assign(Object.assign({},c),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new zs(s.error.body,s.rawResponse);default:throw new _r({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new _r({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /settings/ask-ai/discord.");case"unknown":throw new _r({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}enableAskAi(t,r){return zo.fromPromise(this.__enableAskAi(t,r))}__enableAskAi(t,r){return gRi(this,void 0,void 0,function*(){var i,n,a;let o=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"settings/ask-ai/enable"),method:"POST",headers:o,contentType:"application/json",queryParameters:r?.queryParams,requestType:"json",body:t,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new zs(c.error.body,c.rawResponse);default:throw new _r({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new _r({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /settings/ask-ai/enable.");case"unknown":throw new _r({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}toggleAskAi(t,r){return zo.fromPromise(this.__toggleAskAi(t,r))}__toggleAskAi(t,r){return gRi(this,void 0,void 0,function*(){var i,n,a;let{domain:o,org_name:c,preview:d,locations:s}=t,u={};u.domain=o,u.org_name=c,d!=null&&(u.preview=d.toString()),s!=null&&(Array.isArray(s)?u.locations=s.map(_=>_):u.locations=s);let l=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),p=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"settings/ask-ai/toggle"),method:"POST",headers:l,queryParameters:Object.assign(Object.assign({},u),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(p.ok)return{data:p.body,rawResponse:p.rawResponse};if(p.error.reason==="status-code")switch(p.error.statusCode){case 422:throw new zs(p.error.body,p.rawResponse);default:throw new _r({statusCode:p.error.statusCode,body:p.error.body,rawResponse:p.rawResponse})}switch(p.error.reason){case"non-json":throw new _r({statusCode:p.error.statusCode,body:p.error.rawBody,rawResponse:p.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /settings/ask-ai/toggle.");case"unknown":throw new _r({message:p.error.errorMessage,rawResponse:p.rawResponse})}})}reindexAskAi(t,r){return zo.fromPromise(this.__reindexAskAi(t,r))}__reindexAskAi(t,r){return gRi(this,void 0,void 0,function*(){var i,n,a;let{domain:o,org_name:c}=t,d={};d.domain=o,d.org_name=c;let s=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),u=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"settings/ask-ai/reindex"),method:"POST",headers:s,queryParameters:Object.assign(Object.assign({},d),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(u.ok)return{data:u.body,rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 422:throw new zs(u.error.body,u.rawResponse);default:throw new _r({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new _r({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /settings/ask-ai/reindex.");case"unknown":throw new _r({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}getToggleStatus(t,r){return zo.fromPromise(this.__getToggleStatus(t,r))}__getToggleStatus(t,r){return gRi(this,void 0,void 0,function*(){var i,n,a;let{domain:o}=t,c={};c.domain=o;let d=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),s=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"settings/ask-ai/toggle/status"),method:"GET",headers:d,queryParameters:Object.assign(Object.assign({},c),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new zs(s.error.body,s.rawResponse);default:throw new _r({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new _r({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /settings/ask-ai/toggle/status.");case"unknown":throw new _r({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}reindexPreviewCallback(t,r){return zo.fromPromise(this.__reindexPreviewCallback(t,r))}__reindexPreviewCallback(t,r){return gRi(this,void 0,void 0,function*(){var i,n,a;let o=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"settings/reindex-preview-callback"),method:"POST",headers:o,contentType:"application/json",queryParameters:r?.queryParams,requestType:"json",body:t,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new zs(c.error.body,c.rawResponse);default:throw new _r({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new _r({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /settings/reindex-preview-callback.");case"unknown":throw new _r({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}_getAuthorizationHeader(){return gRi(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var Fcn=function(e,t,r,i){function n(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(u){try{s(i.next(u))}catch(l){o(l)}}function d(u){try{s(i.throw(u))}catch(l){o(l)}}function s(u){u.done?a(u.value):n(u.value).then(c,d)}s((i=i.apply(e,t||[])).next())})},pJs=class{constructor(t={}){this._options=t}createSlackIntegration(t,r){return zo.fromPromise(this.__createSlackIntegration(t,r))}__createSlackIntegration(t,r){return Fcn(this,void 0,void 0,function*(){var i,n,a;let{domain:o}=t,c={};c.domain=o;let d=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),s=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"slack/install"),method:"POST",headers:d,queryParameters:Object.assign(Object.assign({},c),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new zs(s.error.body,s.rawResponse);default:throw new _r({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new _r({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /slack/install.");case"unknown":throw new _r({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}handleSlackEvents(t){return zo.fromPromise(this.__handleSlackEvents(t))}__handleSlackEvents(t){return Fcn(this,void 0,void 0,function*(){var r,i,n;let a=Ho((r=this._options)===null||r===void 0?void 0:r.headers,vu({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield iu({url:Go.join((n=(i=yield ei.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ei.get(this._options.environment))!==null&&n!==void 0?n:gu.Production,"slack/events"),method:"POST",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new _r({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new _r({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /slack/events.");case"unknown":throw new _r({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}handleSlackSlashCommands(t){return zo.fromPromise(this.__handleSlackSlashCommands(t))}__handleSlackSlashCommands(t){return Fcn(this,void 0,void 0,function*(){var r,i,n;let a=Ho((r=this._options)===null||r===void 0?void 0:r.headers,vu({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield iu({url:Go.join((n=(i=yield ei.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ei.get(this._options.environment))!==null&&n!==void 0?n:gu.Production,"slack/slash-commands"),method:"POST",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new _r({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new _r({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /slack/slash-commands.");case"unknown":throw new _r({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}handleSlackInteractions(t){return zo.fromPromise(this.__handleSlackInteractions(t))}__handleSlackInteractions(t){return Fcn(this,void 0,void 0,function*(){var r,i,n;let a=Ho((r=this._options)===null||r===void 0?void 0:r.headers,vu({Authorization:yield this._getAuthorizationHeader()}),t?.headers),o=yield iu({url:Go.join((n=(i=yield ei.get(this._options.baseUrl))!==null&&i!==void 0?i:yield ei.get(this._options.environment))!==null&&n!==void 0?n:gu.Production,"slack/interactions"),method:"POST",headers:a,queryParameters:t?.queryParams,timeoutMs:t?.timeoutInSeconds!=null?t.timeoutInSeconds*1e3:6e4,maxRetries:t?.maxRetries,abortSignal:t?.abortSignal});if(o.ok)return{data:o.body,rawResponse:o.rawResponse};if(o.error.reason==="status-code")throw new _r({statusCode:o.error.statusCode,body:o.error.body,rawResponse:o.rawResponse});switch(o.error.reason){case"non-json":throw new _r({statusCode:o.error.statusCode,body:o.error.rawBody,rawResponse:o.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling POST /slack/interactions.");case"unknown":throw new _r({message:o.error.errorMessage,rawResponse:o.rawResponse})}})}handleSlackOauthCallback(t,r){return zo.fromPromise(this.__handleSlackOauthCallback(t,r))}__handleSlackOauthCallback(t,r){return Fcn(this,void 0,void 0,function*(){var i,n,a;let{code:o,state:c}=t,d={};d.code=o,c!=null&&(d.state=c);let s=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),u=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"slack/oauth/callback"),method:"GET",headers:s,queryParameters:Object.assign(Object.assign({},d),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(u.ok)return{data:u.body,rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 422:throw new zs(u.error.body,u.rawResponse);default:throw new _r({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new _r({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /slack/oauth/callback.");case"unknown":throw new _r({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}getSlackInstallLink(t,r){return zo.fromPromise(this.__getSlackInstallLink(t,r))}__getSlackInstallLink(t,r){return Fcn(this,void 0,void 0,function*(){var i,n,a;let{domain:o}=t,c={};c.domain=o;let d=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),s=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,"slack/get-install"),method:"GET",headers:d,queryParameters:Object.assign(Object.assign({},c),r?.queryParams),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(s.ok)return{data:s.body,rawResponse:s.rawResponse};if(s.error.reason==="status-code")switch(s.error.statusCode){case 422:throw new zs(s.error.body,s.rawResponse);default:throw new _r({statusCode:s.error.statusCode,body:s.error.body,rawResponse:s.rawResponse})}switch(s.error.reason){case"non-json":throw new _r({statusCode:s.error.statusCode,body:s.error.rawBody,rawResponse:s.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /slack/get-install.");case"unknown":throw new _r({message:s.error.errorMessage,rawResponse:s.rawResponse})}})}listSlackIntegrations(t,r){return zo.fromPromise(this.__listSlackIntegrations(t,r))}__listSlackIntegrations(t,r){return Fcn(this,void 0,void 0,function*(){var i,n,a;let o=Ho((i=this._options)===null||i===void 0?void 0:i.headers,vu({Authorization:yield this._getAuthorizationHeader()}),r?.headers),c=yield iu({url:Go.join((a=(n=yield ei.get(this._options.baseUrl))!==null&&n!==void 0?n:yield ei.get(this._options.environment))!==null&&a!==void 0?a:gu.Production,`slack/integrations/${encodeURIComponent(t)}`),method:"GET",headers:o,queryParameters:r?.queryParams,timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:6e4,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(c.ok)return{data:c.body,rawResponse:c.rawResponse};if(c.error.reason==="status-code")switch(c.error.statusCode){case 422:throw new zs(c.error.body,c.rawResponse);default:throw new _r({statusCode:c.error.statusCode,body:c.error.body,rawResponse:c.rawResponse})}switch(c.error.reason){case"non-json":throw new _r({statusCode:c.error.statusCode,body:c.error.rawBody,rawResponse:c.rawResponse});case"timeout":throw new Ro("Timeout exceeded when calling GET /slack/integrations/{domain}.");case"unknown":throw new _r({message:c.error.errorMessage,rawResponse:c.rawResponse})}})}_getAuthorizationHeader(){return Fcn(this,void 0,void 0,function*(){let t=yield ei.get(this._options.token);if(t!=null)return`Bearer ${t}`})}};var sBo=class{constructor(t={}){this._options=Object.assign(Object.assign({},t),{headers:Ho({"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"@fern-api/fai-sdk","X-Fern-SDK-Version":"0.0.6-2ee1b7e28","X-Fern-Runtime":YKs.type,"X-Fern-Runtime-Version":YKs.version},t?.headers)})}get analytics(){var t;return(t=this._analytics)!==null&&t!==void 0?t:this._analytics=new XKs(this._options)}get chat(){var t;return(t=this._chat)!==null&&t!==void 0?t:this._chat=new ZKs(this._options)}get conversation(){var t;return(t=this._conversation)!==null&&t!==void 0?t:this._conversation=new kKs(this._options)}get discord(){var t;return(t=this._discord)!==null&&t!==void 0?t:this._discord=new eJs(this._options)}get document(){var t;return(t=this._document)!==null&&t!==void 0?t:this._document=new tJs(this._options)}get editingSessions(){var t;return(t=this._editingSessions)!==null&&t!==void 0?t:this._editingSessions=new iJs(this._options)}get feedback(){var t;return(t=this._feedback)!==null&&t!==void 0?t:this._feedback=new nJs(this._options)}get guidance(){var t;return(t=this._guidance)!==null&&t!==void 0?t:this._guidance=new aJs(this._options)}get health(){var t;return(t=this._health)!==null&&t!==void 0?t:this._health=new oJs(this._options)}get index(){var t;return(t=this._index)!==null&&t!==void 0?t:this._index=new sJs(this._options)}get mcp(){var t;return(t=this._mcp)!==null&&t!==void 0?t:this._mcp=new cJs(this._options)}get query(){var t;return(t=this._query)!==null&&t!==void 0?t:this._query=new lJs(this._options)}get scribe(){var t;return(t=this._scribe)!==null&&t!==void 0?t:this._scribe=new fJs(this._options)}get settings(){var t;return(t=this._settings)!==null&&t!==void 0?t:this._settings=new dJs(this._options)}get slack(){var t;return(t=this._slack)!==null&&t!==void 0?t:this._slack=new pJs(this._options)}};function jyE({token:e}){return new sBo({baseUrl:"https://fai.buildwithfern.com",token:e})}var lbE=ce(cbE(),1);var fbE=require("util"),FM5=(0,fbE.promisify)(lbE.default);async function dbE(e,t,r){let i=LFa(e,t),n=[];for(let a of i){let o=await Promise.all(a.map(async c=>{try{let d=await FM5(c);return d==null||d.height==null||d.width==null?void 0:{filePath:c,width:d.width,height:d.height,blurDataUrl:void 0}}catch(d){r.logger.error(`Failed to measure image size for ${c}. ${d?.message}`);return}}));n.push(...o.filter(As))}return new Map(n.map(a=>[a.filePath,a]))}async function isp(e,t,r){let i=new Array(t.length),n=new Set;for(let a=0;a<t.length;a++){let o=t[a];if(o===void 0)continue;let c=(async()=>{let d=await r(o,a);i[a]=d})().then(()=>{n.delete(c)});n.add(c),n.size>=e&&await Promise.race(n)}return await Promise.all(n),i}var QM5=10,pbE=10,GJs=parseInt(process.env.FERN_DOCS_ASSET_HASH_CONCURRENCY??"32",10);async function _bE(e){let t=await(0,nsp.readFile)(e);return(0,vbE.createHash)("sha256").update(new Uint8Array(t)).digest("hex")}async function gbE({token:e,organization:t,docsWorkspace:r,domain:i,customDomains:n,apiWorkspaces:a,ossWorkspaces:o,context:c,preview:d,editThisPage:s,isPrivate:u=!1,disableTemplates:l=!1,skipUpload:p=!1,withAiExamples:_=!0,targetAudiences:h}){let y=KVt({token:e.value}),b=u?{type:"private",authType:"sso"}:{type:"public"},v,O=n[0]??i,A=UM5(i),g=r.config.experimental?.dynamicSnippets,m=d||g,j=new b8t({domain:i,docsWorkspace:r,ossWorkspaces:o,apiWorkspaces:a,taskContext:c,editThisPage:s,uploadFiles:async U=>{let x=new Map(U.map(Xe=>[Xe.absoluteFilePath,Xe])),Pe=U.map(Xe=>({...Xe,mediaType:asp.lookup(Xe.absoluteFilePath)})).filter(Xe=>Xe.mediaType!==!1).filter(Xe=>xO.parse(Xe.mediaType)?.isImage()??!1).map(Xe=>Xe.absoluteFilePath),ve=await dbE(Pe,QM5,c);c.logger.debug(`Hashing ${ve.size} image files with concurrency ${GJs}...`);let G=performance.now(),H=Array.from(ve.values()),ue=(await isp(GJs,H,async Xe=>{let Sr=x.get(Xe.filePath);return Sr==null?null:{filePath:di.docs.v1.write.FilePath(Nzo(Sr.relativeFilePath)),width:Xe.width,height:Xe.height,blurDataUrl:Xe.blurDataUrl,alt:void 0,fileHash:await _bE(Sr.absoluteFilePath)}})).filter(Xe=>Xe!=null),Oe=performance.now()-G;c.logger.debug(`Hashed ${ue.length} images in ${Oe.toFixed(0)}ms`);let Qe=U.filter(({absoluteFilePath:Xe})=>!ve.has(Xe));c.logger.debug(`Hashing ${Qe.length} non-image files with concurrency ${GJs}...`);let se=performance.now(),ne=await isp(GJs,Qe,async Xe=>({path:di.docs.v1.write.FilePath(Nzo(Xe.relativeFilePath)),fileHash:await _bE(Xe.absoluteFilePath)})),$e=performance.now()-se;if(c.logger.debug(`Hashed ${ne.length} non-image files in ${$e.toFixed(0)}ms`),d){let Xe=await y.docs.v2.write.startDocsPreviewRegister({orgId:di.OrgId(t),authConfig:u?{type:"private",authType:"sso"}:{type:"public"},filepaths:ne,images:ue,basePath:A});if(Xe.ok){if(O=Xe.body.previewUrl,v=Xe.body.docsRegistrationId,c.logger.debug(`Received preview registration ID: ${v}`),p)c.logger.debug("Skip-upload mode: skipping file uploads for docs preview");else{let Sr=new Set(Xe.body.skippedFiles||[]),Wt=Object.fromEntries(Object.entries(Xe.body.uploadUrls).filter(([Jt])=>!Sr.has(Jt))),Qt=Object.keys(Wt).length,Vt=Sr.size;Qt>0?(c.logger.debug(`Uploading ${Qt} files (${Vt} skipped)...`),await hbE(Wt,r.absoluteFilePath,c,pbE)):c.logger.debug(`No files to upload (all ${Vt} up to date)`)}return ybE(Xe.body.uploadUrls,r.absoluteFilePath)}else return await bbE(Xe.error,c)}else{let Xe=await y.docs.v2.write.startDocsRegister({domain:i,customDomains:n,authConfig:b,apiId:di.ApiId(""),orgId:di.OrgId(t),filepaths:ne,images:ue});if(Xe.ok){v=Xe.body.docsRegistrationId,c.logger.debug(`Received production registration ID: ${v}`);let Sr=Xe.body.skippedFiles?.length||0;if(Sr>0&&c.logger.info(`Skipped ${Sr} unchanged file${Sr===1?"":"s"} (already uploaded)`),p)c.logger.debug("Skip-upload mode: skipping file uploads for docs");else{let Wt=new Set(Xe.body.skippedFiles||[]),Qt=Object.fromEntries(Object.entries(Xe.body.uploadUrls).filter(([Jt])=>!Wt.has(Jt))),Vt=Object.keys(Qt).length;Vt>0?(c.logger.info(`\u2191 Uploading ${Vt} files...`),await hbE(Qt,r.absoluteFilePath,c,pbE)):c.logger.info("No files to upload (all up to date)")}return ybE(Xe.body.uploadUrls,r.absoluteFilePath)}else return bbE(Xe.error,c)}},registerApi:async({ir:U,snippetsConfig:x,playgroundConfig:ee,apiName:Pe,workspace:ve})=>{let G=pH({ir:U,snippetsConfig:x,playgroundConfig:ee,context:c}),H=KM5(_,r.config.experimental?.aiExampleStyleInstructions);if(H&&ve){let ne=ve.getSources().find($e=>$e.type==="openapi")?.absoluteFilePath;G=await Nua(G,H,c,e,t,ne)}let Ee,ue=new Set;if(g){let Qe=await LM5({fdr:y,workspace:ve,organization:t,context:c,snippetsConfig:x});Qe&&Object.keys(Qe).length>0&&(Ee=Qe,ue=new Set(Object.keys(Qe)),c.logger.debug(`Using existing SDK dynamic IRs for: ${Object.keys(Qe).join(", ")}`));let se=await GM5({workspace:ve,organization:t,context:c,snippetsConfig:x,skipLanguages:ue});se&&(Ee={...Ee,...se})}let Oe=await y.api.v1.register.registerApiDefinition({orgId:di.OrgId(t),apiId:di.ApiId(U.apiName.originalName),definition:G,definitionV2:void 0,dynamicIRs:Ee});if(Oe.ok)return c.logger.debug(`Registered API Definition ${Pe}: ${Oe.body.apiDefinitionId}`),Oe.body.dynamicIRs&&Ee&&(p?c.logger.debug("Skip-upload mode: skipping dynamic IR uploads"):await HM5({dynamicIRs:Ee,dynamicIRUploadUrls:Oe.body.dynamicIRs,context:c,apiId:Oe.body.apiDefinitionId})),Oe.body.apiDefinitionId;switch(Oe.error.error){case"UnauthorizedError":case"UserNotInOrgError":return c.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:{let Qe=JM5(Oe.error);return c.logger.error(`FDR registerApiDefinition failed. Error details:
|
|
2017
|
-
${JSON.stringify(Qe,void 0,2)}`),Pe!=null?c.failAndThrow(`Failed to publish docs because API definition (${Pe}) could not be uploaded. Please contact support@buildwithfern.com`,Qe):c.failAndThrow("Failed to publish docs because API definition could not be uploaded. Please contact support@buildwithfern.com",Qe)}}},targetAudiences:h});c.logger.info("Resolving docs definition...");let M=performance.now(),w=await j.resolve(),D=performance.now()-M;if(r.config.settings?.substituteEnvVars){c.logger.debug("Applying environment variable substitution to docs definition...");let{jsFiles:U,...x}=w;w={...FT(x,{onError:Pe=>c.failAndThrow(Pe)},{substituteAsEmpty:!1}),jsFiles:U}}let B=Object.keys(w.pages).length,R=a.length,N=process.memoryUsage();if(c.logger.info(`Resolved docs definition in ${D.toFixed(0)}ms: ${B} pages${R?`, ${R} API workspaces`:""}`),c.logger.debug(`Memory after resolve: RSS=${(N.rss/1024/1024).toFixed(2)}MB, Heap=${(N.heapUsed/1024/1024).toFixed(2)}MB`),v==null)return c.failAndThrow("Failed to publish docs.","Docs registration ID is missing.");c.logger.info("Publishing docs to FDR...");let z=performance.now(),F=await y.docs.v2.write.finishDocsRegister(yG.DocsRegistrationId(v),{docsDefinition:w,excludeApis:!1});if(F.ok){let U=performance.now()-z;c.logger.debug(`Docs published to FDR in ${U.toFixed(0)}ms`);let x=mR(O);await xM5({docsDefinition:w,organization:t,token:e,url:x.replace("https://",""),context:c,fdr:y,isPreview:d,domain:i,customDomains:n});let ee=i9i(x,x);c.logger.info(It.green(`Published docs to ${ee}`))}else switch(F.error.error){case"UnauthorizedError":case"UserNotInOrgError":return c.failAndThrow("Insufficient permissions. Failed to publish docs to "+i);case"DocsRegistrationIdNotFound":return c.failAndThrow("Failed to publish docs to "+i,`Docs registration ID ${v} does not exist.`);default:return c.failAndThrow("Failed to publish docs to "+i,F.error)}}async function hbE(e,t,r,i){let n=Date.now(),a=Object.keys(e).length;r.logger.debug(`Start uploading ${a} files...`);let o=LFa(Object.entries(e),i),c=0;for(let s of o){await Promise.all(s.map(async([l,{uploadUrl:p}])=>{let _=Ze.of(l),h=$u(t,_);try{let y=asp.lookup(h);await RB.put(p,await(0,nsp.readFile)(h),{headers:{"Content-Type":y===!1?"application/octet-stream":y,"Cache-Control":"public, max-age=31536000, immutable"}})}catch(y){r.failAndThrow(`Failed to upload ${h}`,y)}}));let u=Date.now();c+=s.length,r.logger.debug(`Uploaded ${c}/${a} files in ${u-n}ms`)}let d=Date.now();r.logger.debug(`Finished uploading ${a} files in ${d-n}ms`)}function ybE(e,t){let r=[];for(let[i,n]of Object.entries(e)){let a=Ze.of(i),o=$u(t,a);r.push({relativeFilePath:a,absoluteFilePath:o,fileId:n.fileId})}return r}async function bbE(e,t){switch(await t.instrumentPostHogEvent({command:"docs-generation",properties:{error:JSON.stringify(e)}}),e.error){case"InvalidCustomDomainError":return t.failAndThrow("Your docs domain should end with docs.buildwithfern.com");case"InvalidDomainError":return t.failAndThrow("Please make sure that none of your custom domains are not overlapping (i.e. one is a substring of another)");case"UnauthorizedError":return t.failAndThrow("Please make sure that your FERN_TOKEN is set.");case"UserNotInOrgError":return t.failAndThrow("Please verify if you have access to the organization you are trying to publish the docs to. If you are not a member of the organization, please reach out to the organization owner.");case"UnavailableError":return t.failAndThrow("Failed to publish docs. Please try again later or reach out to Fern support at support@buildwithfern.com.");default:return t.failAndThrow("Failed to publish docs.",e)}}function UM5(e){try{return new URL(mR(e)).pathname}catch{return}}async function LM5({fdr:e,workspace:t,organization:r,context:i,snippetsConfig:n}){if(!t)return;let a=await VM5({fdr:e,workspace:t,snippetsConfig:n,context:i});if(Object.keys(a).length===0){i.logger.debug("[SDK Dynamic IR] No snippet configs found, skipping S3 check");return}try{let o=await e.api.v1.register.checkSdkDynamicIrExists({orgId:di.OrgId(r),snippetConfiguration:a});if(!o.ok||!o.body){i.logger.debug("[SDK Dynamic IR] API call failed or returned empty body");return}let c=o.body.existingDynamicIrs;if(Object.keys(c).length===0){i.logger.debug("[SDK Dynamic IR] No existing SDK dynamic IRs found in S3");return}let d={};for(let[s,u]of Object.entries(c))try{i.logger.debug(`Downloading existing SDK dynamic IR for ${s}...`);let l=await fetch(u.downloadUrl);if(l.ok){let p=await l.json();d[s]={dynamicIR:p},i.logger.debug(`Successfully downloaded SDK dynamic IR for ${s}`)}else i.logger.warn(`Failed to download SDK dynamic IR for ${s}: ${l.status}`)}catch(l){i.logger.warn(`Error downloading SDK dynamic IR for ${s}: ${l}`)}return Object.keys(d).length>0?d:void 0}catch(o){i.logger.debug(`Error checking for existing SDK dynamic IRs: ${o}`);return}}async function VM5({fdr:e,workspace:t,snippetsConfig:r,context:i}){let n={},a=[{language:"typescript",snippetName:r.typescriptSdk?.package,explicitVersion:r.typescriptSdk?.version},{language:"python",snippetName:r.pythonSdk?.package,explicitVersion:r.pythonSdk?.version},{language:"java",snippetName:r.javaSdk?.coordinate,explicitVersion:r.javaSdk?.version},{language:"go",snippetName:r.goSdk?.githubRepo,explicitVersion:r.goSdk?.version},{language:"csharp",snippetName:r.csharpSdk?.package,explicitVersion:r.csharpSdk?.version},{language:"ruby",snippetName:r.rubySdk?.gem,explicitVersion:r.rubySdk?.version},{language:"php",snippetName:r.phpSdk?.package,explicitVersion:r.phpSdk?.version},{language:"swift",snippetName:r.swiftSdk?.package,explicitVersion:r.swiftSdk?.version},{language:"rust",snippetName:r.rustSdk?.package,explicitVersion:r.rustSdk?.version}];for(let o of a){if(!o.snippetName)continue;let c=o.explicitVersion;c||(c=(await WM5({fdr:e,workspace:t,language:o.language,snippetName:o.snippetName,context:i}))?.version),n[o.language]={packageName:o.snippetName,version:c},c||i.logger.debug(`[SDK Dynamic IR] ${o.language}: no version specified, will use latest`)}return n}async function WM5({fdr:e,workspace:t,language:r,snippetName:i,context:n}){let a;switch(r){case"csharp":a="Csharp";break;case"go":a="Go";break;case"java":a="Java";break;case"python":a="Python";break;case"ruby":a="Ruby";break;case"typescript":a="TypeScript";break;case"php":a="Php";break;case"swift":a="Swift";break;default:return}let o,c,d;if(t.generatorsConfiguration?.groups){let s=[];for(let u of t.generatorsConfiguration.groups)for(let l of u.generators)if(l.language===r){let p=_n.getPackageName({generatorInvocation:l});p&&s.push(p),!c&&p&&(c=p,d=l.name,l.outputMode.type==="githubV2"&&(o=`${l.outputMode.githubV2.owner}/${l.outputMode.githubV2.repo}`))}}if(!c){n.logger.debug(`[SDK Dynamic IR] ${r}: no generator found with a package name`);return}try{let s=await e.sdks.versions.computeSemanticVersion({githubRepository:o,language:a,package:c});if(!s.ok){n.logger.debug(`[SDK Dynamic IR] ${r}: version computation failed for package "${c}"`);return}return n.logger.debug(`[SDK Dynamic IR] ${r}: computed version ${s.body.version} for package "${c}"`),{version:s.body.version,generatorPackage:c}}catch(s){n.logger.debug(`[SDK Dynamic IR] ${r}: error computing version: ${s}`);return}}async function GM5({workspace:e,organization:t,context:r,snippetsConfig:i,skipLanguages:n=new Set}){let a={};if(!e)return;Object.keys(i).length===0&&(r.logger.warn(`WARNING: No snippets defined for ${e.workspaceName}.`),r.logger.warn("Did you add snippets to your docs configuration?"),r.logger.warn("For more info: https://buildwithfern.com/learn/docs/api-references/sdk-snippets"));let o={typescript:i.typescriptSdk?.package,python:i.pythonSdk?.package,java:i.javaSdk?.coordinate,go:i.goSdk?.githubRepo,csharp:i.csharpSdk?.package,ruby:i.rubySdk?.gem,php:i.phpSdk?.package,swift:i.swiftSdk?.package,rust:i.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let c of e.generatorsConfiguration.groups)for(let d of c.generators){let s=Axn({apiName:e.workspaceName??"",organization:t,generatorInvocation:d}),u="";if(s?.outputConfig.type==="publish")switch(s.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":u=s.outputConfig.value.packageName;break;case"maven":u=s.outputConfig.value.coordinate;break;case"go":u=s.outputConfig.value.repoUrl;break;case"swift":u=s.outputConfig.value.repoUrl;break;case"crates":u=s.outputConfig.value.packageName;break}if(d.language==="php"&&d.config&&typeof d.config=="object"&&"packageName"in d.config&&(u=d.config.packageName??""),!!d.language){if(n.has(d.language)){r.logger.debug(`Skipping dynamic IR generation for ${d.language} (using existing SDK dynamic IR)`);continue}if(d.language&&o[d.language]===u){let l=lS({workspace:e,generationLanguage:d.language,keywords:void 0,smartCasing:d.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:u,version:void 0,context:r,sourceResolver:new cS(r,e),dynamicGeneratorConfig:s}),p=mvn({ir:l,disableExamples:!0,smartCasing:d.smartCasing,generationLanguage:d.language,generatorConfig:s});p?a[d.language]={dynamicIR:p}:r.logger.debug(`Failed to create dynamic IR for ${d.language}`)}}}for(let[c,d]of Object.entries(o))c&&d&&!Object.keys(a).includes(c)&&!n.has(c)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${c} SDK snippets because of unknown package \`${d}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${d} package.`),r.logger.warn());if(Object.keys(a).length>0)return a}async function HM5({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:i}){if(Object.keys(t).length>0)for(let[n,a]of Object.entries(t)){let o=e[n]?.dynamicIR;o?(await fetch(a.uploadUrl,{method:"PUT",body:JSON.stringify(o),headers:{"Content-Type":"application/octet-stream","Content-Length":JSON.stringify(o).length.toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${i}:${n}`):r.logger.warn(`Failed to upload dynamic IR for ${i}:${n}`):r.logger.warn(`Could not find matching dynamic IR to upload for ${i}:${n}`)}}async function xM5({docsDefinition:e,organization:t,token:r,url:i,context:n,fdr:a,isPreview:o,domain:c,customDomains:d}){if(!(e.config.aiChatConfig==null||o)&&(n.logger.debug("Processing AI Chat configuration from docs.yml"),e.config.aiChatConfig.location!=null)){let s=jyE({token:r.value}),u=o?[mR(i).replace("https://","")]:[mR(c).replace("https://",""),...d.map(p=>mR(p).replace("https://",""))];if(n.logger.debug(`Enabling Ask AI for domain${u.length>1?"s":""}: ${u.join(", ")}`),e.config.aiChatConfig.location.includes("docs"))for(let p of u){let _=new URL(mR(p)).hostname;n.logger.debug(`Adding domain ${_} to Algolia whitelist`),(await a.docs.v2.write.addAlgoliaPreviewWhitelistEntry({domain:_})).ok||n.logger.warn(`Failed to add domain ${_} to Algolia whitelist${o?". Please try regenerating to test AI chat in preview.":"."}`)}(await s.settings.enableAskAi({domains:u,org_name:t,locations:e.config.aiChatConfig.location,preview:o})).success&&n.logger.info(It.green(`${o?"":`Ask Fern enabled for ${u.join(", ")}. `}
|
|
2017
|
+
${JSON.stringify(Qe,void 0,2)}`),Pe!=null?c.failAndThrow(`Failed to publish docs because API definition (${Pe}) could not be uploaded. Please contact support@buildwithfern.com`,Qe):c.failAndThrow("Failed to publish docs because API definition could not be uploaded. Please contact support@buildwithfern.com",Qe)}}},targetAudiences:h});c.logger.info("Resolving docs definition...");let M=performance.now(),w=await j.resolve(),D=performance.now()-M;if(r.config.settings?.substituteEnvVars){c.logger.debug("Applying environment variable substitution to docs definition...");let{jsFiles:U,...x}=w;w={...FT(x,{onError:Pe=>c.failAndThrow(Pe)},{substituteAsEmpty:!1}),jsFiles:U}}let B=Object.keys(w.pages).length,R=a.length,N=process.memoryUsage();if(c.logger.info(`Resolved docs definition in ${D.toFixed(0)}ms: ${B} pages${R?`, ${R} API workspaces`:""}`),c.logger.debug(`Memory after resolve: RSS=${(N.rss/1024/1024).toFixed(2)}MB, Heap=${(N.heapUsed/1024/1024).toFixed(2)}MB`),v==null)return c.failAndThrow("Failed to publish docs.","Docs registration ID is missing.");c.logger.info("Publishing docs to FDR...");let z=performance.now(),F=await y.docs.v2.write.finishDocsRegister(yG.DocsRegistrationId(v),{docsDefinition:w,excludeApis:!1});if(F.ok){let U=performance.now()-z;c.logger.debug(`Docs published to FDR in ${U.toFixed(0)}ms`);let x=mR(O);await xM5({docsDefinition:w,organization:t,token:e,url:x.replace("https://",""),context:c,fdr:y,isPreview:d,domain:i,customDomains:n});let ee=i9i(x,x);c.logger.info(It.green(`Published docs to ${ee}`))}else switch(F.error.error){case"UnauthorizedError":case"UserNotInOrgError":return c.failAndThrow("Insufficient permissions. Failed to publish docs to "+i);case"DocsRegistrationIdNotFound":return c.failAndThrow("Failed to publish docs to "+i,`Docs registration ID ${v} does not exist.`);default:return c.failAndThrow("Failed to publish docs to "+i,F.error)}}async function hbE(e,t,r,i){let n=Date.now(),a=Object.keys(e).length;r.logger.debug(`Start uploading ${a} files...`);let o=LFa(Object.entries(e),i),c=0;for(let s of o){await Promise.all(s.map(async([l,{uploadUrl:p}])=>{let _=Ze.of(l),h=$u(t,_);try{let y=asp.lookup(h);await RB.put(p,await(0,nsp.readFile)(h),{headers:{"Content-Type":y===!1?"application/octet-stream":y,"Cache-Control":"public, max-age=31536000, immutable"}})}catch(y){r.failAndThrow(`Failed to upload ${h}`,y)}}));let u=Date.now();c+=s.length,r.logger.debug(`Uploaded ${c}/${a} files in ${u-n}ms`)}let d=Date.now();r.logger.debug(`Finished uploading ${a} files in ${d-n}ms`)}function ybE(e,t){let r=[];for(let[i,n]of Object.entries(e)){let a=Ze.of(i),o=$u(t,a);r.push({relativeFilePath:a,absoluteFilePath:o,fileId:n.fileId})}return r}async function bbE(e,t){switch(await t.instrumentPostHogEvent({command:"docs-generation",properties:{error:JSON.stringify(e)}}),e.error){case"InvalidCustomDomainError":return t.failAndThrow("Your docs domain should end with docs.buildwithfern.com");case"InvalidDomainError":return t.failAndThrow("Please make sure that none of your custom domains are not overlapping (i.e. one is a substring of another)");case"UnauthorizedError":return t.failAndThrow("Please make sure that your FERN_TOKEN is set.");case"UserNotInOrgError":return t.failAndThrow("Please verify if you have access to the organization you are trying to publish the docs to. If you are not a member of the organization, please reach out to the organization owner.");case"UnavailableError":return t.failAndThrow("Failed to publish docs. Please try again later or reach out to Fern support at support@buildwithfern.com.");default:return t.failAndThrow("Failed to publish docs.",e)}}function UM5(e){try{return new URL(mR(e)).pathname}catch{return}}async function LM5({fdr:e,workspace:t,organization:r,context:i,snippetsConfig:n}){if(!t)return;let a=await VM5({fdr:e,workspace:t,snippetsConfig:n,context:i});if(Object.keys(a).length===0){i.logger.debug("[SDK Dynamic IR] No snippet configs found, skipping S3 check");return}try{let o=await e.api.v1.register.checkSdkDynamicIrExists({orgId:di.OrgId(r),snippetConfiguration:a});if(!o.ok||!o.body){i.logger.debug("[SDK Dynamic IR] API call failed or returned empty body");return}let c=o.body.existingDynamicIrs;if(Object.keys(c).length===0){i.logger.debug("[SDK Dynamic IR] No existing SDK dynamic IRs found in S3");return}let d={};for(let[s,u]of Object.entries(c))try{i.logger.debug(`Downloading existing SDK dynamic IR for ${s}...`);let l=await fetch(u.downloadUrl);if(l.ok){let p=await l.json();d[s]={dynamicIR:p},i.logger.debug(`Successfully downloaded SDK dynamic IR for ${s}`)}else i.logger.warn(`Failed to download SDK dynamic IR for ${s}: ${l.status}`)}catch(l){i.logger.warn(`Error downloading SDK dynamic IR for ${s}: ${l}`)}return Object.keys(d).length>0?d:void 0}catch(o){i.logger.debug(`Error checking for existing SDK dynamic IRs: ${o}`);return}}async function VM5({fdr:e,workspace:t,snippetsConfig:r,context:i}){let n={},a=[{language:"typescript",snippetName:r.typescriptSdk?.package,explicitVersion:r.typescriptSdk?.version},{language:"python",snippetName:r.pythonSdk?.package,explicitVersion:r.pythonSdk?.version},{language:"java",snippetName:r.javaSdk?.coordinate,explicitVersion:r.javaSdk?.version},{language:"go",snippetName:r.goSdk?.githubRepo,explicitVersion:r.goSdk?.version},{language:"csharp",snippetName:r.csharpSdk?.package,explicitVersion:r.csharpSdk?.version},{language:"ruby",snippetName:r.rubySdk?.gem,explicitVersion:r.rubySdk?.version},{language:"php",snippetName:r.phpSdk?.package,explicitVersion:r.phpSdk?.version},{language:"swift",snippetName:r.swiftSdk?.package,explicitVersion:r.swiftSdk?.version},{language:"rust",snippetName:r.rustSdk?.package,explicitVersion:r.rustSdk?.version}];for(let o of a){if(!o.snippetName)continue;let c=o.explicitVersion;c||(c=(await WM5({fdr:e,workspace:t,language:o.language,snippetName:o.snippetName,context:i}))?.version),n[o.language]={packageName:o.snippetName,version:c},c||i.logger.debug(`[SDK Dynamic IR] ${o.language}: no version specified, will use latest`)}return n}async function WM5({fdr:e,workspace:t,language:r,snippetName:i,context:n}){let a;switch(r){case"csharp":a="Csharp";break;case"go":a="Go";break;case"java":a="Java";break;case"python":a="Python";break;case"ruby":a="Ruby";break;case"typescript":a="TypeScript";break;case"php":a="Php";break;case"swift":a="Swift";break;default:return}let o,c,d;if(t.generatorsConfiguration?.groups){let s=[];for(let u of t.generatorsConfiguration.groups)for(let l of u.generators)if(l.language===r){let p=_n.getPackageName({generatorInvocation:l});p&&s.push(p),!c&&p&&(c=p,d=l.name,l.outputMode.type==="githubV2"&&(o=`${l.outputMode.githubV2.owner}/${l.outputMode.githubV2.repo}`))}}if(!c){n.logger.debug(`[SDK Dynamic IR] ${r}: no generator found with a package name`);return}try{let s=await e.sdks.versions.computeSemanticVersion({githubRepository:o,language:a,package:c});if(!s.ok){n.logger.debug(`[SDK Dynamic IR] ${r}: version computation failed for package "${c}"`);return}return n.logger.debug(`[SDK Dynamic IR] ${r}: computed version ${s.body.version} for package "${c}"`),{version:s.body.version,generatorPackage:c}}catch(s){n.logger.debug(`[SDK Dynamic IR] ${r}: error computing version: ${s}`);return}}async function GM5({workspace:e,organization:t,context:r,snippetsConfig:i,skipLanguages:n=new Set}){let a={};if(!e)return;Object.keys(i).length===0&&(r.logger.warn(`WARNING: No snippets defined for ${e.workspaceName}.`),r.logger.warn("Did you add snippets to your docs configuration?"),r.logger.warn("For more info: https://buildwithfern.com/learn/docs/api-references/sdk-snippets"));let o={typescript:i.typescriptSdk?.package,python:i.pythonSdk?.package,java:i.javaSdk?.coordinate,go:i.goSdk?.githubRepo,csharp:i.csharpSdk?.package,ruby:i.rubySdk?.gem,php:i.phpSdk?.package,swift:i.swiftSdk?.package,rust:i.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let c of e.generatorsConfiguration.groups)for(let d of c.generators){let s=Axn({apiName:e.workspaceName??"",organization:t,generatorInvocation:d}),u="";if(s?.outputConfig.type==="publish")switch(s.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":u=s.outputConfig.value.packageName;break;case"maven":u=s.outputConfig.value.coordinate;break;case"go":u=s.outputConfig.value.repoUrl;break;case"swift":u=s.outputConfig.value.repoUrl;break;case"crates":u=s.outputConfig.value.packageName;break}if(d.language==="php"&&d.config&&typeof d.config=="object"&&"packageName"in d.config&&(u=d.config.packageName??""),!!d.language){if(n.has(d.language)){r.logger.debug(`Skipping dynamic IR generation for ${d.language} (using existing SDK dynamic IR)`);continue}if(d.language&&o[d.language]===u){let l=lS({workspace:e,generationLanguage:d.language,keywords:void 0,smartCasing:d.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:u,version:void 0,context:r,sourceResolver:new cS(r,e),dynamicGeneratorConfig:s}),p=mvn({ir:l,disableExamples:!0,smartCasing:d.smartCasing,generationLanguage:d.language,generatorConfig:s});p?a[d.language]={dynamicIR:p}:r.logger.debug(`Failed to create dynamic IR for ${d.language}`)}}}for(let[c,d]of Object.entries(o))c&&d&&!Object.keys(a).includes(c)&&!n.has(c)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${c} SDK snippets because of unknown package \`${d}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${d} package.`),r.logger.warn());if(Object.keys(a).length>0)return a}async function HM5({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:i}){if(Object.keys(t).length>0)for(let[n,a]of Object.entries(t)){let o=e[n]?.dynamicIR;if(o){let c=JSON.stringify(o);(await fetch(a.uploadUrl,{method:"PUT",body:c,headers:{"Content-Type":"application/octet-stream","Content-Length":Buffer.byteLength(c,"utf8").toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${i}:${n}`):r.logger.warn(`Failed to upload dynamic IR for ${i}:${n}`)}else r.logger.warn(`Could not find matching dynamic IR to upload for ${i}:${n}`)}}async function xM5({docsDefinition:e,organization:t,token:r,url:i,context:n,fdr:a,isPreview:o,domain:c,customDomains:d}){if(!(e.config.aiChatConfig==null||o)&&(n.logger.debug("Processing AI Chat configuration from docs.yml"),e.config.aiChatConfig.location!=null)){let s=jyE({token:r.value}),u=o?[mR(i).replace("https://","")]:[mR(c).replace("https://",""),...d.map(p=>mR(p).replace("https://",""))];if(n.logger.debug(`Enabling Ask AI for domain${u.length>1?"s":""}: ${u.join(", ")}`),e.config.aiChatConfig.location.includes("docs"))for(let p of u){let _=new URL(mR(p)).hostname;n.logger.debug(`Adding domain ${_} to Algolia whitelist`),(await a.docs.v2.write.addAlgoliaPreviewWhitelistEntry({domain:_})).ok||n.logger.warn(`Failed to add domain ${_} to Algolia whitelist${o?". Please try regenerating to test AI chat in preview.":"."}`)}(await s.settings.enableAskAi({domains:u,org_name:t,locations:e.config.aiChatConfig.location,preview:o})).success&&n.logger.info(It.green(`${o?"":`Ask Fern enabled for ${u.join(", ")}. `}
|
|
2018
2018
|
Note: it may take a few minutes after publishing for Ask Fern settings to reflect expected state.`))}}function KM5(e,t){if(e)return{enabled:!0,model:process.env.FERN_AI_MODEL||"gpt-4o-mini",maxRetries:parseInt(process.env.FERN_AI_MAX_RETRIES||"3"),requestTimeoutMs:parseInt(process.env.FERN_AI_TIMEOUT_MS||"25000"),styleInstructions:t}}function JM5(e){let t=e,r=t?.content;return{errorType:t?.error,statusCode:t?.statusCode??r?.statusCode,reason:r?.reason,errorMessage:r?.errorMessage??r?.message,body:r?.body,cause:r?.cause,rawError:e}}async function osp({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:i,context:n,token:a,instanceUrl:o,preview:c,disableTemplates:d,skipUpload:s}){let u=c&&!i.config.settings?.substituteEnvVars;i.config=FT(i.config,{onError:h=>n.failAndThrow(h)},{substituteAsEmpty:u});let l=i.config.instances;if(l.length===0){n.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(l.length>1&&o==null){n.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${l[0]?.url})`);return}let p=l.find(h=>h.url===o)??l[0];if(p==null){n.failAndThrow(`No docs instance with url ${o}. Failed to register.`);return}let _=[];p.customDomain!=null&&(typeof p.customDomain=="string"?_.push(p.customDomain):Array.isArray(p.customDomain)&&_.push(...p.customDomain)),n.logger.info(`Starting docs publishing for ${c?"preview":"production"}: ${p.url}`),n.logger.debug(`Organization: ${e}, Preview: ${c}, APIs: ${t.length}, OSS: ${r.length}`),await n.runInteractiveTask({name:p.url},async()=>{let h=performance.now();await gbE({docsWorkspace:i,customDomains:_,domain:p.url,token:a,organization:e,context:n,apiWorkspaces:t,ossWorkspaces:r,preview:c,editThisPage:p.editThisPage,isPrivate:p.private,disableTemplates:d,skipUpload:s,withAiExamples:i.config.experimental?.aiExamples??!0,targetAudiences:p.audiences?Array.isArray(p.audiences)?p.audiences:[p.audiences]:void 0});let y=performance.now()-h;n.logger.debug(`Docs publishing completed in ${y.toFixed(0)}ms`)})}function Lcn(){return typeof navigator=="object"&&"userAgent"in navigator?navigator.userAgent:typeof process=="object"&&process.version!==void 0?`Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`:"<environment undetectable>"}var tvE=ce(qbE());var TbE="9.0.6";var eD5=`octokit-endpoint.js/${TbE} ${Lcn()}`,RbE={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":eD5},mediaType:{format:""}};function zbE(e){return e?Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{}):{}}function NbE(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 usp(e,t){let r=Object.assign({},e);return Object.keys(t).forEach(i=>{NbE(t[i])?i in e?r[i]=usp(e[i],t[i]):Object.assign(r,{[i]:t[i]}):Object.assign(r,{[i]:t[i]})}),r}function ssp(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function dBo(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=zbE(r.headers),ssp(r),ssp(r.headers);let i=usp(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 FbE(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 tD5=/\{[^{}}]+\}/g;function rD5(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function QbE(e){let t=e.match(tD5);return t?t.map(rD5).reduce((r,i)=>r.concat(i),[]):[]}function csp(e,t){let r={__proto__:null};for(let i of Object.keys(e))t.indexOf(i)===-1&&(r[i]=e[i]);return r}function UbE(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 oNa(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}function pBo(e,t,r){return t=e==="+"||e==="#"?UbE(t):oNa(t),r?oNa(r)+"="+t:t}function aNa(e){return e!=null}function lsp(e){return e===";"||e==="&"||e==="?"}function iD5(e,t,r,i){var n=e[r],a=[];if(aNa(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(pBo(t,n,lsp(t)?r:""));else if(i==="*")Array.isArray(n)?n.filter(aNa).forEach(function(o){a.push(pBo(t,o,lsp(t)?r:""))}):Object.keys(n).forEach(function(o){aNa(n[o])&&a.push(pBo(t,n[o],o))});else{let o=[];Array.isArray(n)?n.filter(aNa).forEach(function(c){o.push(pBo(t,c))}):Object.keys(n).forEach(function(c){aNa(n[c])&&(o.push(oNa(c)),o.push(pBo(t,n[c].toString())))}),lsp(t)?a.push(oNa(r)+"="+o.join(",")):o.length!==0&&a.push(o.join(","))}else t===";"?aNa(n)&&a.push(oNa(r)):n===""&&(t==="&"||t==="?")?a.push(oNa(r)+"="):n===""&&a.push("");return a}function LbE(e){return{expand:nD5.bind(null,e)}}function nD5(e,t){var r=["+","#",".","/",";","?","&"];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(i,n,a){if(n){let c="",d=[];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);d.push(iD5(t,c,u[1],u[2]||u[3]))}),c&&c!=="+"){var o=",";return c==="?"?o="&":c!=="#"&&(o=c),(d.length!==0?c:"")+d.join(o)}else return d.join(",")}else return UbE(a)}),e==="/"?e:e.replace(/\/$/,"")}function HJs(e){let t=e.method.toUpperCase(),r=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),i=Object.assign({},e.headers),n,a=csp(e,["method","baseUrl","url","headers","request","mediaType"]),o=QbE(r);r=LbE(r).expand(a),/^http/.test(r)||(r=e.baseUrl+r);let c=Object.keys(e).filter(u=>o.includes(u)).concat("baseUrl"),d=csp(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=FbE(r,d):"data"in d?n=d.data:Object.keys(d).length&&(n=d),!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 VbE(e,t,r){return HJs(dBo(e,t,r))}function fsp(e,t){let r=dBo(e,t),i=VbE.bind(null,r);return Object.assign(i,{DEFAULTS:r,defaults:fsp.bind(null,r),merge:dBo.bind(null,r),parse:HJs})}var WbE=fsp(null,RbE);var GbE="8.4.1";function HbE(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)}var _Bo=class extends Error{constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="Deprecation"}};var dsp=ce(Q$c()),aD5=(0,dsp.default)(e=>console.warn(e)),oD5=(0,dsp.default)(e=>console.warn(e)),Vcn=class extends Error{constructor(t,r,i){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="HttpError",this.status=r;let n;"headers"in i&&typeof i.headers<"u"&&(n=i.headers),"response"in i&&(this.response=i.response,n=i.response.headers);let a=Object.assign({},i.request);i.request.headers.authorization&&(a.headers=Object.assign({},i.request.headers,{authorization:i.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),a.url=a.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=a,Object.defineProperty(this,"code",{get(){return aD5(new _Bo("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")),r}}),Object.defineProperty(this,"headers",{get(){return oD5(new _Bo("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.")),n||{}}})}};function xbE(e){return e.arrayBuffer()}function _sp(e){let t=e.request&&e.request.log?e.request.log:console,r=e.request?.parseSuccessResponseBody!==!1;(HbE(e.body)||Array.isArray(e.body))&&(e.body=JSON.stringify(e.body));let i={},n,a,{fetch:o}=globalThis;if(e.request?.fetch&&(o=e.request.fetch),!o)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");return o(e.url,{method:e.method,body:e.body,redirect:e.request?.redirect,headers:e.headers,signal:e.request?.signal,...e.body&&{duplex:"half"}}).then(async c=>{a=c.url,n=c.status;for(let d of c.headers)i[d[0]]=d[1];if("deprecation"in i){let d=i.link&&i.link.match(/<([^<>]+)>; rel="deprecation"/),s=d&&d.pop();t.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${i.sunset}${s?`. See ${s}`:""}`)}if(!(n===204||n===205)){if(e.method==="HEAD"){if(n<400)return;throw new Vcn(c.statusText,n,{response:{url:a,status:n,headers:i,data:void 0},request:e})}if(n===304)throw new Vcn("Not modified",n,{response:{url:a,status:n,headers:i,data:await psp(c)},request:e});if(n>=400){let d=await psp(c);throw new Vcn(uD5(d),n,{response:{url:a,status:n,headers:i,data:d},request:e})}return r?await psp(c):c.body}}).then(c=>({status:n,url:a,headers:i,data:c})).catch(c=>{if(c instanceof Vcn)throw c;if(c.name==="AbortError")throw c;let d=c.message;throw c.name==="TypeError"&&"cause"in c&&(c.cause instanceof Error?d=c.cause.message:typeof c.cause=="string"&&(d=c.cause)),new Vcn(d,500,{request:e})})}async function psp(e){let t=e.headers.get("content-type");return/application\/json/.test(t)?e.json().catch(()=>e.text()).catch(()=>""):!t||/^text\/|charset=utf-8$/.test(t)?e.text():xbE(e)}function uD5(e){if(typeof e=="string")return e;let t;return"documentation_url"in e?t=` - ${e.documentation_url}`:t="","message"in e?Array.isArray(e.errors)?`${e.message}: ${e.errors.map(JSON.stringify).join(", ")}${t}`:`${e.message}${t}`:`Unknown error: ${JSON.stringify(e)}`}function xJs(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 _sp(r.parse(o));let c=(d,s)=>_sp(r.parse(r.merge(d,s)));return Object.assign(c,{endpoint:r,defaults:xJs.bind(null,r)}),o.request.hook(c,o)},{endpoint:r,defaults:xJs.bind(null,r)})}var hBo=xJs(WbE,{headers:{"user-agent":`octokit-request.js/${GbE} ${Lcn()}`}});var sD5="7.1.1";function cD5(e){return`Request failed due to following response errors:
|
|
2019
2019
|
`+e.errors.map(t=>` - ${t.message}`).join(`
|
|
2020
2020
|
`)}var lD5=class extends Error{constructor(e,t,r){super(cD5(r)),this.request=e,this.headers=t,this.response=r,this.name="GraphqlResponseError",this.errors=r.errors,this.data=r.data,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},fD5=["method","baseUrl","url","headers","request","query","mediaType"],dD5=["query","method","url"],KbE=/\/api\/v3\/?$/;function pD5(e,t,r){if(r){if(typeof t=="string"&&"query"in r)return Promise.reject(new Error('[@octokit/graphql] "query" cannot be used as variable name'));for(let o in r)if(dD5.includes(o))return Promise.reject(new Error(`[@octokit/graphql] "${o}" cannot be used as variable name`))}let i=typeof t=="string"?Object.assign({query:t},r):t,n=Object.keys(i).reduce((o,c)=>fD5.includes(c)?(o[c]=i[c],o):(o.variables||(o.variables={}),o.variables[c]=i[c],o),{}),a=i.baseUrl||e.endpoint.DEFAULTS.baseUrl;return KbE.test(a)&&(n.url=a.replace(KbE,"/api/graphql")),e(n).then(o=>{if(o.data.errors){let c={};for(let d of Object.keys(o.headers))c[d]=o.headers[d];throw new lD5(n,c,o.data)}return o.data.data})}function hsp(e,t){let r=e.defaults(t);return Object.assign((n,a)=>pD5(r,n,a),{defaults:hsp.bind(null,r),endpoint:r.endpoint})}var L5Z=hsp(hBo,{headers:{"user-agent":`octokit-graphql.js/${sD5} ${Lcn()}`},method:"POST",url:"/graphql"});function JbE(e){return hsp(e,{method:"POST",url:"/graphql"})}var _D5=/^v1\./,hD5=/^ghs_/,yD5=/^ghu_/;async function $bE(e){let t=e.split(/\./).length===3,r=_D5.test(e)||hD5.test(e),i=yD5.test(e);return{type:"token",token:e,tokenType:t?"app":r?"installation":i?"user-to-server":"oauth"}}function YbE(e){return e.split(/\./).length===3?`bearer ${e}`:`token ${e}`}async function XbE(e,t,r,i){let n=t.endpoint.merge(r,i);return n.headers.authorization=YbE(e),t(n)}var ZbE=function(t){if(!t)throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");if(typeof t!="string")throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");return t=t.replace(/^(token|bearer) +/i,""),Object.assign($bE.bind(null,t),{hook:XbE.bind(null,t)})};var rvE="5.2.2",kbE=()=>{},bD5=console.warn.bind(console),vD5=console.error.bind(console);function gD5(e={}){return typeof e.debug!="function"&&(e.debug=kbE),typeof e.info!="function"&&(e.info=kbE),typeof e.warn!="function"&&(e.warn=bD5),typeof e.error!="function"&&(e.error=vD5),e}var evE=`octokit-core.js/${rvE} ${Lcn()}`,ivE=class{static{this.VERSION=rvE}static defaults(e){return class extends this{constructor(...r){let i=r[0]||{};if(typeof e=="function"){super(e(i));return}super(Object.assign({},e,i,i.userAgent&&e.userAgent?{userAgent:`${i.userAgent} ${e.userAgent}`}:null))}}}static{this.plugins=[]}static plugin(...e){let t=this.plugins;return class extends this{static{this.plugins=t.concat(e.filter(i=>!t.includes(i)))}}}constructor(e={}){let t=new tvE.Collection,r={baseUrl:hBo.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},e.request,{hook:t.bind(null,"request")}),mediaType:{previews:[],format:""}};if(r.headers["user-agent"]=e.userAgent?`${e.userAgent} ${evE}`:evE,e.baseUrl&&(r.baseUrl=e.baseUrl),e.previews&&(r.mediaType.previews=e.previews),e.timeZone&&(r.headers["time-zone"]=e.timeZone),this.request=hBo.defaults(r),this.graphql=JbE(this.request).defaults(r),this.log=gD5(e.log),this.hook=t,e.authStrategy){let{authStrategy:n,...a}=e,o=n(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:a},e.auth));t.wrap("request",o.hook),this.auth=o}else if(!e.auth)this.auth=async()=>({type:"unauthenticated"});else{let n=ZbE(e.auth);t.wrap("request",n.hook),this.auth=n}let i=this.constructor;for(let n=0;n<i.plugins.length;++n)Object.assign(this,i.plugins[n](this,e))}};var nvE="4.0.1";function ysp(e){e.hook.wrap("request",(t,r)=>{e.log.debug("request",r);let i=Date.now(),n=e.request.endpoint.parse(r),a=n.url.replace(r.baseUrl,"");return t(r).then(o=>(e.log.info(`${n.method} ${a} - ${o.status} in ${Date.now()-i}ms`),o)).catch(o=>{throw e.log.info(`${n.method} ${a} - ${o.status} in ${Date.now()-i}ms`),o})})}ysp.VERSION=nvE;var OD5="11.4.4-cjs.2";function AD5(e){if(!e.data)return{...e,data:[]};if(!("total_count"in e.data&&!("url"in e.data)))return e;let r=e.data.incomplete_results,i=e.data.repository_selection,n=e.data.total_count;delete e.data.incomplete_results,delete e.data.repository_selection,delete e.data.total_count;let a=Object.keys(e.data)[0],o=e.data[a];return e.data=o,typeof r<"u"&&(e.data.incomplete_results=r),typeof i<"u"&&(e.data.repository_selection=i),e.data.total_count=n,e}function bsp(e,t,r){let i=typeof t=="function"?t.endpoint(r):e.request.endpoint(t,r),n=typeof t=="function"?t:e.request,a=i.method,o=i.headers,c=i.url;return{[Symbol.asyncIterator]:()=>({async next(){if(!c)return{done:!0};try{let d=await n({method:a,url:c,headers:o}),s=AD5(d);return c=((s.headers.link||"").match(/<([^<>]+)>;\s*rel="next"/)||[])[1],{value:s}}catch(d){if(d.status!==409)throw d;return c="",{value:{status:200,headers:{},data:[]}}}}})}}function avE(e,t,r,i){return typeof r=="function"&&(i=r,r=void 0),ovE(e,[],bsp(e,t,r)[Symbol.asyncIterator](),i)}function ovE(e,t,r,i){return r.next().then(n=>{if(n.done)return t;let a=!1;function o(){a=!0}return t=t.concat(i?i(n.value,o):n.value.data),a?t:ovE(e,t,r,i)})}var c6Z=Object.assign(avE,{iterator:bsp});function vsp(e){return{paginate:Object.assign(avE.bind(null,e),{iterator:bsp.bind(null,e)})}}vsp.VERSION=OD5;var gsp="13.3.2-cjs.1";var mD5={actions:{addCustomLabelsToSelfHostedRunnerForOrg:["POST /orgs/{org}/actions/runners/{runner_id}/labels"],addCustomLabelsToSelfHostedRunnerForRepo:["POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],addRepoAccessToSelfHostedRunnerGroupInOrg:["PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}"],addSelectedRepoToOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],addSelectedRepoToOrgVariable:["PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"],approveWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"],cancelWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"],createEnvironmentVariable:["POST /repos/{owner}/{repo}/environments/{environment_name}/variables"],createOrUpdateEnvironmentSecret:["PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],createOrUpdateOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"],createOrgVariable:["POST /orgs/{org}/actions/variables"],createRegistrationTokenForOrg:["POST /orgs/{org}/actions/runners/registration-token"],createRegistrationTokenForRepo:["POST /repos/{owner}/{repo}/actions/runners/registration-token"],createRemoveTokenForOrg:["POST /orgs/{org}/actions/runners/remove-token"],createRemoveTokenForRepo:["POST /repos/{owner}/{repo}/actions/runners/remove-token"],createRepoVariable:["POST /repos/{owner}/{repo}/actions/variables"],createWorkflowDispatch:["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"],deleteActionsCacheById:["DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}"],deleteActionsCacheByKey:["DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}"],deleteArtifact:["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],deleteEnvironmentSecret:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],deleteEnvironmentVariable:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],deleteOrgSecret:["DELETE /orgs/{org}/actions/secrets/{secret_name}"],deleteOrgVariable:["DELETE /orgs/{org}/actions/variables/{name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"],deleteRepoVariable:["DELETE /repos/{owner}/{repo}/actions/variables/{name}"],deleteSelfHostedRunnerFromOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}"],deleteSelfHostedRunnerFromRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"],deleteWorkflowRun:["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"],deleteWorkflowRunLogs:["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],disableSelectedRepositoryGithubActionsOrganization:["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"],disableWorkflow:["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"],downloadArtifact:["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"],downloadJobLogsForWorkflowRun:["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"],downloadWorkflowRunAttemptLogs:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"],downloadWorkflowRunLogs:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],enableSelectedRepositoryGithubActionsOrganization:["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"],enableWorkflow:["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"],forceCancelWorkflowRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel"],generateRunnerJitconfigForOrg:["POST /orgs/{org}/actions/runners/generate-jitconfig"],generateRunnerJitconfigForRepo:["POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig"],getActionsCacheList:["GET /repos/{owner}/{repo}/actions/caches"],getActionsCacheUsage:["GET /repos/{owner}/{repo}/actions/cache/usage"],getActionsCacheUsageByRepoForOrg:["GET /orgs/{org}/actions/cache/usage-by-repository"],getActionsCacheUsageForOrg:["GET /orgs/{org}/actions/cache/usage"],getAllowedActionsOrganization:["GET /orgs/{org}/actions/permissions/selected-actions"],getAllowedActionsRepository:["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"],getArtifact:["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],getCustomOidcSubClaimForRepo:["GET /repos/{owner}/{repo}/actions/oidc/customization/sub"],getEnvironmentPublicKey:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key"],getEnvironmentSecret:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"],getEnvironmentVariable:["GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],getGithubActionsDefaultWorkflowPermissionsOrganization:["GET /orgs/{org}/actions/permissions/workflow"],getGithubActionsDefaultWorkflowPermissionsRepository:["GET /repos/{owner}/{repo}/actions/permissions/workflow"],getGithubActionsPermissionsOrganization:["GET /orgs/{org}/actions/permissions"],getGithubActionsPermissionsRepository:["GET /repos/{owner}/{repo}/actions/permissions"],getJobForWorkflowRun:["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],getOrgPublicKey:["GET /orgs/{org}/actions/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/actions/secrets/{secret_name}"],getOrgVariable:["GET /orgs/{org}/actions/variables/{name}"],getPendingDeploymentsForRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],getRepoPermissions:["GET /repos/{owner}/{repo}/actions/permissions",{},{renamed:["actions","getGithubActionsPermissionsRepository"]}],getRepoPublicKey:["GET /repos/{owner}/{repo}/actions/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],getRepoVariable:["GET /repos/{owner}/{repo}/actions/variables/{name}"],getReviewsForRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"],getSelfHostedRunnerForOrg:["GET /orgs/{org}/actions/runners/{runner_id}"],getSelfHostedRunnerForRepo:["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"],getWorkflow:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],getWorkflowAccessToRepository:["GET /repos/{owner}/{repo}/actions/permissions/access"],getWorkflowRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}"],getWorkflowRunAttempt:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"],getWorkflowRunUsage:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"],getWorkflowUsage:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"],listArtifactsForRepo:["GET /repos/{owner}/{repo}/actions/artifacts"],listEnvironmentSecrets:["GET /repos/{owner}/{repo}/environments/{environment_name}/secrets"],listEnvironmentVariables:["GET /repos/{owner}/{repo}/environments/{environment_name}/variables"],listJobsForWorkflowRun:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"],listJobsForWorkflowRunAttempt:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"],listLabelsForSelfHostedRunnerForOrg:["GET /orgs/{org}/actions/runners/{runner_id}/labels"],listLabelsForSelfHostedRunnerForRepo:["GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],listOrgSecrets:["GET /orgs/{org}/actions/secrets"],listOrgVariables:["GET /orgs/{org}/actions/variables"],listRepoOrganizationSecrets:["GET /repos/{owner}/{repo}/actions/organization-secrets"],listRepoOrganizationVariables:["GET /repos/{owner}/{repo}/actions/organization-variables"],listRepoSecrets:["GET /repos/{owner}/{repo}/actions/secrets"],listRepoVariables:["GET /repos/{owner}/{repo}/actions/variables"],listRepoWorkflows:["GET /repos/{owner}/{repo}/actions/workflows"],listRunnerApplicationsForOrg:["GET /orgs/{org}/actions/runners/downloads"],listRunnerApplicationsForRepo:["GET /repos/{owner}/{repo}/actions/runners/downloads"],listSelectedReposForOrgSecret:["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"],listSelectedReposForOrgVariable:["GET /orgs/{org}/actions/variables/{name}/repositories"],listSelectedRepositoriesEnabledGithubActionsOrganization:["GET /orgs/{org}/actions/permissions/repositories"],listSelfHostedRunnersForOrg:["GET /orgs/{org}/actions/runners"],listSelfHostedRunnersForRepo:["GET /repos/{owner}/{repo}/actions/runners"],listWorkflowRunArtifacts:["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"],listWorkflowRuns:["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"],listWorkflowRunsForRepo:["GET /repos/{owner}/{repo}/actions/runs"],reRunJobForWorkflowRun:["POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun"],reRunWorkflow:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"],reRunWorkflowFailedJobs:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs"],removeAllCustomLabelsFromSelfHostedRunnerForOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}/labels"],removeAllCustomLabelsFromSelfHostedRunnerForRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],removeCustomLabelFromSelfHostedRunnerForOrg:["DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}"],removeCustomLabelFromSelfHostedRunnerForRepo:["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],removeSelectedRepoFromOrgVariable:["DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"],reviewCustomGatesForRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule"],reviewPendingDeploymentsForRun:["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],setAllowedActionsOrganization:["PUT /orgs/{org}/actions/permissions/selected-actions"],setAllowedActionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"],setCustomLabelsForSelfHostedRunnerForOrg:["PUT /orgs/{org}/actions/runners/{runner_id}/labels"],setCustomLabelsForSelfHostedRunnerForRepo:["PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],setCustomOidcSubClaimForRepo:["PUT /repos/{owner}/{repo}/actions/oidc/customization/sub"],setGithubActionsDefaultWorkflowPermissionsOrganization:["PUT /orgs/{org}/actions/permissions/workflow"],setGithubActionsDefaultWorkflowPermissionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions/workflow"],setGithubActionsPermissionsOrganization:["PUT /orgs/{org}/actions/permissions"],setGithubActionsPermissionsRepository:["PUT /repos/{owner}/{repo}/actions/permissions"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"],setSelectedReposForOrgVariable:["PUT /orgs/{org}/actions/variables/{name}/repositories"],setSelectedRepositoriesEnabledGithubActionsOrganization:["PUT /orgs/{org}/actions/permissions/repositories"],setWorkflowAccessToRepository:["PUT /repos/{owner}/{repo}/actions/permissions/access"],updateEnvironmentVariable:["PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"],updateOrgVariable:["PATCH /orgs/{org}/actions/variables/{name}"],updateRepoVariable:["PATCH /repos/{owner}/{repo}/actions/variables/{name}"]},activity:{checkRepoIsStarredByAuthenticatedUser:["GET /user/starred/{owner}/{repo}"],deleteRepoSubscription:["DELETE /repos/{owner}/{repo}/subscription"],deleteThreadSubscription:["DELETE /notifications/threads/{thread_id}/subscription"],getFeeds:["GET /feeds"],getRepoSubscription:["GET /repos/{owner}/{repo}/subscription"],getThread:["GET /notifications/threads/{thread_id}"],getThreadSubscriptionForAuthenticatedUser:["GET /notifications/threads/{thread_id}/subscription"],listEventsForAuthenticatedUser:["GET /users/{username}/events"],listNotificationsForAuthenticatedUser:["GET /notifications"],listOrgEventsForAuthenticatedUser:["GET /users/{username}/events/orgs/{org}"],listPublicEvents:["GET /events"],listPublicEventsForRepoNetwork:["GET /networks/{owner}/{repo}/events"],listPublicEventsForUser:["GET /users/{username}/events/public"],listPublicOrgEvents:["GET /orgs/{org}/events"],listReceivedEventsForUser:["GET /users/{username}/received_events"],listReceivedPublicEventsForUser:["GET /users/{username}/received_events/public"],listRepoEvents:["GET /repos/{owner}/{repo}/events"],listRepoNotificationsForAuthenticatedUser:["GET /repos/{owner}/{repo}/notifications"],listReposStarredByAuthenticatedUser:["GET /user/starred"],listReposStarredByUser:["GET /users/{username}/starred"],listReposWatchedByUser:["GET /users/{username}/subscriptions"],listStargazersForRepo:["GET /repos/{owner}/{repo}/stargazers"],listWatchedReposForAuthenticatedUser:["GET /user/subscriptions"],listWatchersForRepo:["GET /repos/{owner}/{repo}/subscribers"],markNotificationsAsRead:["PUT /notifications"],markRepoNotificationsAsRead:["PUT /repos/{owner}/{repo}/notifications"],markThreadAsDone:["DELETE /notifications/threads/{thread_id}"],markThreadAsRead:["PATCH /notifications/threads/{thread_id}"],setRepoSubscription:["PUT /repos/{owner}/{repo}/subscription"],setThreadSubscription:["PUT /notifications/threads/{thread_id}/subscription"],starRepoForAuthenticatedUser:["PUT /user/starred/{owner}/{repo}"],unstarRepoForAuthenticatedUser:["DELETE /user/starred/{owner}/{repo}"]},apps:{addRepoToInstallation:["PUT /user/installations/{installation_id}/repositories/{repository_id}",{},{renamed:["apps","addRepoToInstallationForAuthenticatedUser"]}],addRepoToInstallationForAuthenticatedUser:["PUT /user/installations/{installation_id}/repositories/{repository_id}"],checkToken:["POST /applications/{client_id}/token"],createFromManifest:["POST /app-manifests/{code}/conversions"],createInstallationAccessToken:["POST /app/installations/{installation_id}/access_tokens"],deleteAuthorization:["DELETE /applications/{client_id}/grant"],deleteInstallation:["DELETE /app/installations/{installation_id}"],deleteToken:["DELETE /applications/{client_id}/token"],getAuthenticated:["GET /app"],getBySlug:["GET /apps/{app_slug}"],getInstallation:["GET /app/installations/{installation_id}"],getOrgInstallation:["GET /orgs/{org}/installation"],getRepoInstallation:["GET /repos/{owner}/{repo}/installation"],getSubscriptionPlanForAccount:["GET /marketplace_listing/accounts/{account_id}"],getSubscriptionPlanForAccountStubbed:["GET /marketplace_listing/stubbed/accounts/{account_id}"],getUserInstallation:["GET /users/{username}/installation"],getWebhookConfigForApp:["GET /app/hook/config"],getWebhookDelivery:["GET /app/hook/deliveries/{delivery_id}"],listAccountsForPlan:["GET /marketplace_listing/plans/{plan_id}/accounts"],listAccountsForPlanStubbed:["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"],listInstallationReposForAuthenticatedUser:["GET /user/installations/{installation_id}/repositories"],listInstallationRequestsForAuthenticatedApp:["GET /app/installation-requests"],listInstallations:["GET /app/installations"],listInstallationsForAuthenticatedUser:["GET /user/installations"],listPlans:["GET /marketplace_listing/plans"],listPlansStubbed:["GET /marketplace_listing/stubbed/plans"],listReposAccessibleToInstallation:["GET /installation/repositories"],listSubscriptionsForAuthenticatedUser:["GET /user/marketplace_purchases"],listSubscriptionsForAuthenticatedUserStubbed:["GET /user/marketplace_purchases/stubbed"],listWebhookDeliveries:["GET /app/hook/deliveries"],redeliverWebhookDelivery:["POST /app/hook/deliveries/{delivery_id}/attempts"],removeRepoFromInstallation:["DELETE /user/installations/{installation_id}/repositories/{repository_id}",{},{renamed:["apps","removeRepoFromInstallationForAuthenticatedUser"]}],removeRepoFromInstallationForAuthenticatedUser:["DELETE /user/installations/{installation_id}/repositories/{repository_id}"],resetToken:["PATCH /applications/{client_id}/token"],revokeInstallationAccessToken:["DELETE /installation/token"],scopeToken:["POST /applications/{client_id}/token/scoped"],suspendInstallation:["PUT /app/installations/{installation_id}/suspended"],unsuspendInstallation:["DELETE /app/installations/{installation_id}/suspended"],updateWebhookConfigForApp:["PATCH /app/hook/config"]},billing:{getGithubActionsBillingOrg:["GET /orgs/{org}/settings/billing/actions"],getGithubActionsBillingUser:["GET /users/{username}/settings/billing/actions"],getGithubBillingUsageReportOrg:["GET /organizations/{org}/settings/billing/usage"],getGithubPackagesBillingOrg:["GET /orgs/{org}/settings/billing/packages"],getGithubPackagesBillingUser:["GET /users/{username}/settings/billing/packages"],getSharedStorageBillingOrg:["GET /orgs/{org}/settings/billing/shared-storage"],getSharedStorageBillingUser:["GET /users/{username}/settings/billing/shared-storage"]},checks:{create:["POST /repos/{owner}/{repo}/check-runs"],createSuite:["POST /repos/{owner}/{repo}/check-suites"],get:["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"],getSuite:["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"],listAnnotations:["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"],listForRef:["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"],listForSuite:["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"],listSuitesForRef:["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"],rerequestRun:["POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"],rerequestSuite:["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"],setSuitesPreferences:["PATCH /repos/{owner}/{repo}/check-suites/preferences"],update:["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"]},codeScanning:{commitAutofix:["POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits"],createAutofix:["POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"],createVariantAnalysis:["POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses"],deleteAnalysis:["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"],deleteCodeqlDatabase:["DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"],getAlert:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}",{},{renamedParameters:{alert_id:"alert_number"}}],getAnalysis:["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"],getAutofix:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"],getCodeqlDatabase:["GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"],getDefaultSetup:["GET /repos/{owner}/{repo}/code-scanning/default-setup"],getSarif:["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"],getVariantAnalysis:["GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}"],getVariantAnalysisRepoTask:["GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}"],listAlertInstances:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"],listAlertsForOrg:["GET /orgs/{org}/code-scanning/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/code-scanning/alerts"],listAlertsInstances:["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",{},{renamed:["codeScanning","listAlertInstances"]}],listCodeqlDatabases:["GET /repos/{owner}/{repo}/code-scanning/codeql/databases"],listRecentAnalyses:["GET /repos/{owner}/{repo}/code-scanning/analyses"],updateAlert:["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"],updateDefaultSetup:["PATCH /repos/{owner}/{repo}/code-scanning/default-setup"],uploadSarif:["POST /repos/{owner}/{repo}/code-scanning/sarifs"]},codeSecurity:{attachConfiguration:["POST /orgs/{org}/code-security/configurations/{configuration_id}/attach"],attachEnterpriseConfiguration:["POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach"],createConfiguration:["POST /orgs/{org}/code-security/configurations"],createConfigurationForEnterprise:["POST /enterprises/{enterprise}/code-security/configurations"],deleteConfiguration:["DELETE /orgs/{org}/code-security/configurations/{configuration_id}"],deleteConfigurationForEnterprise:["DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}"],detachConfiguration:["DELETE /orgs/{org}/code-security/configurations/detach"],getConfiguration:["GET /orgs/{org}/code-security/configurations/{configuration_id}"],getConfigurationForRepository:["GET /repos/{owner}/{repo}/code-security-configuration"],getConfigurationsForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations"],getConfigurationsForOrg:["GET /orgs/{org}/code-security/configurations"],getDefaultConfigurations:["GET /orgs/{org}/code-security/configurations/defaults"],getDefaultConfigurationsForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations/defaults"],getRepositoriesForConfiguration:["GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories"],getRepositoriesForEnterpriseConfiguration:["GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories"],getSingleConfigurationForEnterprise:["GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}"],setConfigurationAsDefault:["PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults"],setConfigurationAsDefaultForEnterprise:["PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults"],updateConfiguration:["PATCH /orgs/{org}/code-security/configurations/{configuration_id}"],updateEnterpriseConfiguration:["PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}"]},codesOfConduct:{getAllCodesOfConduct:["GET /codes_of_conduct"],getConductCode:["GET /codes_of_conduct/{key}"]},codespaces:{addRepositoryForSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],addSelectedRepoToOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"],checkPermissionsForDevcontainer:["GET /repos/{owner}/{repo}/codespaces/permissions_check"],codespaceMachinesForAuthenticatedUser:["GET /user/codespaces/{codespace_name}/machines"],createForAuthenticatedUser:["POST /user/codespaces"],createOrUpdateOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],createOrUpdateSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}"],createWithPrForAuthenticatedUser:["POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces"],createWithRepoForAuthenticatedUser:["POST /repos/{owner}/{repo}/codespaces"],deleteForAuthenticatedUser:["DELETE /user/codespaces/{codespace_name}"],deleteFromOrganization:["DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}"],deleteOrgSecret:["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],deleteSecretForAuthenticatedUser:["DELETE /user/codespaces/secrets/{secret_name}"],exportForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/exports"],getCodespacesForUserInOrg:["GET /orgs/{org}/members/{username}/codespaces"],getExportDetailsForAuthenticatedUser:["GET /user/codespaces/{codespace_name}/exports/{export_id}"],getForAuthenticatedUser:["GET /user/codespaces/{codespace_name}"],getOrgPublicKey:["GET /orgs/{org}/codespaces/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/codespaces/secrets/{secret_name}"],getPublicKeyForAuthenticatedUser:["GET /user/codespaces/secrets/public-key"],getRepoPublicKey:["GET /repos/{owner}/{repo}/codespaces/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],getSecretForAuthenticatedUser:["GET /user/codespaces/secrets/{secret_name}"],listDevcontainersInRepositoryForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/devcontainers"],listForAuthenticatedUser:["GET /user/codespaces"],listInOrganization:["GET /orgs/{org}/codespaces",{},{renamedParameters:{org_id:"org"}}],listInRepositoryForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces"],listOrgSecrets:["GET /orgs/{org}/codespaces/secrets"],listRepoSecrets:["GET /repos/{owner}/{repo}/codespaces/secrets"],listRepositoriesForSecretForAuthenticatedUser:["GET /user/codespaces/secrets/{secret_name}/repositories"],listSecretsForAuthenticatedUser:["GET /user/codespaces/secrets"],listSelectedReposForOrgSecret:["GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories"],preFlightWithRepoForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/new"],publishForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/publish"],removeRepositoryForSecretForAuthenticatedUser:["DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"],repoMachinesForAuthenticatedUser:["GET /repos/{owner}/{repo}/codespaces/machines"],setRepositoriesForSecretForAuthenticatedUser:["PUT /user/codespaces/secrets/{secret_name}/repositories"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories"],startForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/start"],stopForAuthenticatedUser:["POST /user/codespaces/{codespace_name}/stop"],stopInOrganization:["POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop"],updateForAuthenticatedUser:["PATCH /user/codespaces/{codespace_name}"]},copilot:{addCopilotSeatsForTeams:["POST /orgs/{org}/copilot/billing/selected_teams"],addCopilotSeatsForUsers:["POST /orgs/{org}/copilot/billing/selected_users"],cancelCopilotSeatAssignmentForTeams:["DELETE /orgs/{org}/copilot/billing/selected_teams"],cancelCopilotSeatAssignmentForUsers:["DELETE /orgs/{org}/copilot/billing/selected_users"],copilotMetricsForOrganization:["GET /orgs/{org}/copilot/metrics"],copilotMetricsForTeam:["GET /orgs/{org}/team/{team_slug}/copilot/metrics"],getCopilotOrganizationDetails:["GET /orgs/{org}/copilot/billing"],getCopilotSeatDetailsForUser:["GET /orgs/{org}/members/{username}/copilot"],listCopilotSeats:["GET /orgs/{org}/copilot/billing/seats"],usageMetricsForOrg:["GET /orgs/{org}/copilot/usage"],usageMetricsForTeam:["GET /orgs/{org}/team/{team_slug}/copilot/usage"]},dependabot:{addSelectedRepoToOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],createOrUpdateOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}"],createOrUpdateRepoSecret:["PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],deleteOrgSecret:["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"],deleteRepoSecret:["DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],getAlert:["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"],getOrgPublicKey:["GET /orgs/{org}/dependabot/secrets/public-key"],getOrgSecret:["GET /orgs/{org}/dependabot/secrets/{secret_name}"],getRepoPublicKey:["GET /repos/{owner}/{repo}/dependabot/secrets/public-key"],getRepoSecret:["GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],listAlertsForEnterprise:["GET /enterprises/{enterprise}/dependabot/alerts"],listAlertsForOrg:["GET /orgs/{org}/dependabot/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/dependabot/alerts"],listOrgSecrets:["GET /orgs/{org}/dependabot/secrets"],listRepoSecrets:["GET /repos/{owner}/{repo}/dependabot/secrets"],listSelectedReposForOrgSecret:["GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],removeSelectedRepoFromOrgSecret:["DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],setSelectedReposForOrgSecret:["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],updateAlert:["PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"]},dependencyGraph:{createRepositorySnapshot:["POST /repos/{owner}/{repo}/dependency-graph/snapshots"],diffRange:["GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}"],exportSbom:["GET /repos/{owner}/{repo}/dependency-graph/sbom"]},emojis:{get:["GET /emojis"]},gists:{checkIsStarred:["GET /gists/{gist_id}/star"],create:["POST /gists"],createComment:["POST /gists/{gist_id}/comments"],delete:["DELETE /gists/{gist_id}"],deleteComment:["DELETE /gists/{gist_id}/comments/{comment_id}"],fork:["POST /gists/{gist_id}/forks"],get:["GET /gists/{gist_id}"],getComment:["GET /gists/{gist_id}/comments/{comment_id}"],getRevision:["GET /gists/{gist_id}/{sha}"],list:["GET /gists"],listComments:["GET /gists/{gist_id}/comments"],listCommits:["GET /gists/{gist_id}/commits"],listForUser:["GET /users/{username}/gists"],listForks:["GET /gists/{gist_id}/forks"],listPublic:["GET /gists/public"],listStarred:["GET /gists/starred"],star:["PUT /gists/{gist_id}/star"],unstar:["DELETE /gists/{gist_id}/star"],update:["PATCH /gists/{gist_id}"],updateComment:["PATCH /gists/{gist_id}/comments/{comment_id}"]},git:{createBlob:["POST /repos/{owner}/{repo}/git/blobs"],createCommit:["POST /repos/{owner}/{repo}/git/commits"],createRef:["POST /repos/{owner}/{repo}/git/refs"],createTag:["POST /repos/{owner}/{repo}/git/tags"],createTree:["POST /repos/{owner}/{repo}/git/trees"],deleteRef:["DELETE /repos/{owner}/{repo}/git/refs/{ref}"],getBlob:["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"],getCommit:["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"],getRef:["GET /repos/{owner}/{repo}/git/ref/{ref}"],getTag:["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"],getTree:["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"],listMatchingRefs:["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"],updateRef:["PATCH /repos/{owner}/{repo}/git/refs/{ref}"]},gitignore:{getAllTemplates:["GET /gitignore/templates"],getTemplate:["GET /gitignore/templates/{name}"]},interactions:{getRestrictionsForAuthenticatedUser:["GET /user/interaction-limits"],getRestrictionsForOrg:["GET /orgs/{org}/interaction-limits"],getRestrictionsForRepo:["GET /repos/{owner}/{repo}/interaction-limits"],getRestrictionsForYourPublicRepos:["GET /user/interaction-limits",{},{renamed:["interactions","getRestrictionsForAuthenticatedUser"]}],removeRestrictionsForAuthenticatedUser:["DELETE /user/interaction-limits"],removeRestrictionsForOrg:["DELETE /orgs/{org}/interaction-limits"],removeRestrictionsForRepo:["DELETE /repos/{owner}/{repo}/interaction-limits"],removeRestrictionsForYourPublicRepos:["DELETE /user/interaction-limits",{},{renamed:["interactions","removeRestrictionsForAuthenticatedUser"]}],setRestrictionsForAuthenticatedUser:["PUT /user/interaction-limits"],setRestrictionsForOrg:["PUT /orgs/{org}/interaction-limits"],setRestrictionsForRepo:["PUT /repos/{owner}/{repo}/interaction-limits"],setRestrictionsForYourPublicRepos:["PUT /user/interaction-limits",{},{renamed:["interactions","setRestrictionsForAuthenticatedUser"]}]},issues:{addAssignees:["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"],addLabels:["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"],addSubIssue:["POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"],checkUserCanBeAssigned:["GET /repos/{owner}/{repo}/assignees/{assignee}"],checkUserCanBeAssignedToIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}"],create:["POST /repos/{owner}/{repo}/issues"],createComment:["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"],createLabel:["POST /repos/{owner}/{repo}/labels"],createMilestone:["POST /repos/{owner}/{repo}/milestones"],deleteComment:["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"],deleteLabel:["DELETE /repos/{owner}/{repo}/labels/{name}"],deleteMilestone:["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"],get:["GET /repos/{owner}/{repo}/issues/{issue_number}"],getComment:["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"],getEvent:["GET /repos/{owner}/{repo}/issues/events/{event_id}"],getLabel:["GET /repos/{owner}/{repo}/labels/{name}"],getMilestone:["GET /repos/{owner}/{repo}/milestones/{milestone_number}"],list:["GET /issues"],listAssignees:["GET /repos/{owner}/{repo}/assignees"],listComments:["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"],listCommentsForRepo:["GET /repos/{owner}/{repo}/issues/comments"],listEvents:["GET /repos/{owner}/{repo}/issues/{issue_number}/events"],listEventsForRepo:["GET /repos/{owner}/{repo}/issues/events"],listEventsForTimeline:["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"],listForAuthenticatedUser:["GET /user/issues"],listForOrg:["GET /orgs/{org}/issues"],listForRepo:["GET /repos/{owner}/{repo}/issues"],listLabelsForMilestone:["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"],listLabelsForRepo:["GET /repos/{owner}/{repo}/labels"],listLabelsOnIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"],listMilestones:["GET /repos/{owner}/{repo}/milestones"],listSubIssues:["GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"],lock:["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"],removeAllLabels:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"],removeAssignees:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"],removeLabel:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"],removeSubIssue:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue"],reprioritizeSubIssue:["PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority"],setLabels:["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"],unlock:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"],update:["PATCH /repos/{owner}/{repo}/issues/{issue_number}"],updateComment:["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"],updateLabel:["PATCH /repos/{owner}/{repo}/labels/{name}"],updateMilestone:["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"]},licenses:{get:["GET /licenses/{license}"],getAllCommonlyUsed:["GET /licenses"],getForRepo:["GET /repos/{owner}/{repo}/license"]},markdown:{render:["POST /markdown"],renderRaw:["POST /markdown/raw",{headers:{"content-type":"text/plain; charset=utf-8"}}]},meta:{get:["GET /meta"],getAllVersions:["GET /versions"],getOctocat:["GET /octocat"],getZen:["GET /zen"],root:["GET /"]},migrations:{deleteArchiveForAuthenticatedUser:["DELETE /user/migrations/{migration_id}/archive"],deleteArchiveForOrg:["DELETE /orgs/{org}/migrations/{migration_id}/archive"],downloadArchiveForOrg:["GET /orgs/{org}/migrations/{migration_id}/archive"],getArchiveForAuthenticatedUser:["GET /user/migrations/{migration_id}/archive"],getStatusForAuthenticatedUser:["GET /user/migrations/{migration_id}"],getStatusForOrg:["GET /orgs/{org}/migrations/{migration_id}"],listForAuthenticatedUser:["GET /user/migrations"],listForOrg:["GET /orgs/{org}/migrations"],listReposForAuthenticatedUser:["GET /user/migrations/{migration_id}/repositories"],listReposForOrg:["GET /orgs/{org}/migrations/{migration_id}/repositories"],listReposForUser:["GET /user/migrations/{migration_id}/repositories",{},{renamed:["migrations","listReposForAuthenticatedUser"]}],startForAuthenticatedUser:["POST /user/migrations"],startForOrg:["POST /orgs/{org}/migrations"],unlockRepoForAuthenticatedUser:["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"],unlockRepoForOrg:["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"]},oidc:{getOidcCustomSubTemplateForOrg:["GET /orgs/{org}/actions/oidc/customization/sub"],updateOidcCustomSubTemplateForOrg:["PUT /orgs/{org}/actions/oidc/customization/sub"]},orgs:{addSecurityManagerTeam:["PUT /orgs/{org}/security-managers/teams/{team_slug}",{},{deprecated:"octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team"}],assignTeamToOrgRole:["PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"],assignUserToOrgRole:["PUT /orgs/{org}/organization-roles/users/{username}/{role_id}"],blockUser:["PUT /orgs/{org}/blocks/{username}"],cancelInvitation:["DELETE /orgs/{org}/invitations/{invitation_id}"],checkBlockedUser:["GET /orgs/{org}/blocks/{username}"],checkMembershipForUser:["GET /orgs/{org}/members/{username}"],checkPublicMembershipForUser:["GET /orgs/{org}/public_members/{username}"],convertMemberToOutsideCollaborator:["PUT /orgs/{org}/outside_collaborators/{username}"],createInvitation:["POST /orgs/{org}/invitations"],createOrUpdateCustomProperties:["PATCH /orgs/{org}/properties/schema"],createOrUpdateCustomPropertiesValuesForRepos:["PATCH /orgs/{org}/properties/values"],createOrUpdateCustomProperty:["PUT /orgs/{org}/properties/schema/{custom_property_name}"],createWebhook:["POST /orgs/{org}/hooks"],delete:["DELETE /orgs/{org}"],deleteWebhook:["DELETE /orgs/{org}/hooks/{hook_id}"],enableOrDisableSecurityProductOnAllOrgRepos:["POST /orgs/{org}/{security_product}/{enablement}",{},{deprecated:"octokit.rest.orgs.enableOrDisableSecurityProductOnAllOrgRepos() is deprecated, see https://docs.github.com/rest/orgs/orgs#enable-or-disable-a-security-feature-for-an-organization"}],get:["GET /orgs/{org}"],getAllCustomProperties:["GET /orgs/{org}/properties/schema"],getCustomProperty:["GET /orgs/{org}/properties/schema/{custom_property_name}"],getMembershipForAuthenticatedUser:["GET /user/memberships/orgs/{org}"],getMembershipForUser:["GET /orgs/{org}/memberships/{username}"],getOrgRole:["GET /orgs/{org}/organization-roles/{role_id}"],getWebhook:["GET /orgs/{org}/hooks/{hook_id}"],getWebhookConfigForOrg:["GET /orgs/{org}/hooks/{hook_id}/config"],getWebhookDelivery:["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"],list:["GET /organizations"],listAppInstallations:["GET /orgs/{org}/installations"],listAttestations:["GET /orgs/{org}/attestations/{subject_digest}"],listBlockedUsers:["GET /orgs/{org}/blocks"],listCustomPropertiesValuesForRepos:["GET /orgs/{org}/properties/values"],listFailedInvitations:["GET /orgs/{org}/failed_invitations"],listForAuthenticatedUser:["GET /user/orgs"],listForUser:["GET /users/{username}/orgs"],listInvitationTeams:["GET /orgs/{org}/invitations/{invitation_id}/teams"],listMembers:["GET /orgs/{org}/members"],listMembershipsForAuthenticatedUser:["GET /user/memberships/orgs"],listOrgRoleTeams:["GET /orgs/{org}/organization-roles/{role_id}/teams"],listOrgRoleUsers:["GET /orgs/{org}/organization-roles/{role_id}/users"],listOrgRoles:["GET /orgs/{org}/organization-roles"],listOrganizationFineGrainedPermissions:["GET /orgs/{org}/organization-fine-grained-permissions"],listOutsideCollaborators:["GET /orgs/{org}/outside_collaborators"],listPatGrantRepositories:["GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories"],listPatGrantRequestRepositories:["GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories"],listPatGrantRequests:["GET /orgs/{org}/personal-access-token-requests"],listPatGrants:["GET /orgs/{org}/personal-access-tokens"],listPendingInvitations:["GET /orgs/{org}/invitations"],listPublicMembers:["GET /orgs/{org}/public_members"],listSecurityManagerTeams:["GET /orgs/{org}/security-managers",{},{deprecated:"octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams"}],listWebhookDeliveries:["GET /orgs/{org}/hooks/{hook_id}/deliveries"],listWebhooks:["GET /orgs/{org}/hooks"],pingWebhook:["POST /orgs/{org}/hooks/{hook_id}/pings"],redeliverWebhookDelivery:["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],removeCustomProperty:["DELETE /orgs/{org}/properties/schema/{custom_property_name}"],removeMember:["DELETE /orgs/{org}/members/{username}"],removeMembershipForUser:["DELETE /orgs/{org}/memberships/{username}"],removeOutsideCollaborator:["DELETE /orgs/{org}/outside_collaborators/{username}"],removePublicMembershipForAuthenticatedUser:["DELETE /orgs/{org}/public_members/{username}"],removeSecurityManagerTeam:["DELETE /orgs/{org}/security-managers/teams/{team_slug}",{},{deprecated:"octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team"}],reviewPatGrantRequest:["POST /orgs/{org}/personal-access-token-requests/{pat_request_id}"],reviewPatGrantRequestsInBulk:["POST /orgs/{org}/personal-access-token-requests"],revokeAllOrgRolesTeam:["DELETE /orgs/{org}/organization-roles/teams/{team_slug}"],revokeAllOrgRolesUser:["DELETE /orgs/{org}/organization-roles/users/{username}"],revokeOrgRoleTeam:["DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"],revokeOrgRoleUser:["DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}"],setMembershipForUser:["PUT /orgs/{org}/memberships/{username}"],setPublicMembershipForAuthenticatedUser:["PUT /orgs/{org}/public_members/{username}"],unblockUser:["DELETE /orgs/{org}/blocks/{username}"],update:["PATCH /orgs/{org}"],updateMembershipForAuthenticatedUser:["PATCH /user/memberships/orgs/{org}"],updatePatAccess:["POST /orgs/{org}/personal-access-tokens/{pat_id}"],updatePatAccesses:["POST /orgs/{org}/personal-access-tokens"],updateWebhook:["PATCH /orgs/{org}/hooks/{hook_id}"],updateWebhookConfigForOrg:["PATCH /orgs/{org}/hooks/{hook_id}/config"]},packages:{deletePackageForAuthenticatedUser:["DELETE /user/packages/{package_type}/{package_name}"],deletePackageForOrg:["DELETE /orgs/{org}/packages/{package_type}/{package_name}"],deletePackageForUser:["DELETE /users/{username}/packages/{package_type}/{package_name}"],deletePackageVersionForAuthenticatedUser:["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],deletePackageVersionForOrg:["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],deletePackageVersionForUser:["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],getAllPackageVersionsForAPackageOwnedByAnOrg:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions",{},{renamed:["packages","getAllPackageVersionsForPackageOwnedByOrg"]}],getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions",{},{renamed:["packages","getAllPackageVersionsForPackageOwnedByAuthenticatedUser"]}],getAllPackageVersionsForPackageOwnedByAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions"],getAllPackageVersionsForPackageOwnedByOrg:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"],getAllPackageVersionsForPackageOwnedByUser:["GET /users/{username}/packages/{package_type}/{package_name}/versions"],getPackageForAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}"],getPackageForOrganization:["GET /orgs/{org}/packages/{package_type}/{package_name}"],getPackageForUser:["GET /users/{username}/packages/{package_type}/{package_name}"],getPackageVersionForAuthenticatedUser:["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],getPackageVersionForOrganization:["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],getPackageVersionForUser:["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],listDockerMigrationConflictingPackagesForAuthenticatedUser:["GET /user/docker/conflicts"],listDockerMigrationConflictingPackagesForOrganization:["GET /orgs/{org}/docker/conflicts"],listDockerMigrationConflictingPackagesForUser:["GET /users/{username}/docker/conflicts"],listPackagesForAuthenticatedUser:["GET /user/packages"],listPackagesForOrganization:["GET /orgs/{org}/packages"],listPackagesForUser:["GET /users/{username}/packages"],restorePackageForAuthenticatedUser:["POST /user/packages/{package_type}/{package_name}/restore{?token}"],restorePackageForOrg:["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"],restorePackageForUser:["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"],restorePackageVersionForAuthenticatedUser:["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],restorePackageVersionForOrg:["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],restorePackageVersionForUser:["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"]},privateRegistries:{createOrgPrivateRegistry:["POST /orgs/{org}/private-registries"],deleteOrgPrivateRegistry:["DELETE /orgs/{org}/private-registries/{secret_name}"],getOrgPrivateRegistry:["GET /orgs/{org}/private-registries/{secret_name}"],getOrgPublicKey:["GET /orgs/{org}/private-registries/public-key"],listOrgPrivateRegistries:["GET /orgs/{org}/private-registries"],updateOrgPrivateRegistry:["PATCH /orgs/{org}/private-registries/{secret_name}"]},projects:{addCollaborator:["PUT /projects/{project_id}/collaborators/{username}"],createCard:["POST /projects/columns/{column_id}/cards"],createColumn:["POST /projects/{project_id}/columns"],createForAuthenticatedUser:["POST /user/projects"],createForOrg:["POST /orgs/{org}/projects"],createForRepo:["POST /repos/{owner}/{repo}/projects"],delete:["DELETE /projects/{project_id}"],deleteCard:["DELETE /projects/columns/cards/{card_id}"],deleteColumn:["DELETE /projects/columns/{column_id}"],get:["GET /projects/{project_id}"],getCard:["GET /projects/columns/cards/{card_id}"],getColumn:["GET /projects/columns/{column_id}"],getPermissionForUser:["GET /projects/{project_id}/collaborators/{username}/permission"],listCards:["GET /projects/columns/{column_id}/cards"],listCollaborators:["GET /projects/{project_id}/collaborators"],listColumns:["GET /projects/{project_id}/columns"],listForOrg:["GET /orgs/{org}/projects"],listForRepo:["GET /repos/{owner}/{repo}/projects"],listForUser:["GET /users/{username}/projects"],moveCard:["POST /projects/columns/cards/{card_id}/moves"],moveColumn:["POST /projects/columns/{column_id}/moves"],removeCollaborator:["DELETE /projects/{project_id}/collaborators/{username}"],update:["PATCH /projects/{project_id}"],updateCard:["PATCH /projects/columns/cards/{card_id}"],updateColumn:["PATCH /projects/columns/{column_id}"]},pulls:{checkIfMerged:["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"],create:["POST /repos/{owner}/{repo}/pulls"],createReplyForReviewComment:["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"],createReview:["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],createReviewComment:["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"],deletePendingReview:["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],deleteReviewComment:["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"],dismissReview:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"],get:["GET /repos/{owner}/{repo}/pulls/{pull_number}"],getReview:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],getReviewComment:["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"],list:["GET /repos/{owner}/{repo}/pulls"],listCommentsForReview:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"],listCommits:["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"],listFiles:["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"],listRequestedReviewers:["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],listReviewComments:["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"],listReviewCommentsForRepo:["GET /repos/{owner}/{repo}/pulls/comments"],listReviews:["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],merge:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"],removeRequestedReviewers:["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],requestReviewers:["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],submitReview:["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"],update:["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"],updateBranch:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"],updateReview:["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],updateReviewComment:["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"]},rateLimit:{get:["GET /rate_limit"]},reactions:{createForCommitComment:["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"],createForIssue:["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"],createForIssueComment:["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],createForPullRequestReviewComment:["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],createForRelease:["POST /repos/{owner}/{repo}/releases/{release_id}/reactions"],createForTeamDiscussionCommentInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],createForTeamDiscussionInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"],deleteForCommitComment:["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"],deleteForIssue:["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"],deleteForIssueComment:["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"],deleteForPullRequestComment:["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"],deleteForRelease:["DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}"],deleteForTeamDiscussion:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"],deleteForTeamDiscussionComment:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"],listForCommitComment:["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"],listForIssue:["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"],listForIssueComment:["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],listForPullRequestReviewComment:["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],listForRelease:["GET /repos/{owner}/{repo}/releases/{release_id}/reactions"],listForTeamDiscussionCommentInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],listForTeamDiscussionInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"]},repos:{acceptInvitation:["PATCH /user/repository_invitations/{invitation_id}",{},{renamed:["repos","acceptInvitationForAuthenticatedUser"]}],acceptInvitationForAuthenticatedUser:["PATCH /user/repository_invitations/{invitation_id}"],addAppAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],addCollaborator:["PUT /repos/{owner}/{repo}/collaborators/{username}"],addStatusCheckContexts:["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],addTeamAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],addUserAccessRestrictions:["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],cancelPagesDeployment:["POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel"],checkAutomatedSecurityFixes:["GET /repos/{owner}/{repo}/automated-security-fixes"],checkCollaborator:["GET /repos/{owner}/{repo}/collaborators/{username}"],checkPrivateVulnerabilityReporting:["GET /repos/{owner}/{repo}/private-vulnerability-reporting"],checkVulnerabilityAlerts:["GET /repos/{owner}/{repo}/vulnerability-alerts"],codeownersErrors:["GET /repos/{owner}/{repo}/codeowners/errors"],compareCommits:["GET /repos/{owner}/{repo}/compare/{base}...{head}"],compareCommitsWithBasehead:["GET /repos/{owner}/{repo}/compare/{basehead}"],createAttestation:["POST /repos/{owner}/{repo}/attestations"],createAutolink:["POST /repos/{owner}/{repo}/autolinks"],createCommitComment:["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"],createCommitSignatureProtection:["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],createCommitStatus:["POST /repos/{owner}/{repo}/statuses/{sha}"],createDeployKey:["POST /repos/{owner}/{repo}/keys"],createDeployment:["POST /repos/{owner}/{repo}/deployments"],createDeploymentBranchPolicy:["POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"],createDeploymentProtectionRule:["POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"],createDeploymentStatus:["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],createDispatchEvent:["POST /repos/{owner}/{repo}/dispatches"],createForAuthenticatedUser:["POST /user/repos"],createFork:["POST /repos/{owner}/{repo}/forks"],createInOrg:["POST /orgs/{org}/repos"],createOrUpdateCustomPropertiesValues:["PATCH /repos/{owner}/{repo}/properties/values"],createOrUpdateEnvironment:["PUT /repos/{owner}/{repo}/environments/{environment_name}"],createOrUpdateFileContents:["PUT /repos/{owner}/{repo}/contents/{path}"],createOrgRuleset:["POST /orgs/{org}/rulesets"],createPagesDeployment:["POST /repos/{owner}/{repo}/pages/deployments"],createPagesSite:["POST /repos/{owner}/{repo}/pages"],createRelease:["POST /repos/{owner}/{repo}/releases"],createRepoRuleset:["POST /repos/{owner}/{repo}/rulesets"],createUsingTemplate:["POST /repos/{template_owner}/{template_repo}/generate"],createWebhook:["POST /repos/{owner}/{repo}/hooks"],declineInvitation:["DELETE /user/repository_invitations/{invitation_id}",{},{renamed:["repos","declineInvitationForAuthenticatedUser"]}],declineInvitationForAuthenticatedUser:["DELETE /user/repository_invitations/{invitation_id}"],delete:["DELETE /repos/{owner}/{repo}"],deleteAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],deleteAdminBranchProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],deleteAnEnvironment:["DELETE /repos/{owner}/{repo}/environments/{environment_name}"],deleteAutolink:["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"],deleteBranchProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"],deleteCommitComment:["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],deleteCommitSignatureProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],deleteDeployKey:["DELETE /repos/{owner}/{repo}/keys/{key_id}"],deleteDeployment:["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"],deleteDeploymentBranchPolicy:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],deleteFile:["DELETE /repos/{owner}/{repo}/contents/{path}"],deleteInvitation:["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"],deleteOrgRuleset:["DELETE /orgs/{org}/rulesets/{ruleset_id}"],deletePagesSite:["DELETE /repos/{owner}/{repo}/pages"],deletePullRequestReviewProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],deleteRelease:["DELETE /repos/{owner}/{repo}/releases/{release_id}"],deleteReleaseAsset:["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"],deleteRepoRuleset:["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"],deleteWebhook:["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"],disableAutomatedSecurityFixes:["DELETE /repos/{owner}/{repo}/automated-security-fixes"],disableDeploymentProtectionRule:["DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"],disablePrivateVulnerabilityReporting:["DELETE /repos/{owner}/{repo}/private-vulnerability-reporting"],disableVulnerabilityAlerts:["DELETE /repos/{owner}/{repo}/vulnerability-alerts"],downloadArchive:["GET /repos/{owner}/{repo}/zipball/{ref}",{},{renamed:["repos","downloadZipballArchive"]}],downloadTarballArchive:["GET /repos/{owner}/{repo}/tarball/{ref}"],downloadZipballArchive:["GET /repos/{owner}/{repo}/zipball/{ref}"],enableAutomatedSecurityFixes:["PUT /repos/{owner}/{repo}/automated-security-fixes"],enablePrivateVulnerabilityReporting:["PUT /repos/{owner}/{repo}/private-vulnerability-reporting"],enableVulnerabilityAlerts:["PUT /repos/{owner}/{repo}/vulnerability-alerts"],generateReleaseNotes:["POST /repos/{owner}/{repo}/releases/generate-notes"],get:["GET /repos/{owner}/{repo}"],getAccessRestrictions:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],getAdminBranchProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],getAllDeploymentProtectionRules:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"],getAllEnvironments:["GET /repos/{owner}/{repo}/environments"],getAllStatusCheckContexts:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"],getAllTopics:["GET /repos/{owner}/{repo}/topics"],getAppsWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"],getAutolink:["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"],getBranch:["GET /repos/{owner}/{repo}/branches/{branch}"],getBranchProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection"],getBranchRules:["GET /repos/{owner}/{repo}/rules/branches/{branch}"],getClones:["GET /repos/{owner}/{repo}/traffic/clones"],getCodeFrequencyStats:["GET /repos/{owner}/{repo}/stats/code_frequency"],getCollaboratorPermissionLevel:["GET /repos/{owner}/{repo}/collaborators/{username}/permission"],getCombinedStatusForRef:["GET /repos/{owner}/{repo}/commits/{ref}/status"],getCommit:["GET /repos/{owner}/{repo}/commits/{ref}"],getCommitActivityStats:["GET /repos/{owner}/{repo}/stats/commit_activity"],getCommitComment:["GET /repos/{owner}/{repo}/comments/{comment_id}"],getCommitSignatureProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],getCommunityProfileMetrics:["GET /repos/{owner}/{repo}/community/profile"],getContent:["GET /repos/{owner}/{repo}/contents/{path}"],getContributorsStats:["GET /repos/{owner}/{repo}/stats/contributors"],getCustomDeploymentProtectionRule:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"],getCustomPropertiesValues:["GET /repos/{owner}/{repo}/properties/values"],getDeployKey:["GET /repos/{owner}/{repo}/keys/{key_id}"],getDeployment:["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],getDeploymentBranchPolicy:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],getDeploymentStatus:["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"],getEnvironment:["GET /repos/{owner}/{repo}/environments/{environment_name}"],getLatestPagesBuild:["GET /repos/{owner}/{repo}/pages/builds/latest"],getLatestRelease:["GET /repos/{owner}/{repo}/releases/latest"],getOrgRuleSuite:["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"],getOrgRuleSuites:["GET /orgs/{org}/rulesets/rule-suites"],getOrgRuleset:["GET /orgs/{org}/rulesets/{ruleset_id}"],getOrgRulesets:["GET /orgs/{org}/rulesets"],getPages:["GET /repos/{owner}/{repo}/pages"],getPagesBuild:["GET /repos/{owner}/{repo}/pages/builds/{build_id}"],getPagesDeployment:["GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}"],getPagesHealthCheck:["GET /repos/{owner}/{repo}/pages/health"],getParticipationStats:["GET /repos/{owner}/{repo}/stats/participation"],getPullRequestReviewProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],getPunchCardStats:["GET /repos/{owner}/{repo}/stats/punch_card"],getReadme:["GET /repos/{owner}/{repo}/readme"],getReadmeInDirectory:["GET /repos/{owner}/{repo}/readme/{dir}"],getRelease:["GET /repos/{owner}/{repo}/releases/{release_id}"],getReleaseAsset:["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],getReleaseByTag:["GET /repos/{owner}/{repo}/releases/tags/{tag}"],getRepoRuleSuite:["GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}"],getRepoRuleSuites:["GET /repos/{owner}/{repo}/rulesets/rule-suites"],getRepoRuleset:["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"],getRepoRulesets:["GET /repos/{owner}/{repo}/rulesets"],getStatusChecksProtection:["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],getTeamsWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"],getTopPaths:["GET /repos/{owner}/{repo}/traffic/popular/paths"],getTopReferrers:["GET /repos/{owner}/{repo}/traffic/popular/referrers"],getUsersWithAccessToProtectedBranch:["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"],getViews:["GET /repos/{owner}/{repo}/traffic/views"],getWebhook:["GET /repos/{owner}/{repo}/hooks/{hook_id}"],getWebhookConfigForRepo:["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"],getWebhookDelivery:["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"],listActivities:["GET /repos/{owner}/{repo}/activity"],listAttestations:["GET /repos/{owner}/{repo}/attestations/{subject_digest}"],listAutolinks:["GET /repos/{owner}/{repo}/autolinks"],listBranches:["GET /repos/{owner}/{repo}/branches"],listBranchesForHeadCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"],listCollaborators:["GET /repos/{owner}/{repo}/collaborators"],listCommentsForCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"],listCommitCommentsForRepo:["GET /repos/{owner}/{repo}/comments"],listCommitStatusesForRef:["GET /repos/{owner}/{repo}/commits/{ref}/statuses"],listCommits:["GET /repos/{owner}/{repo}/commits"],listContributors:["GET /repos/{owner}/{repo}/contributors"],listCustomDeploymentRuleIntegrations:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps"],listDeployKeys:["GET /repos/{owner}/{repo}/keys"],listDeploymentBranchPolicies:["GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"],listDeploymentStatuses:["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],listDeployments:["GET /repos/{owner}/{repo}/deployments"],listForAuthenticatedUser:["GET /user/repos"],listForOrg:["GET /orgs/{org}/repos"],listForUser:["GET /users/{username}/repos"],listForks:["GET /repos/{owner}/{repo}/forks"],listInvitations:["GET /repos/{owner}/{repo}/invitations"],listInvitationsForAuthenticatedUser:["GET /user/repository_invitations"],listLanguages:["GET /repos/{owner}/{repo}/languages"],listPagesBuilds:["GET /repos/{owner}/{repo}/pages/builds"],listPublic:["GET /repositories"],listPullRequestsAssociatedWithCommit:["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"],listReleaseAssets:["GET /repos/{owner}/{repo}/releases/{release_id}/assets"],listReleases:["GET /repos/{owner}/{repo}/releases"],listTags:["GET /repos/{owner}/{repo}/tags"],listTeams:["GET /repos/{owner}/{repo}/teams"],listWebhookDeliveries:["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"],listWebhooks:["GET /repos/{owner}/{repo}/hooks"],merge:["POST /repos/{owner}/{repo}/merges"],mergeUpstream:["POST /repos/{owner}/{repo}/merge-upstream"],pingWebhook:["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"],redeliverWebhookDelivery:["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],removeAppAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],removeCollaborator:["DELETE /repos/{owner}/{repo}/collaborators/{username}"],removeStatusCheckContexts:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],removeStatusCheckProtection:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],removeTeamAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],removeUserAccessRestrictions:["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],renameBranch:["POST /repos/{owner}/{repo}/branches/{branch}/rename"],replaceAllTopics:["PUT /repos/{owner}/{repo}/topics"],requestPagesBuild:["POST /repos/{owner}/{repo}/pages/builds"],setAdminBranchProtection:["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],setAppAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",{},{mapToData:"apps"}],setStatusCheckContexts:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",{},{mapToData:"contexts"}],setTeamAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",{},{mapToData:"teams"}],setUserAccessRestrictions:["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",{},{mapToData:"users"}],testPushWebhook:["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"],transfer:["POST /repos/{owner}/{repo}/transfer"],update:["PATCH /repos/{owner}/{repo}"],updateBranchProtection:["PUT /repos/{owner}/{repo}/branches/{branch}/protection"],updateCommitComment:["PATCH /repos/{owner}/{repo}/comments/{comment_id}"],updateDeploymentBranchPolicy:["PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"],updateInformationAboutPagesSite:["PUT /repos/{owner}/{repo}/pages"],updateInvitation:["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"],updateOrgRuleset:["PUT /orgs/{org}/rulesets/{ruleset_id}"],updatePullRequestReviewProtection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],updateRelease:["PATCH /repos/{owner}/{repo}/releases/{release_id}"],updateReleaseAsset:["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"],updateRepoRuleset:["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"],updateStatusCheckPotection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks",{},{renamed:["repos","updateStatusCheckProtection"]}],updateStatusCheckProtection:["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],updateWebhook:["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"],updateWebhookConfigForRepo:["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"],uploadReleaseAsset:["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}",{baseUrl:"https://uploads.github.com"}]},search:{code:["GET /search/code"],commits:["GET /search/commits"],issuesAndPullRequests:["GET /search/issues"],labels:["GET /search/labels"],repos:["GET /search/repositories"],topics:["GET /search/topics"],users:["GET /search/users"]},secretScanning:{createPushProtectionBypass:["POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses"],getAlert:["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],getScanHistory:["GET /repos/{owner}/{repo}/secret-scanning/scan-history"],listAlertsForEnterprise:["GET /enterprises/{enterprise}/secret-scanning/alerts"],listAlertsForOrg:["GET /orgs/{org}/secret-scanning/alerts"],listAlertsForRepo:["GET /repos/{owner}/{repo}/secret-scanning/alerts"],listLocationsForAlert:["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations"],updateAlert:["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"]},securityAdvisories:{createFork:["POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks"],createPrivateVulnerabilityReport:["POST /repos/{owner}/{repo}/security-advisories/reports"],createRepositoryAdvisory:["POST /repos/{owner}/{repo}/security-advisories"],createRepositoryAdvisoryCveRequest:["POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve"],getGlobalAdvisory:["GET /advisories/{ghsa_id}"],getRepositoryAdvisory:["GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}"],listGlobalAdvisories:["GET /advisories"],listOrgRepositoryAdvisories:["GET /orgs/{org}/security-advisories"],listRepositoryAdvisories:["GET /repos/{owner}/{repo}/security-advisories"],updateRepositoryAdvisory:["PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}"]},teams:{addOrUpdateMembershipForUserInOrg:["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"],addOrUpdateProjectPermissionsInOrg:["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}"],addOrUpdateRepoPermissionsInOrg:["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],checkPermissionsForProjectInOrg:["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}"],checkPermissionsForRepoInOrg:["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],create:["POST /orgs/{org}/teams"],createDiscussionCommentInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],createDiscussionInOrg:["POST /orgs/{org}/teams/{team_slug}/discussions"],deleteDiscussionCommentInOrg:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],deleteDiscussionInOrg:["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],deleteInOrg:["DELETE /orgs/{org}/teams/{team_slug}"],getByName:["GET /orgs/{org}/teams/{team_slug}"],getDiscussionCommentInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],getDiscussionInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],getMembershipForUserInOrg:["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"],list:["GET /orgs/{org}/teams"],listChildInOrg:["GET /orgs/{org}/teams/{team_slug}/teams"],listDiscussionCommentsInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],listDiscussionsInOrg:["GET /orgs/{org}/teams/{team_slug}/discussions"],listForAuthenticatedUser:["GET /user/teams"],listMembersInOrg:["GET /orgs/{org}/teams/{team_slug}/members"],listPendingInvitationsInOrg:["GET /orgs/{org}/teams/{team_slug}/invitations"],listProjectsInOrg:["GET /orgs/{org}/teams/{team_slug}/projects"],listReposInOrg:["GET /orgs/{org}/teams/{team_slug}/repos"],removeMembershipForUserInOrg:["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"],removeProjectInOrg:["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"],removeRepoInOrg:["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],updateDiscussionCommentInOrg:["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],updateDiscussionInOrg:["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],updateInOrg:["PATCH /orgs/{org}/teams/{team_slug}"]},users:{addEmailForAuthenticated:["POST /user/emails",{},{renamed:["users","addEmailForAuthenticatedUser"]}],addEmailForAuthenticatedUser:["POST /user/emails"],addSocialAccountForAuthenticatedUser:["POST /user/social_accounts"],block:["PUT /user/blocks/{username}"],checkBlocked:["GET /user/blocks/{username}"],checkFollowingForUser:["GET /users/{username}/following/{target_user}"],checkPersonIsFollowedByAuthenticated:["GET /user/following/{username}"],createGpgKeyForAuthenticated:["POST /user/gpg_keys",{},{renamed:["users","createGpgKeyForAuthenticatedUser"]}],createGpgKeyForAuthenticatedUser:["POST /user/gpg_keys"],createPublicSshKeyForAuthenticated:["POST /user/keys",{},{renamed:["users","createPublicSshKeyForAuthenticatedUser"]}],createPublicSshKeyForAuthenticatedUser:["POST /user/keys"],createSshSigningKeyForAuthenticatedUser:["POST /user/ssh_signing_keys"],deleteEmailForAuthenticated:["DELETE /user/emails",{},{renamed:["users","deleteEmailForAuthenticatedUser"]}],deleteEmailForAuthenticatedUser:["DELETE /user/emails"],deleteGpgKeyForAuthenticated:["DELETE /user/gpg_keys/{gpg_key_id}",{},{renamed:["users","deleteGpgKeyForAuthenticatedUser"]}],deleteGpgKeyForAuthenticatedUser:["DELETE /user/gpg_keys/{gpg_key_id}"],deletePublicSshKeyForAuthenticated:["DELETE /user/keys/{key_id}",{},{renamed:["users","deletePublicSshKeyForAuthenticatedUser"]}],deletePublicSshKeyForAuthenticatedUser:["DELETE /user/keys/{key_id}"],deleteSocialAccountForAuthenticatedUser:["DELETE /user/social_accounts"],deleteSshSigningKeyForAuthenticatedUser:["DELETE /user/ssh_signing_keys/{ssh_signing_key_id}"],follow:["PUT /user/following/{username}"],getAuthenticated:["GET /user"],getById:["GET /user/{account_id}"],getByUsername:["GET /users/{username}"],getContextForUser:["GET /users/{username}/hovercard"],getGpgKeyForAuthenticated:["GET /user/gpg_keys/{gpg_key_id}",{},{renamed:["users","getGpgKeyForAuthenticatedUser"]}],getGpgKeyForAuthenticatedUser:["GET /user/gpg_keys/{gpg_key_id}"],getPublicSshKeyForAuthenticated:["GET /user/keys/{key_id}",{},{renamed:["users","getPublicSshKeyForAuthenticatedUser"]}],getPublicSshKeyForAuthenticatedUser:["GET /user/keys/{key_id}"],getSshSigningKeyForAuthenticatedUser:["GET /user/ssh_signing_keys/{ssh_signing_key_id}"],list:["GET /users"],listAttestations:["GET /users/{username}/attestations/{subject_digest}"],listBlockedByAuthenticated:["GET /user/blocks",{},{renamed:["users","listBlockedByAuthenticatedUser"]}],listBlockedByAuthenticatedUser:["GET /user/blocks"],listEmailsForAuthenticated:["GET /user/emails",{},{renamed:["users","listEmailsForAuthenticatedUser"]}],listEmailsForAuthenticatedUser:["GET /user/emails"],listFollowedByAuthenticated:["GET /user/following",{},{renamed:["users","listFollowedByAuthenticatedUser"]}],listFollowedByAuthenticatedUser:["GET /user/following"],listFollowersForAuthenticatedUser:["GET /user/followers"],listFollowersForUser:["GET /users/{username}/followers"],listFollowingForUser:["GET /users/{username}/following"],listGpgKeysForAuthenticated:["GET /user/gpg_keys",{},{renamed:["users","listGpgKeysForAuthenticatedUser"]}],listGpgKeysForAuthenticatedUser:["GET /user/gpg_keys"],listGpgKeysForUser:["GET /users/{username}/gpg_keys"],listPublicEmailsForAuthenticated:["GET /user/public_emails",{},{renamed:["users","listPublicEmailsForAuthenticatedUser"]}],listPublicEmailsForAuthenticatedUser:["GET /user/public_emails"],listPublicKeysForUser:["GET /users/{username}/keys"],listPublicSshKeysForAuthenticated:["GET /user/keys",{},{renamed:["users","listPublicSshKeysForAuthenticatedUser"]}],listPublicSshKeysForAuthenticatedUser:["GET /user/keys"],listSocialAccountsForAuthenticatedUser:["GET /user/social_accounts"],listSocialAccountsForUser:["GET /users/{username}/social_accounts"],listSshSigningKeysForAuthenticatedUser:["GET /user/ssh_signing_keys"],listSshSigningKeysForUser:["GET /users/{username}/ssh_signing_keys"],setPrimaryEmailVisibilityForAuthenticated:["PATCH /user/email/visibility",{},{renamed:["users","setPrimaryEmailVisibilityForAuthenticatedUser"]}],setPrimaryEmailVisibilityForAuthenticatedUser:["PATCH /user/email/visibility"],unblock:["DELETE /user/blocks/{username}"],unfollow:["DELETE /user/following/{username}"],updateAuthenticated:["PATCH /user"]}},uvE=mD5;var jxn=new Map;for(let[e,t]of Object.entries(uvE))for(let[r,i]of Object.entries(t)){let[n,a,o]=i,[c,d]=n.split(/ /),s=Object.assign({method:c,url:d},a);jxn.has(e)||jxn.set(e,new Map),jxn.get(e).set(r,{scope:e,methodName:r,endpointDefaults:s,decorations:o})}var PD5={has({scope:e},t){return jxn.get(e).has(t)},getOwnPropertyDescriptor(e,t){return{value:this.get(e,t),configurable:!0,writable:!0,enumerable:!0}},defineProperty(e,t,r){return Object.defineProperty(e.cache,t,r),!0},deleteProperty(e,t){return delete e.cache[t],!0},ownKeys({scope:e}){return[...jxn.get(e).keys()]},set(e,t,r){return e.cache[t]=r},get({octokit:e,scope:t,cache:r},i){if(r[i])return r[i];let n=jxn.get(t).get(i);if(!n)return;let{endpointDefaults:a,decorations:o}=n;return o?r[i]=jD5(e,t,i,a,o):r[i]=e.request.defaults(a),r[i]}};function Osp(e){let t={};for(let r of jxn.keys())t[r]=new Proxy({octokit:e,scope:r,cache:{}},PD5);return t}function jD5(e,t,r,i,n){let a=e.request.defaults(i);function o(...c){let d=a.endpoint.merge(...c);if(n.mapToData)return d=Object.assign({},d,{data:d[n.mapToData],[n.mapToData]:void 0}),a(d);if(n.renamed){let[s,u]=n.renamed;e.log.warn(`octokit.${t}.${r}() has been renamed to octokit.${s}.${u}()`)}if(n.deprecated&&e.log.warn(n.deprecated),n.renamedParameters){let s=a.endpoint.merge(...c);for(let[u,l]of Object.entries(n.renamedParameters))u in s&&(e.log.warn(`"${u}" parameter is deprecated for "octokit.${t}.${r}()". Use "${l}" instead`),l in s||(s[l]=s[u]),delete s[u]);return a(s)}return a(...c)}return Object.assign(o,a)}function wD5(e){return{rest:Osp(e)}}wD5.VERSION=gsp;function Asp(e){let t=Osp(e);return{...t,rest:t}}Asp.VERSION=gsp;var ED5="20.1.2",svE=ivE.plugin(ysp,Asp,vsp).defaults({userAgent:`octokit-rest.js/${ED5}`});var ARi=ce(require("fs/promises"),1),msp=ce(require("os"),1),lvE=ce(require("path"),1),Psp=ce(fG(),1);async function fvE({token:e,projectConfig:t,workspace:r,generatorGroup:i,version:n,keepDocker:a,inspect:o,context:c,absolutePathToPreview:d,runner:s,ai:u}){(await Promise.all(i.generators.map(async p=>c.runInteractiveTask({name:p.name},async _=>{p=(z=>FT(z,{onError:F=>_.failAndThrow(F)}))(p);let y=await r.toFernWorkspace({context:c},Aoa(p),p.apiOverride?.specs),b=Axn({apiName:y.definition.rootApiFile.contents.name,organization:t.organization,generatorInvocation:p}),v=SD5(p);n=n??await WLc({packageName:v,generatorInvocation:p});let O=lS({workspace:y,audiences:i.audiences,generationLanguage:p.language,keywords:p.keywords,smartCasing:p.smartCasing,exampleGeneration:{includeOptionalRequestPropertyExamples:!1,disabled:p.disableExamples},readme:p.readme,version:n??await WLc({packageName:v,generatorInvocation:p}),packageName:v,context:c,sourceResolver:new cS(c,y),dynamicGeneratorConfig:b,generationMetadata:{cliVersion:r.cliVersion,generatorName:p.name,generatorVersion:p.version,generatorConfig:p.config}}),A=I4({token:e?.value});if(p.absolutePathToLocalOutput==null&&(e=await MZn(),e==null)){_.failWithoutThrowing("Please provide a FERN_TOKEN in your environment.");return}let g=await A.organization.get(ny.OrganizationId(t.organization));if(p.absolutePathToLocalOutput==null&&!g.ok){_.failWithoutThrowing(`Failed to load details for organization ${t.organization}.`);return}g.ok&&(g.body.isWhitelabled&&(O.readmeConfig==null&&(O.readmeConfig=qD5),O.readmeConfig.whiteLabel=!0),O.selfHosted=g.body.selfHostedSdKs);let m=ID5({generatorInvocation:p,org:g.ok?g.body:void 0,version:n,packageName:v,context:_});m!=null&&(O.publishConfig=m);let j=MD5(d,p),M=j??p.absolutePathToLocalOutput??Cr.of(await Psp.default.dir().then(z=>z.path)),w=TD5(p,j!=null);if(n!=null&&NKs(n)&&w==null&&c.failAndThrow(`Automatic versioning (--version AUTO) requires a self-hosted GitHub repository configuration. Regular GitHub repositories are not supported because auto versioning needs to push changes back to the repository. Please configure your generator with self-hosted GitHub output in generators.yml. Example:
|