fern-api 3.64.3 → 3.64.4
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
|
@@ -1355,7 +1355,7 @@ ${SYh.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&y3c(th
|
|
|
1355
1355
|
`+_An.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?_An.default.cyan(zYh(t,this.opt.mask)):_An.default.italic(_An.default.dim("[hidden]")):this.opt.mask?zYh(t,this.opt.mask):_An.default.italic(_An.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 anu=ce(ON(),1);var RXh=ce(X3c(),1),inu=require("child_process"),Xca=require("fs"),rnu=ce(require("path"),1),zXh=ce(require("os"),1),NXh=require("crypto"),RWc=ce(qXh(),1);var kiu=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var F2a=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var enu=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var tnu=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function nnu(e="",t,r){let i=new zWc(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 TXh(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function UVD(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 zWc=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=UVD(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??zXh.default.tmpdir(),r=(0,NXh.randomUUID)(),i=TXh(this.fileOptions.prefix),n=TXh(this.fileOptions.postfix),a=`${i}${r}${n}`,o=rnu.default.resolve(t,a),c=rnu.default.resolve(t)+rnu.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,Xca.writeFileSync)(this.tempFile,this.text,d)}catch(t){throw new kiu(t)}}readTemporaryFile(){try{let t=(0,Xca.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,RXh.detect)(t)??"utf8";RWc.default.encodingExists(r)||(r="utf8"),this.text=RWc.default.decode(t,r)}}catch(t){throw new enu(t)}}removeTemporaryFile(){try{(0,Xca.unlinkSync)(this.tempFile)}catch(t){throw new tnu(t)}}launchEditor(){try{let t=(0,inu.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new F2a(t)}}launchEditorAsync(t){try{(0,inu.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new F2a(r)}}};var FXh=ce(Fme(),1);var Q2a=class extends mN{_run(t){this.done=t,this.editorResult=new FXh.Subject;let r=E3(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"?anu.default.dim("Received"):anu.default.dim("Press <enter> to launch your preferred editor."),t&&(r=anu.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),nnu(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 WXh=require("stream");var LXh=ce(require("readline"),1),VXh=ce(UXh(),1),gAn=class{constructor(t){this.rl||=LXh.default.createInterface(VVD(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 VVD(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 VXh.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var U2a=class extends gAn{constructor(t={}){super(t),this.log=new WXh.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return P2a(this.rl,this.bottomBar.split(`
|
|
1356
1356
|
`).length),this}updateBottomBar(t){return P2a(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+`
|
|
1357
1357
|
`}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&&Siu(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var oA=ce(Fme(),1),GXh=ce(xZa(),1);var onu=ce(Fme(),1),xXh=ce(xZa(),1),unu=function(e,t,r){return typeof e[t]!="function"?(0,onu.of)(e):(0,onu.from)((0,xXh.default)(e[t])(r).then(i=>(e[t]=i,e)))};var HXh={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}},Zca=class extends gAn{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,oA.from)(t):(0,oA.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,oA.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,oA.from)([t]),this.process=i.pipe((0,oA.concatMap)(this.processQuestion.bind(this)),(0,oA.publish)()),this.process.connect(),this.process.pipe((0,oA.reduce)((n,a)=>(HXh.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,oA.defer)(()=>(0,oA.of)(t).pipe((0,oA.concatMap)(this.setDefaultType.bind(this)),(0,oA.concatMap)(this.filterIfRunnable.bind(this)),(0,oA.concatMap)(()=>unu(t,"message",this.answers)),(0,oA.concatMap)(()=>unu(t,"default",this.answers)),(0,oA.concatMap)(()=>unu(t,"choices",this.answers)),(0,oA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,oA.defer)(()=>(0,oA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,oA.defer)(()=>(0,oA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&HXh.get(this.answers,t.name)!==void 0)return oA.EMPTY;if(t.when===!1)return oA.EMPTY;if(typeof t.when!="function")return(0,oA.of)(t);let{answers:r}=this;return(0,oA.defer)(()=>(0,oA.from)((0,GXh.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,oA.filter)(i=>i!=null)))}};function KXh(e){let t=function(r,i){let n;try{n=new Zca(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",w2a),this.registerPrompt("input",hAn),this.registerPrompt("number",E2a),this.registerPrompt("confirm",S2a),this.registerPrompt("rawlist",M2a),this.registerPrompt("expand",D2a),this.registerPrompt("checkbox",I2a),this.registerPrompt("password",B2a),this.registerPrompt("editor",Q2a)},t.restoreDefaultPrompts(),t}var FWc=KXh();function xVD(e,t){FWc.registerPrompt(e,t)}function HVD(){FWc.restoreDefaultPrompts()}var GVD={prompt:FWc,ui:{BottomBar:U2a,Prompt:Zca},createPromptModule:KXh,registerPrompt:xVD,restoreDefaultPrompts:HVD,Separator:SZ},w5t=GVD;var kca=require("path");function JXh(){let e=KVD();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function KVD(e=process.argv[1]?(0,kca.dirname)(process.argv[1]):process.cwd(),t=kca.sep==="\\"){let r=t?$Xh(e):e;return i=>{if(!i)return;let n=t?$Xh(i):i,{dir:a,base:o,ext:c}=kca.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 $Xh(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var QWc=e=>{if("flags"in e){let t=YXh(e.flags),r=XXh(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,ZXh(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,$VD(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function $VD(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 YXh=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,L2a(r)]).filter(([,t])=>t!==void 0)),XXh=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?ZXh(i):void 0]}))};var L2a=e=>e===void 0?void 0:e.variant??e.enabled,ZXh=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var snu="0123456789abcdef",cnu=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+=snu.charAt(this.bytes[r]>>>4),t+=snu.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+=snu.charAt(this.bytes[r]>>>4),t+=snu.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}},UWc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??JVD()}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 cnu.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,cnu.ofInner(t)}},JVD=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),kXh,R2t=()=>YVD().toString(),YVD=()=>(kXh||(kXh=new UWc)).generate();var XVD=["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"],eZh=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return XVD.concat(t).some(i=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};var DZ=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",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 kVD=Array.isArray,tZh=Object.prototype,Lm6=tZh.hasOwnProperty,LWc=tZh.toString,VWc=kVD||function(e){return LWc.call(e)==="[object Array]"};var rZh=e=>e===Object(e)&&!VWc(e);var ela=e=>e===void 0,V2a=e=>LWc.call(e)=="[object String]",iZh=e=>V2a(e)&&e.trim().length===0;var nZh=e=>LWc.call(e)=="[object Number]"&&e===e;var WWc=e=>e instanceof Error;function W2a(e){return e===null||typeof e!="object"}function OAn(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function aZh(e){return OAn(e,"ErrorEvent")}function lnu(e){return!ela(Event)&&e3D(e,Event)}function oZh(e){return OAn(e,"Object")}function e3D(e,t){try{return e instanceof t}catch{return!1}}function x2a(e,t,r,i,n){return t>r&&(i.warn("min cannot be greater than max."),t=r),nZh(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),x2a(n||r,t,r,i))}var t3D=864e5,fnu=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=x2a(t.bucketSize,0,100,t._logger),this._refillRate=x2a(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=x2a(t.refillInterval,0,t3D,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 dnu=class{add(t){let r=R2t();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 r3D(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var uZh=(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=>uZh(`${e} ${a}`,t,r)}},i3D=e=>e();function sZh(e,t=i3D){return uZh(e,t,r3D())}var rla="Mobile",hnu="iOS",tla="Android",cZh="Tablet",km6=tla+" "+cZh;var n3D="Apple",eA6=n3D+" Watch",lZh="Safari",_nu="BlackBerry",fZh="Samsung",a3D=fZh+"Browser",o3D=fZh+" Internet",ynu="Chrome",u3D=ynu+" OS",s3D=ynu+" "+hnu,dZh="Internet Explorer",c3D=dZh+" "+rla,HWc="Opera",tA6=HWc+" Mini",pZh="Edge",l3D="Microsoft "+pZh,GWc="Firefox",f3D=GWc+" "+hnu,KWc="Nintendo",$Wc="PlayStation",pnu="Xbox",d3D=tla+" "+rla,p3D=rla+" "+lZh,H2a="Windows",h3D=H2a+" Phone";var hZh="Generic",rA6=hZh+" "+rla.toLowerCase(),iA6=hZh+" "+cZh.toLowerCase(),_3D="Konqueror",S7="(\\d+(\\.\\d+)?)",xWc=new RegExp("Version/"+S7),nA6=new RegExp(pnu,"i"),aA6=new RegExp($Wc+" \\w+","i"),oA6=new RegExp(KWc+" \\w+","i"),y3D=new RegExp(_nu+"|PlayBook|BB10","i"),b3D={"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 uA6={[c3D]:[new RegExp("rv:"+S7)],[l3D]:[new RegExp(pZh+"?\\/"+S7)],[ynu]:[new RegExp("("+ynu+"|CrMo)\\/"+S7)],[s3D]:[new RegExp("CriOS\\/"+S7)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+S7)],[lZh]:[xWc],[p3D]:[xWc],[HWc]:[new RegExp("("+HWc+"|OPR)\\/"+S7)],[GWc]:[new RegExp(GWc+"\\/"+S7)],[f3D]:[new RegExp("FxiOS\\/"+S7)],[_3D]:[new RegExp("Konqueror[:/]?"+S7,"i")],[_nu]:[new RegExp(_nu+" "+S7),xWc],[d3D]:[new RegExp("android\\s"+S7,"i")],[o3D]:[new RegExp(a3D+"\\/"+S7)],[dZh]:[new RegExp("(rv:|MSIE )"+S7)],Mozilla:[new RegExp("rv:"+S7)]};var sA6=[[new RegExp(pnu+"; "+pnu+" (.*?)[);]","i"),e=>[pnu,e&&e[1]||""]],[new RegExp(KWc,"i"),[KWc,""]],[new RegExp($Wc,"i"),[$Wc,""]],[y3D,[_nu,""]],[new RegExp(H2a,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[h3D,""];if(new RegExp(rla).test(t)&&!/IEMobile\b/.test(t))return[H2a+" "+rla,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=b3D[i]||"";return/arm/i.test(t)&&(n="RT"),[H2a,n]}return[H2a,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[hnu,t.join(".")]}return[hnu,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=ela(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+tla+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+tla+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[tla,t.join(".")]}return[tla,""]}],[/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/,[u3D,""]],[/Linux|debian/i,["Linux",""]]];var _Zh="utf8";function yZh(e,t){if(!e||typeof e!="string"||v3D(e))throw new Error(t)}function v3D(e){return e.trim().length===0}function bZh(e){return e?.replace(/\/+$/,"")}async function vZh(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 bnu(){return new Date().toISOString()}function mAn(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var gZh=e=>e instanceof Error;function JWc(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var vnu=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 OZh(){return"CompressionStream"in globalThis}async function YWc(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 AAn=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()}},ila=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function mZh(e){if(e instanceof AAn){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 XWc(e){return typeof e=="object"&&(e instanceof AAn||e instanceof ila)}function AZh(e){return typeof e=="object"&&e instanceof AAn&&e.status===413}var G2a=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new dnu,this._events=new vnu,this._isInitialized=!1,yZh(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=bZh(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:XWc},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=r.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=sZh("[PostHog]",this.logMsgIfDebug.bind(this)),this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!OZh()||(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(DZ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(DZ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(DZ.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.evaluationContexts&&this.evaluationContexts.length>0&&(s.evaluation_contexts=this.evaluationContexts);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(f=>f.json()).then(f=>({success:!0,response:QWc(f)})).catch(f=>(this._events.emit("error",f),{success:!1,error:this.categorizeRequestError(f)}))}categorizeRequestError(t){if(t instanceof AAn)return{type:"api_error",statusCode:t.status};if(t instanceof ila){let r=t.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}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=L2a(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.success)return;let s=d.response;return s.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"),s.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:s?.requestId,quotaLimited:s.quotaLimited}):s}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(DZ.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(DZ.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(DZ.Props,this.props)})}processBeforeEnqueue(t){return t}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);if(n=this.processBeforeEnqueue(n),n===null)return;let a=this.getPersistedProperty(DZ.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),a.push({message:n}),this.setPersistedProperty(DZ.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=mAn(()=>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=this.prepareMessage(t,r,i);if(n=this.processBeforeEnqueue(n),n===null)return;let a={api_key:this.apiKey,batch:[n],sent_at:bnu()};this.historicalMigration&&(a.historical_migration=!0);let o=JSON.stringify(a),c=`${this.host}/batch/`,d=this.disableCompression?null:await YWc(o,this.isDebug),s={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...d!==null&&{"Content-Encoding":"gzip"}},body:d||o};try{await this.fetchWithRetry(c,s)}catch(u){this._events.emit("error",u)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:bnu(),uuid:i?.uuid?i.uuid:R2t()};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 mZh(t)})}async flush(){let t=JWc([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),JWc([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(DZ.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(h=>h.message),o=()=>{let _=(this.getPersistedProperty(DZ.Queue)||[]).slice(n.length);this.setPersistedProperty(DZ.Queue,_),t=_},c={api_key:this.apiKey,batch:a,sent_at:bnu()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=`${this.host}/batch/`,u=this.disableCompression?null:await YWc(d,this.isDebug),f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||d},p={retryCheck:h=>AZh(h)?!1:XWc(h)};try{await this.fetchWithRetry(s,f,p)}catch(h){if(AZh(h)&&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 h instanceof ila||o(),this._events.emit("error",h),h}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,_Zh)}catch{a instanceof Blob?o=a.size:o=new TextEncoder().encode(a).length}return await vZh(async()=>{let c=null;try{c=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(s){throw new ila(s)}if(!(r.mode==="no-cors")&&(c.status<200||c.status>=400))throw new AAn(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(DZ.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!XWc(n))throw n;await mZh(n)}};return Promise.race([new Promise((n,a)=>{mAn(()=>{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 IZ={};$t(IZ,{DOMExceptionCoercer:()=>t8c,ErrorCoercer:()=>r8c,ErrorEventCoercer:()=>i8c,ErrorPropertiesBuilder:()=>ZWc,EventCoercer:()=>o8c,ObjectCoercer:()=>a8c,PrimitiveCoercer:()=>u8c,PromiseRejectionEventCoercer:()=>s8c,ReduceableCache:()=>c8c,StringCoercer:()=>n8c,chromeStackLineParser:()=>kWc,createDefaultStackParser:()=>q3D,createStackParser:()=>qZh,geckoStackLineParser:()=>e8c,nodeStackLineParser:()=>DZh,opera10StackLineParser:()=>EZh,opera11StackLineParser:()=>SZh,reverseAndStripFrames:()=>CZh,winjsStackLineParser:()=>wZh});var gnu,PZh,Onu;function jZh(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return Onu&&r.length===PZh||(PZh=r.length,Onu=r.reduce((i,n)=>{gnu||(gnu={});let a=gnu[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,gnu[n]=[s,u];break}}}return i},{})),Onu}var O3D=4,ZWc=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&&VWc(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:jZh(this.stackParser)}}buildCoercingContext(t,r,i=0){let n=(o,c)=>{if(c<=O3D){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 M3="?";function z2t(e,t,r,i,n){let a={platform:e,filename:t,function:r==="<anonymous>"?M3:r,in_app:!0};return ela(i)||(a.lineno=i),ela(n)||(a.colno=n),a}var mnu=(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]:M3,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var m3D=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,A3D=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,P3D=/\((\S*)(?::(\d+))(?::(\d+))\)/,kWc=(e,t)=>{let r=m3D.exec(e);if(r){let[,n,a,o]=r;return z2t(t,n,M3,+a,+o)}let i=A3D.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let c=P3D.exec(i[2]);c&&(i[2]=c[1],i[3]=c[2],i[4]=c[3])}let[a,o]=mnu(i[1]||M3,i[2]);return z2t(t,o,a,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var j3D=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,w3D=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,e8c=(e,t)=>{let r=j3D.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=w3D.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]||M3;return[a,n]=mnu(a,n),z2t(t,n,a,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var E3D=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,wZh=(e,t)=>{let r=E3D.exec(e);return r?z2t(t,r[2],r[1]||M3,+r[3],r[4]?+r[4]:void 0):void 0};var S3D=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,EZh=(e,t)=>{let r=S3D.exec(e);return r?z2t(t,r[2],r[3]||M3,+r[1]):void 0},M3D=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,SZh=(e,t)=>{let r=M3D.exec(e);return r?z2t(t,r[5],r[3]||r[4]||M3,+r[1],+r[2]):void 0};var D3D=/^\s*[-]{4,}$/,I3D=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,DZh=(e,t)=>{let r=e.match(I3D);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 f=i.indexOf(".Module");f>0&&(a=a.slice(f+1),i=i.slice(0,f))}o=void 0}n&&(o=i,c=n),n==="<anonymous>"&&(c=void 0,a=void 0),a===void 0&&(c=c||M3,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:MZh(r[3]),colno:MZh(r[4]),in_app:B3D(d||"",s),platform:t}}if(e.match(D3D))return{filename:e,platform:t}};function B3D(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 MZh(e){return parseInt(e||"",10)||void 0}var IZh=/\(error: (.*)\)/,BZh=50;function CZh(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,BZh).map(r=>({...r,filename:r.filename||C3D(t).filename,function:r.function||M3}))}function C3D(e){return e[e.length-1]||{}}function q3D(){return qZh("web:javascript",kWc,e8c)}function qZh(e,...t){return(r,i=0)=>{let n=[],a=r.split(`
|
|
1358
|
-
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=IZh.test(c)?c.replace(IZh,"$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>=BZh)break}}return CZh(n)}}var t8c=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=V2a(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 OAn(t,"DOMException")}isDOMError(t){return OAn(t,"DOMError")}};var r8c=class{match(t){return WWc(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 i8c=class{constructor(){}match(t){return aZh(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 T3D=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,n8c=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(T3D);return n&&(r=n[1],i=n[2]),[r,i]}};var TZh=["fatal","error","warning","log","info","debug"];function Anu(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 a8c=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 lnu(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=Anu(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return V2a(t)&&!iZh(t)&&TZh.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(gZh(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var o8c=class{match(t){return lnu(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${Anu(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var u8c=class{match(t){return W2a(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var s8c=class{match(t){return OAn(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return W2a(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(W2a(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 c8c=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 NZh=require("fs"),FZh=require("readline"),Pnu=new IZ.ReduceableCache(25),QZh=new IZ.ReduceableCache(20),l8c=7,R3D=1e3,z3D=1e4;async function UZh(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"||U3D(o)||L3D(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(QZh.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=W3D(a);if(o.every(d=>V3D(n,d)))continue;let c=x3D(Pnu,n,{});i.push(N3D(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&F3D(e,Pnu),Pnu.reduce(),e}function N3D(e,t,r){return new Promise(i=>{let n=(0,NZh.createReadStream)(e),a=(0,FZh.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],f=s[1];function p(){QZh.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",h=>{if(c++,!(c<u)&&(r[c]=H3D(h,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let _=t[d];if(_===void 0){a.close(),a.removeAllListeners();return}u=_[0],f=_[1]}})})}function F3D(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;Q3D(r.lineno,r,i)}}function Q3D(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=LZh(e);n<e;n++){let a=r[n];if(a===void 0)return void RZh(t);t.pre_context.push(a)}if(r[e]===void 0)return void RZh(t);t.context_line=r[e];let i=VZh(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 RZh(e){delete e.pre_context,delete e.context_line,delete e.post_context}function U3D(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function L3D(e){return e.lineno!==void 0&&e.lineno>z3D||e.colno!==void 0&&e.colno>R3D}function V3D(e,t){let r=Pnu.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 W3D(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=zZh(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+l8c:(n.push(i),i=zZh(a)),t++}return n}function zZh(e){return[LZh(e),VZh(e)]}function LZh(e){return Math.max(1,e-l8c)}function VZh(e){return e+l8c}function x3D(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function H3D(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 G3D(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 WZh(e,t){globalThis.process?.on("uncaughtException",G3D(e,t))}function xZh(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var K3D=2e3,E5t=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new fnu({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return rZh(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}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||R2t(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(WZh(this.onException.bind(this),this.onFatalError.bind(this)),xZh(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){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(K3D),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var HZh="5.24.7";var K2a={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function GZh(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 $3D=6e4,J3D=1152921504606847e3,Y3D=["is_not"],nla=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},W0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},N2t=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},jnu=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.strictLocalEvaluation=c.strictLocalEvaluation??!1,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 N2t||d instanceof W0?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(f=>this.featureFlagsByKey[f]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async f=>{try{let{value:p,payload:h}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,h&&(c[f.key]=h)}catch(p){p instanceof N2t||p instanceof W0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${f.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.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 W0("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 W0("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 W0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new W0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new W0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new W0(`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 f=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=f}catch(f){throw new W0(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new W0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new W0(`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,f=a.multivariate?.variants||[];d=u&&f.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof N2t)throw u;if(u instanceof W0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new W0("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"?XZh(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):YZh(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await KZh(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await KZh(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}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(i=>i.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(i=>i.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}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),this.warnAboutExperienceContinuityFlags(r.flags),!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!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(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($3D,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}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.clearBackoff();return;case 401:throw this.beginBackoff(),new nla(`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.beginBackoff(),new nla(`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.beginBackoff(),new nla(`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.clearBackoff(),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),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(t){t instanceof nla&&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=mAn(()=>{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 KZh(e,t,r=""){let i=await GZh(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/J3D}function YZh(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 W0("Operator is_not_set is not supported")}else throw new W0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!Y3D.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(f=>String(f).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,f){if(f==="gt")return s>u;if(f==="gte")return s>=u;if(f==="lt")return s<u;if(f==="lte")return s<=u;throw new Error(`Invalid operator: ${f}`)}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 $Zh(String(n))&&String(o).match(String(n))!==null;case"not_regex":return $Zh(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 W0("Date operations cannot be performed on boolean values");let s=Z3D(String(n));if(s==null&&(s=JZh(n)),s==null)throw new W0(`Invalid date: ${n}`);let u=JZh(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new W0(`Unknown operator: ${a}`)}}function X3D(e,t){if(!(e in t))throw new N2t(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function XZh(e,t,r,i=!1){let n=String(e.value);X3D(n,r);let a=r[n];return ZZh(a,t,r,i)}function ZZh(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=ZZh(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof N2t)throw d;if(d instanceof W0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new W0("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=XZh(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=YZh(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 N2t)throw d;if(d instanceof W0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new W0("can't match cohort without a given cohort property value");return n==="AND"}function $Zh(e){try{return new RegExp(e),!0}catch{return!1}}function JZh(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 W0(`${e} is in an invalid date format`)}throw new W0(`The date provided ${e} must be a string, number, or date object`)}function Z3D(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 wnu=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var k3D=100,kZh=3e4,eWD=5e4,Enu=class extends G2a{constructor(t,r={}){if(super(t,r),this._memoryStorage=new wnu,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,k3D):kZh,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 jnu({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,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new E5t(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||eWD}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 HZh}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=kZh){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 _getFeatureFlagResult(t,r,i={},n){let a=i.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let A=this._flagOverrides[t];if(A===void 0)return;let j=this._payloadOverrides?.[t];return{key:t,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:j}}let{groups:o,disableGeoip:c}=i,{onlyEvaluateLocally:d,personProperties:s,groupProperties:u}=i,f=this.addLocalPersonAndGroupProperties(r,o,s,u);s=f.allPersonProperties,u=f.allGroupProperties,d==null&&(d=this.options.strictLocalEvaluation??!1);let p,h=!1,_,y,b,v,O,m;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let A=this.featureFlagsPoller?.featureFlagsByKey[t];if(A)try{let j=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(A,r,o,s,u,n);if(j){h=!0;let S=j.value;v=A.id,m="Evaluated locally",p={key:t,enabled:S!==!1,variant:typeof S=="string"?S:void 0,payload:j.payload??void 0}}}catch(j){if(j instanceof N2t||j instanceof W0)this._logger?.info(`${j.name} when computing flag locally: ${t}: ${j.message}`);else throw j}}if(!h&&!d){let A=await super.getFeatureFlagDetailsStateless(r,o,s,u,c,[t]);if(A===void 0)b=K2a.UNKNOWN_ERROR;else{_=A.requestId,y=A.evaluatedAt;let j=[];A.errorsWhileComputingFlags&&j.push(K2a.ERRORS_WHILE_COMPUTING),A.quotaLimited?.includes("feature_flags")&&j.push(K2a.QUOTA_LIMITED);let S=A.flags[t];if(S===void 0)j.push(K2a.FLAG_MISSING);else{v=S.metadata?.id,O=S.metadata?.version,m=S.reason?.description??S.reason?.code;let w;if(S.metadata?.payload!==void 0)try{w=JSON.parse(S.metadata.payload)}catch{w=S.metadata.payload}p={key:t,enabled:S.enabled,variant:S.variant,payload:w}}j.length>0&&(b=j.join(","))}}if(a){let A=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,j=`${t}_${A}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(j)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(j):this.distinctIdHasSentFlagCalls[r]=[j];let S={$feature_flag:t,$feature_flag_response:A,$feature_flag_id:v,$feature_flag_version:O,$feature_flag_reason:m,locally_evaluated:h,[`$feature/${t}`]:A,$feature_flag_request_id:_,$feature_flag_evaluated_at:y};b&&(S.$feature_flag_error=b),this.capture({distinctId:r,event:"$feature_flag_called",properties:S,groups:o,disableGeoip:c})}}return p!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(p={...p,payload:this._payloadOverrides[t]}),p}async getFeatureFlag(t,r,i){let n=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n!==void 0)return n.enabled===!1?!1:n.variant??!0}async getFeatureFlagPayload(t,r,i,n){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let a=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:!1},i);if(a!==void 0)return a.payload??null}async getFeatureFlagResult(t,r,i){return this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}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=this.options.strictLocalEvaluation??!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},h=!0;if(u&&(f=u.response,p=u.payloads,h=u.fallbackToFlags),h&&!o){let _=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,..._.flags||{}},p={...p,..._.payloads||{}}}return this._flagOverrides!==void 0&&(f={...f,...this._flagOverrides}),this._payloadOverrides!==void 0&&(p={...p,...this._payloadOverrides}),{featureFlags:f,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)}overrideFeatureFlags(t){let r=i=>Object.fromEntries(i.map(n=>[n,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let i=r.flags;if(i===!1||Array.isArray(i)||typeof i=="object"&&i!==null)return!0}if("payloads"in r){let i=r.payloads;if(i===!1||typeof i=="object"&&i!==null)return!0}return!1}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=mAn(()=>{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(oZh(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??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);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,f]of Object.entries(r||{}))s[u]=String(f);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,n){if(!E5t.isPreviouslyCapturedError(t)){let a=new Error("PostHog syntheticException");this.addPendingPromise(E5t.buildEventMessage(t,{syntheticException:a},r,i).then(o=>this.capture({...o,uuid:n})))}}async captureExceptionImmediate(t,r,i){if(!E5t.isPreviouslyCapturedError(t)){let n=new Error("PostHog syntheticException");this.addPendingPromise(E5t.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(),f=r||u?.distinctId,p={...u?.properties||{},...n||{}};f||(f=R2t(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let h=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!h)return Promise.reject(null);let _=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(h.distinctId,a,d,y)}return h.event,{}}).then(y=>{let b={};if(y)for(let[O,m]of Object.entries(y))b[`$feature/${O}`]=m;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,...h.properties||{},$groups:h.groups||a}));return h.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof _.$raw_user_agent=="string"&&eZh(_.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(h.event="$bot_pageview",_.$browser_type="bot"),{distinctId:h.distinctId,event:h.event,properties:_,options:{timestamp:h.timestamp,disableGeoip:h.disableGeoip,uuid:h.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 e2h=require("async_hooks"),Snu=class{constructor(){this.storage=new e2h.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 t2h="posthog-node";function tWD(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[f8c.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 f=o.exception?.values||[],p=f.map(_=>({..._,stacktrace:_.stacktrace?{..._.stacktrace,type:"raw",frames:(_.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),h={$exception_message:f[0]?.value||o.message,$exception_type:f[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:f[0]?.value||o.message,$sentry_exception_type:f[0]?.type,$sentry_tags:o.tags};return t&&r&&(h.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:h}),o}}var f8c=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=t2h,this.name=t2h,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(tWD(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};E5t.errorPropertiesBuilder=new IZ.ErrorPropertiesBuilder([new IZ.EventCoercer,new IZ.ErrorCoercer,new IZ.ObjectCoercer,new IZ.StringCoercer,new IZ.PrimitiveCoercer],IZ.createStackParser("node:javascript",IZ.nodeStackLineParser),[JXh(),UZh]);var ala=class extends Enu{getLibraryId(){return"posthog-node"}initializeContext(){return new Snu}};var Mnu=class{posthog;constructor({posthogApiKey:t}){this.posthog=new ala(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.64.3",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var $2a=class{async sendEvent(){}async identify(){}async flush(){}};var ola=require("fs/promises"),a2h=require("os"),o2h=require("path");var r2h=ce(require("crypto")),Inu=new Uint8Array(256),Dnu=Inu.length;function d8c(){return Dnu>Inu.length-16&&(r2h.default.randomFillSync(Inu),Dnu=0),Inu.slice(Dnu,Dnu+=16)}var D3=[];for(let e=0;e<256;++e)D3.push((e+256).toString(16).slice(1));function i2h(e,t=0){return D3[e[t+0]]+D3[e[t+1]]+D3[e[t+2]]+D3[e[t+3]]+"-"+D3[e[t+4]]+D3[e[t+5]]+"-"+D3[e[t+6]]+D3[e[t+7]]+"-"+D3[e[t+8]]+D3[e[t+9]]+"-"+D3[e[t+10]]+D3[e[t+11]]+D3[e[t+12]]+D3[e[t+13]]+D3[e[t+14]]+D3[e[t+15]]}var n2h=ce(require("crypto")),p8c={randomUUID:n2h.default.randomUUID};function rWD(e,t,r){if(p8c.randomUUID&&!t&&!e)return p8c.randomUUID();e=e||{};let i=e.random||(e.rng||d8c)();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 i2h(i)}var Ume=rWD;var iWD="id",nWD=".fern",J2a=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new ala(r),this.userId=t==null?void 0:YFc(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.64.3",...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 Fq({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=ut(vr.of((0,a2h.homedir)()),me.of(nWD),me.of(iWD));await ii(t)||(await(0,ola.mkdir)((0,o2h.dirname)(t),{recursive:!0}),await(0,ola.writeFile)(t,Ume())),this.persistedDistinctId=(await(0,ola.readFile)(t)).toString()}return this.persistedDistinctId}};var h8c;async function ula(){return h8c==null&&(h8c=await aWD()),h8c}async function aWD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new $2a;let r=await KZo();return r!=null?new J2a({token:r,posthogApiKey:e}):await y2t()!=null?new Mnu({posthogApiKey:e}):new J2a({token:void 0,posthogApiKey:e})}catch{return new $2a}}var u2h=(e=0)=>t=>`\x1B[${t+e}m`,s2h=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,c2h=(e=0)=>(t,r,i)=>`\x1B[${38+e};2;${t};${r};${i}m`,KD={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},uw6=Object.keys(KD.modifier),oWD=Object.keys(KD.color),uWD=Object.keys(KD.bgColor),sw6=[...oWD,...uWD];function sWD(){let e=new Map;for(let[t,r]of Object.entries(KD)){for(let[i,n]of Object.entries(r))KD[i]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},r[i]=KD[i],e.set(n[0],n[1]);Object.defineProperty(KD,t,{value:r,enumerable:!1})}return Object.defineProperty(KD,"codes",{value:e,enumerable:!1}),KD.color.close="\x1B[39m",KD.bgColor.close="\x1B[49m",KD.color.ansi=u2h(),KD.color.ansi256=s2h(),KD.color.ansi16m=c2h(),KD.bgColor.ansi=u2h(10),KD.bgColor.ansi256=s2h(10),KD.bgColor.ansi16m=c2h(10),Object.defineProperties(KD,{rgbToAnsi256:{value(t,r,i){return t===r&&r===i?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(i/255*5)},enumerable:!1},hexToRgb:{value(t){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!r)return[0,0,0];let[i]=r;i.length===3&&(i=[...i].map(a=>a+a).join(""));let n=Number.parseInt(i,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:t=>KD.rgbToAnsi256(...KD.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,i,n;if(t>=232)r=((t-232)*10+8)/255,i=r,n=r;else{t-=16;let c=t%36;r=Math.floor(t/36)/5,i=Math.floor(c/6)/5,n=c%6/5}let a=Math.max(r,i,n)*2;if(a===0)return 30;let o=30+(Math.round(n)<<2|Math.round(i)<<1|Math.round(r));return a===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(t,r,i)=>KD.ansi256ToAnsi(KD.rgbToAnsi256(t,r,i)),enumerable:!1},hexToAnsi:{value:t=>KD.ansi256ToAnsi(KD.hexToAnsi256(t)),enumerable:!1}}),KD}var cWD=sWD(),S5t=cWD;var Cnu=ce(require("process"),1),f2h=ce(require("os"),1),_8c=ce(require("tty"),1);function mDe(e,t=globalThis.Deno?globalThis.Deno.args:Cnu.default.argv){let r=e.startsWith("-")?"":e.length===1?"-":"--",i=t.indexOf(r+e),n=t.indexOf("--");return i!==-1&&(n===-1||i<n)}var{env:IC}=Cnu.default,Bnu;mDe("no-color")||mDe("no-colors")||mDe("color=false")||mDe("color=never")?Bnu=0:(mDe("color")||mDe("colors")||mDe("color=true")||mDe("color=always"))&&(Bnu=1);function lWD(){if("FORCE_COLOR"in IC)return IC.FORCE_COLOR==="true"?1:IC.FORCE_COLOR==="false"?0:IC.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(IC.FORCE_COLOR,10),3)}function fWD(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function dWD(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let i=lWD();i!==void 0&&(Bnu=i);let n=r?Bnu:i;if(n===0)return 0;if(r){if(mDe("color=16m")||mDe("color=full")||mDe("color=truecolor"))return 3;if(mDe("color=256"))return 2}if("TF_BUILD"in IC&&"AGENT_NAME"in IC)return 1;if(e&&!t&&n===void 0)return 0;let a=n||0;if(IC.TERM==="dumb")return a;if(Cnu.default.platform==="win32"){let o=f2h.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in IC)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in IC)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in IC)||IC.CI_NAME==="codeship"?1:a;if("TEAMCITY_VERSION"in IC)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(IC.TEAMCITY_VERSION)?1:0;if(IC.COLORTERM==="truecolor"||IC.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in IC){let o=Number.parseInt((IC.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(IC.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(IC.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(IC.TERM)||"COLORTERM"in IC?1:a}function l2h(e,t={}){let r=dWD(e,{streamIsTTY:e&&e.isTTY,...t});return fWD(r)}var pWD={stdout:l2h({isTTY:_8c.default.isatty(1)}),stderr:l2h({isTTY:_8c.default.isatty(2)})},d2h=pWD;function p2h(e,t,r){let i=e.indexOf(t);if(i===-1)return e;let n=t.length,a=0,o="";do o+=e.slice(a,i)+t+r,a=i+n,i=e.indexOf(t,a);while(i!==-1);return o+=e.slice(a),o}function h2h(e,t,r,i){let n=0,a="";do{let o=e[i-1]==="\r";a+=e.slice(n,o?i-1:i)+t+(o?`\r
|
|
1358
|
+
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=IZh.test(c)?c.replace(IZh,"$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>=BZh)break}}return CZh(n)}}var t8c=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=V2a(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 OAn(t,"DOMException")}isDOMError(t){return OAn(t,"DOMError")}};var r8c=class{match(t){return WWc(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 i8c=class{constructor(){}match(t){return aZh(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 T3D=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,n8c=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(T3D);return n&&(r=n[1],i=n[2]),[r,i]}};var TZh=["fatal","error","warning","log","info","debug"];function Anu(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 a8c=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 lnu(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=Anu(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return V2a(t)&&!iZh(t)&&TZh.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(gZh(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var o8c=class{match(t){return lnu(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${Anu(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var u8c=class{match(t){return W2a(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var s8c=class{match(t){return OAn(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return W2a(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(W2a(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 c8c=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 NZh=require("fs"),FZh=require("readline"),Pnu=new IZ.ReduceableCache(25),QZh=new IZ.ReduceableCache(20),l8c=7,R3D=1e3,z3D=1e4;async function UZh(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"||U3D(o)||L3D(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(QZh.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=W3D(a);if(o.every(d=>V3D(n,d)))continue;let c=x3D(Pnu,n,{});i.push(N3D(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&F3D(e,Pnu),Pnu.reduce(),e}function N3D(e,t,r){return new Promise(i=>{let n=(0,NZh.createReadStream)(e),a=(0,FZh.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],f=s[1];function p(){QZh.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",h=>{if(c++,!(c<u)&&(r[c]=H3D(h,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let _=t[d];if(_===void 0){a.close(),a.removeAllListeners();return}u=_[0],f=_[1]}})})}function F3D(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;Q3D(r.lineno,r,i)}}function Q3D(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=LZh(e);n<e;n++){let a=r[n];if(a===void 0)return void RZh(t);t.pre_context.push(a)}if(r[e]===void 0)return void RZh(t);t.context_line=r[e];let i=VZh(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 RZh(e){delete e.pre_context,delete e.context_line,delete e.post_context}function U3D(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function L3D(e){return e.lineno!==void 0&&e.lineno>z3D||e.colno!==void 0&&e.colno>R3D}function V3D(e,t){let r=Pnu.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 W3D(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=zZh(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+l8c:(n.push(i),i=zZh(a)),t++}return n}function zZh(e){return[LZh(e),VZh(e)]}function LZh(e){return Math.max(1,e-l8c)}function VZh(e){return e+l8c}function x3D(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function H3D(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 G3D(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 WZh(e,t){globalThis.process?.on("uncaughtException",G3D(e,t))}function xZh(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var K3D=2e3,E5t=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new fnu({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return rZh(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}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||R2t(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(WZh(this.onException.bind(this),this.onFatalError.bind(this)),xZh(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){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(K3D),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var HZh="5.24.7";var K2a={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function GZh(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 $3D=6e4,J3D=1152921504606847e3,Y3D=["is_not"],nla=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},W0=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},N2t=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},jnu=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.strictLocalEvaluation=c.strictLocalEvaluation??!1,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 N2t||d instanceof W0?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(f=>this.featureFlagsByKey[f]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async f=>{try{let{value:p,payload:h}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,h&&(c[f.key]=h)}catch(p){p instanceof N2t||p instanceof W0?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${f.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.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 W0("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 W0("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 W0("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new W0(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new W0(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new W0(`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 f=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=f}catch(f){throw new W0(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new W0(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new W0(`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,f=a.multivariate?.variants||[];d=u&&f.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof N2t)throw u;if(u instanceof W0)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new W0("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"?XZh(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):YZh(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await KZh(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await KZh(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}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(i=>i.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(i=>i.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}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),this.warnAboutExperienceContinuityFlags(r.flags),!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!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(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($3D,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}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.clearBackoff();return;case 401:throw this.beginBackoff(),new nla(`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.beginBackoff(),new nla(`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.beginBackoff(),new nla(`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.clearBackoff(),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),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(t){t instanceof nla&&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=mAn(()=>{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 KZh(e,t,r=""){let i=await GZh(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/J3D}function YZh(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 W0("Operator is_not_set is not supported")}else throw new W0(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!Y3D.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(f=>String(f).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,f){if(f==="gt")return s>u;if(f==="gte")return s>=u;if(f==="lt")return s<u;if(f==="lte")return s<=u;throw new Error(`Invalid operator: ${f}`)}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 $Zh(String(n))&&String(o).match(String(n))!==null;case"not_regex":return $Zh(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 W0("Date operations cannot be performed on boolean values");let s=Z3D(String(n));if(s==null&&(s=JZh(n)),s==null)throw new W0(`Invalid date: ${n}`);let u=JZh(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new W0(`Unknown operator: ${a}`)}}function X3D(e,t){if(!(e in t))throw new N2t(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function XZh(e,t,r,i=!1){let n=String(e.value);X3D(n,r);let a=r[n];return ZZh(a,t,r,i)}function ZZh(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=ZZh(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof N2t)throw d;if(d instanceof W0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new W0("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=XZh(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=YZh(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 N2t)throw d;if(d instanceof W0)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new W0("can't match cohort without a given cohort property value");return n==="AND"}function $Zh(e){try{return new RegExp(e),!0}catch{return!1}}function JZh(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 W0(`${e} is in an invalid date format`)}throw new W0(`The date provided ${e} must be a string, number, or date object`)}function Z3D(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 wnu=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var k3D=100,kZh=3e4,eWD=5e4,Enu=class extends G2a{constructor(t,r={}){if(super(t,r),this._memoryStorage=new wnu,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,k3D):kZh,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 jnu({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,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new E5t(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||eWD}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 HZh}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=kZh){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 _getFeatureFlagResult(t,r,i={},n){let a=i.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let A=this._flagOverrides[t];if(A===void 0)return;let j=this._payloadOverrides?.[t];return{key:t,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:j}}let{groups:o,disableGeoip:c}=i,{onlyEvaluateLocally:d,personProperties:s,groupProperties:u}=i,f=this.addLocalPersonAndGroupProperties(r,o,s,u);s=f.allPersonProperties,u=f.allGroupProperties,d==null&&(d=this.options.strictLocalEvaluation??!1);let p,h=!1,_,y,b,v,O,m;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let A=this.featureFlagsPoller?.featureFlagsByKey[t];if(A)try{let j=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(A,r,o,s,u,n);if(j){h=!0;let S=j.value;v=A.id,m="Evaluated locally",p={key:t,enabled:S!==!1,variant:typeof S=="string"?S:void 0,payload:j.payload??void 0}}}catch(j){if(j instanceof N2t||j instanceof W0)this._logger?.info(`${j.name} when computing flag locally: ${t}: ${j.message}`);else throw j}}if(!h&&!d){let A=await super.getFeatureFlagDetailsStateless(r,o,s,u,c,[t]);if(A===void 0)b=K2a.UNKNOWN_ERROR;else{_=A.requestId,y=A.evaluatedAt;let j=[];A.errorsWhileComputingFlags&&j.push(K2a.ERRORS_WHILE_COMPUTING),A.quotaLimited?.includes("feature_flags")&&j.push(K2a.QUOTA_LIMITED);let S=A.flags[t];if(S===void 0)j.push(K2a.FLAG_MISSING);else{v=S.metadata?.id,O=S.metadata?.version,m=S.reason?.description??S.reason?.code;let w;if(S.metadata?.payload!==void 0)try{w=JSON.parse(S.metadata.payload)}catch{w=S.metadata.payload}p={key:t,enabled:S.enabled,variant:S.variant,payload:w}}j.length>0&&(b=j.join(","))}}if(a){let A=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,j=`${t}_${A}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(j)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(j):this.distinctIdHasSentFlagCalls[r]=[j];let S={$feature_flag:t,$feature_flag_response:A,$feature_flag_id:v,$feature_flag_version:O,$feature_flag_reason:m,locally_evaluated:h,[`$feature/${t}`]:A,$feature_flag_request_id:_,$feature_flag_evaluated_at:y};b&&(S.$feature_flag_error=b),this.capture({distinctId:r,event:"$feature_flag_called",properties:S,groups:o,disableGeoip:c})}}return p!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(p={...p,payload:this._payloadOverrides[t]}),p}async getFeatureFlag(t,r,i){let n=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n!==void 0)return n.enabled===!1?!1:n.variant??!0}async getFeatureFlagPayload(t,r,i,n){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let a=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:!1},i);if(a!==void 0)return a.payload??null}async getFeatureFlagResult(t,r,i){return this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}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=this.options.strictLocalEvaluation??!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},h=!0;if(u&&(f=u.response,p=u.payloads,h=u.fallbackToFlags),h&&!o){let _=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,..._.flags||{}},p={...p,..._.payloads||{}}}return this._flagOverrides!==void 0&&(f={...f,...this._flagOverrides}),this._payloadOverrides!==void 0&&(p={...p,...this._payloadOverrides}),{featureFlags:f,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)}overrideFeatureFlags(t){let r=i=>Object.fromEntries(i.map(n=>[n,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let i=r.flags;if(i===!1||Array.isArray(i)||typeof i=="object"&&i!==null)return!0}if("payloads"in r){let i=r.payloads;if(i===!1||typeof i=="object"&&i!==null)return!0}return!1}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=mAn(()=>{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(oZh(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??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);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,f]of Object.entries(r||{}))s[u]=String(f);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,n){if(!E5t.isPreviouslyCapturedError(t)){let a=new Error("PostHog syntheticException");this.addPendingPromise(E5t.buildEventMessage(t,{syntheticException:a},r,i).then(o=>this.capture({...o,uuid:n})))}}async captureExceptionImmediate(t,r,i){if(!E5t.isPreviouslyCapturedError(t)){let n=new Error("PostHog syntheticException");this.addPendingPromise(E5t.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(),f=r||u?.distinctId,p={...u?.properties||{},...n||{}};f||(f=R2t(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let h=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!h)return Promise.reject(null);let _=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(h.distinctId,a,d,y)}return h.event,{}}).then(y=>{let b={};if(y)for(let[O,m]of Object.entries(y))b[`$feature/${O}`]=m;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,...h.properties||{},$groups:h.groups||a}));return h.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof _.$raw_user_agent=="string"&&eZh(_.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(h.event="$bot_pageview",_.$browser_type="bot"),{distinctId:h.distinctId,event:h.event,properties:_,options:{timestamp:h.timestamp,disableGeoip:h.disableGeoip,uuid:h.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 e2h=require("async_hooks"),Snu=class{constructor(){this.storage=new e2h.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 t2h="posthog-node";function tWD(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[f8c.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 f=o.exception?.values||[],p=f.map(_=>({..._,stacktrace:_.stacktrace?{..._.stacktrace,type:"raw",frames:(_.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),h={$exception_message:f[0]?.value||o.message,$exception_type:f[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:f[0]?.value||o.message,$sentry_exception_type:f[0]?.type,$sentry_tags:o.tags};return t&&r&&(h.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:h}),o}}var f8c=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=t2h,this.name=t2h,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(tWD(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};E5t.errorPropertiesBuilder=new IZ.ErrorPropertiesBuilder([new IZ.EventCoercer,new IZ.ErrorCoercer,new IZ.ObjectCoercer,new IZ.StringCoercer,new IZ.PrimitiveCoercer],IZ.createStackParser("node:javascript",IZ.nodeStackLineParser),[JXh(),UZh]);var ala=class extends Enu{getLibraryId(){return"posthog-node"}initializeContext(){return new Snu}};var Mnu=class{posthog;constructor({posthogApiKey:t}){this.posthog=new ala(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.64.4",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var $2a=class{async sendEvent(){}async identify(){}async flush(){}};var ola=require("fs/promises"),a2h=require("os"),o2h=require("path");var r2h=ce(require("crypto")),Inu=new Uint8Array(256),Dnu=Inu.length;function d8c(){return Dnu>Inu.length-16&&(r2h.default.randomFillSync(Inu),Dnu=0),Inu.slice(Dnu,Dnu+=16)}var D3=[];for(let e=0;e<256;++e)D3.push((e+256).toString(16).slice(1));function i2h(e,t=0){return D3[e[t+0]]+D3[e[t+1]]+D3[e[t+2]]+D3[e[t+3]]+"-"+D3[e[t+4]]+D3[e[t+5]]+"-"+D3[e[t+6]]+D3[e[t+7]]+"-"+D3[e[t+8]]+D3[e[t+9]]+"-"+D3[e[t+10]]+D3[e[t+11]]+D3[e[t+12]]+D3[e[t+13]]+D3[e[t+14]]+D3[e[t+15]]}var n2h=ce(require("crypto")),p8c={randomUUID:n2h.default.randomUUID};function rWD(e,t,r){if(p8c.randomUUID&&!t&&!e)return p8c.randomUUID();e=e||{};let i=e.random||(e.rng||d8c)();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 i2h(i)}var Ume=rWD;var iWD="id",nWD=".fern",J2a=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new ala(r),this.userId=t==null?void 0:YFc(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.64.4",...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 Fq({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=ut(vr.of((0,a2h.homedir)()),me.of(nWD),me.of(iWD));await ii(t)||(await(0,ola.mkdir)((0,o2h.dirname)(t),{recursive:!0}),await(0,ola.writeFile)(t,Ume())),this.persistedDistinctId=(await(0,ola.readFile)(t)).toString()}return this.persistedDistinctId}};var h8c;async function ula(){return h8c==null&&(h8c=await aWD()),h8c}async function aWD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new $2a;let r=await KZo();return r!=null?new J2a({token:r,posthogApiKey:e}):await y2t()!=null?new Mnu({posthogApiKey:e}):new J2a({token:void 0,posthogApiKey:e})}catch{return new $2a}}var u2h=(e=0)=>t=>`\x1B[${t+e}m`,s2h=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,c2h=(e=0)=>(t,r,i)=>`\x1B[${38+e};2;${t};${r};${i}m`,KD={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},uw6=Object.keys(KD.modifier),oWD=Object.keys(KD.color),uWD=Object.keys(KD.bgColor),sw6=[...oWD,...uWD];function sWD(){let e=new Map;for(let[t,r]of Object.entries(KD)){for(let[i,n]of Object.entries(r))KD[i]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},r[i]=KD[i],e.set(n[0],n[1]);Object.defineProperty(KD,t,{value:r,enumerable:!1})}return Object.defineProperty(KD,"codes",{value:e,enumerable:!1}),KD.color.close="\x1B[39m",KD.bgColor.close="\x1B[49m",KD.color.ansi=u2h(),KD.color.ansi256=s2h(),KD.color.ansi16m=c2h(),KD.bgColor.ansi=u2h(10),KD.bgColor.ansi256=s2h(10),KD.bgColor.ansi16m=c2h(10),Object.defineProperties(KD,{rgbToAnsi256:{value(t,r,i){return t===r&&r===i?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(i/255*5)},enumerable:!1},hexToRgb:{value(t){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!r)return[0,0,0];let[i]=r;i.length===3&&(i=[...i].map(a=>a+a).join(""));let n=Number.parseInt(i,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:t=>KD.rgbToAnsi256(...KD.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,i,n;if(t>=232)r=((t-232)*10+8)/255,i=r,n=r;else{t-=16;let c=t%36;r=Math.floor(t/36)/5,i=Math.floor(c/6)/5,n=c%6/5}let a=Math.max(r,i,n)*2;if(a===0)return 30;let o=30+(Math.round(n)<<2|Math.round(i)<<1|Math.round(r));return a===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(t,r,i)=>KD.ansi256ToAnsi(KD.rgbToAnsi256(t,r,i)),enumerable:!1},hexToAnsi:{value:t=>KD.ansi256ToAnsi(KD.hexToAnsi256(t)),enumerable:!1}}),KD}var cWD=sWD(),S5t=cWD;var Cnu=ce(require("process"),1),f2h=ce(require("os"),1),_8c=ce(require("tty"),1);function mDe(e,t=globalThis.Deno?globalThis.Deno.args:Cnu.default.argv){let r=e.startsWith("-")?"":e.length===1?"-":"--",i=t.indexOf(r+e),n=t.indexOf("--");return i!==-1&&(n===-1||i<n)}var{env:IC}=Cnu.default,Bnu;mDe("no-color")||mDe("no-colors")||mDe("color=false")||mDe("color=never")?Bnu=0:(mDe("color")||mDe("colors")||mDe("color=true")||mDe("color=always"))&&(Bnu=1);function lWD(){if("FORCE_COLOR"in IC)return IC.FORCE_COLOR==="true"?1:IC.FORCE_COLOR==="false"?0:IC.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(IC.FORCE_COLOR,10),3)}function fWD(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function dWD(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let i=lWD();i!==void 0&&(Bnu=i);let n=r?Bnu:i;if(n===0)return 0;if(r){if(mDe("color=16m")||mDe("color=full")||mDe("color=truecolor"))return 3;if(mDe("color=256"))return 2}if("TF_BUILD"in IC&&"AGENT_NAME"in IC)return 1;if(e&&!t&&n===void 0)return 0;let a=n||0;if(IC.TERM==="dumb")return a;if(Cnu.default.platform==="win32"){let o=f2h.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in IC)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in IC)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in IC)||IC.CI_NAME==="codeship"?1:a;if("TEAMCITY_VERSION"in IC)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(IC.TEAMCITY_VERSION)?1:0;if(IC.COLORTERM==="truecolor"||IC.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in IC){let o=Number.parseInt((IC.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(IC.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(IC.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(IC.TERM)||"COLORTERM"in IC?1:a}function l2h(e,t={}){let r=dWD(e,{streamIsTTY:e&&e.isTTY,...t});return fWD(r)}var pWD={stdout:l2h({isTTY:_8c.default.isatty(1)}),stderr:l2h({isTTY:_8c.default.isatty(2)})},d2h=pWD;function p2h(e,t,r){let i=e.indexOf(t);if(i===-1)return e;let n=t.length,a=0,o="";do o+=e.slice(a,i)+t+r,a=i+n,i=e.indexOf(t,a);while(i!==-1);return o+=e.slice(a),o}function h2h(e,t,r,i){let n=0,a="";do{let o=e[i-1]==="\r";a+=e.slice(n,o?i-1:i)+t+(o?`\r
|
|
1359
1359
|
`:`
|
|
1360
1360
|
`)+r,n=i+1,i=e.indexOf(`
|
|
1361
1361
|
`,n)}while(i!==-1);return a+=e.slice(n),a}var{stdout:_2h,stderr:y2h}=d2h,y8c=Symbol("GENERATOR"),sla=Symbol("STYLER"),Y2a=Symbol("IS_EMPTY"),b2h=["ansi","ansi","ansi256","ansi16m"],cla=Object.create(null),hWD=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let r=_2h?_2h.level:0;e.level=t.level===void 0?r:t.level};var _WD=e=>{let t=(...r)=>r.join(" ");return hWD(t,e),Object.setPrototypeOf(t,X2a.prototype),t};function X2a(e){return _WD(e)}Object.setPrototypeOf(X2a.prototype,Function.prototype);for(let[e,t]of Object.entries(S5t))cla[e]={get(){let r=qnu(this,v8c(t.open,t.close,this[sla]),this[Y2a]);return Object.defineProperty(this,e,{value:r}),r}};cla.visible={get(){let e=qnu(this,this[sla],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var b8c=(e,t,r,...i)=>e==="rgb"?t==="ansi16m"?S5t[r].ansi16m(...i):t==="ansi256"?S5t[r].ansi256(S5t.rgbToAnsi256(...i)):S5t[r].ansi(S5t.rgbToAnsi(...i)):e==="hex"?b8c("rgb",t,r,...S5t.hexToRgb(...i)):S5t[r][e](...i),yWD=["rgb","hex","ansi256"];for(let e of yWD){cla[e]={get(){let{level:r}=this;return function(...i){let n=v8c(b8c(e,b2h[r],"color",...i),S5t.color.close,this[sla]);return qnu(this,n,this[Y2a])}}};let t="bg"+e[0].toUpperCase()+e.slice(1);cla[t]={get(){let{level:r}=this;return function(...i){let n=v8c(b8c(e,b2h[r],"bgColor",...i),S5t.bgColor.close,this[sla]);return qnu(this,n,this[Y2a])}}}}var bWD=Object.defineProperties(()=>{},{...cla,level:{enumerable:!0,get(){return this[y8c].level},set(e){this[y8c].level=e}}}),v8c=(e,t,r)=>{let i,n;return r===void 0?(i=e,n=t):(i=r.openAll+e,n=t+r.closeAll),{open:e,close:t,openAll:i,closeAll:n,parent:r}},qnu=(e,t,r)=>{let i=(...n)=>vWD(i,n.length===1?""+n[0]:n.join(" "));return Object.setPrototypeOf(i,bWD),i[y8c]=e,i[sla]=t,i[Y2a]=r,i},vWD=(e,t)=>{if(e.level<=0||!t)return e[Y2a]?"":t;let r=e[sla];if(r===void 0)return t;let{openAll:i,closeAll:n}=r;if(t.includes("\x1B"))for(;r!==void 0;)t=p2h(t,r.close,r.open),r=r.parent;let a=t.indexOf(`
|
|
@@ -1597,7 +1597,7 @@ ${n.mark.snippet}`)),t.failAndThrow(o)}else throw n}}async function cAe({absolut
|
|
|
1597
1597
|
`)),{ok:!0,value:t}):i}}function bMu(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var bya=class e extends Error{errors;constructor(t){super(t.map(bMu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var vya=class e extends Error{errors;constructor(t){super(t.map(bMu).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function DP(e){return{nullable:()=>$UI(e),optional:()=>jol(e),optionalNullable:()=>JUI(e),transform:t=>wol(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new vya(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new bya(i.errors)}}}function $UI(e){let t={parse:(r,i)=>r==null?{ok:!0,value:null}:e.parse(r,i),json:(r,i)=>r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>cp.NULLABLE};return{...t,...DP(t)}}function jol(e){let t={parse:(r,i)=>r==null?{ok:!0,value:void 0}:e.parse(r,i),json:(r,i)=>i?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>cp.OPTIONAL};return{...t,...DP(t)}}function JUI(e){let t={parse:(r,i)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.parse(r,i),json:(r,i)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.json(r,i),getType:()=>cp.OPTIONAL_NULLABLE};return{...t,...DP(t)}}function wol(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(i,n)=>{let a=t.untransform(i);return e.json(a,n)},getType:()=>e.getType()};return{...r,...DP(r)}}function Lz_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t}:typeof t=="number"?{ok:!0,value:BigInt(t)}:{ok:!1,errors:[{path:r,message:GA(t,"bigint | number")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="bigint"?{ok:!1,errors:[{path:r,message:GA(t,"bigint")}]}:{ok:!0,value:t},getType:()=>cp.BIGINT};return{...TU(e),...DP(e)}}var YUI=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function Vz_(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:GA(t,"string")}]}:YUI.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:GA(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:GA(t,"Date object")}]},getType:()=>cp.DATE};return{...TU(e),...DP(e)}}function RU(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...TU(r),...DP(r)}}}function vMu(e){let t=new Set(e);return RU(cp.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:GA(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:GA(i,"enum")}]}:{ok:!0,value:i})()}function Wz_(e){let t=Eol(e);return{...t,...DP(t)}}function Eol(e){return{parse:(t,r)=>gya(e).parse(t,r),json:(t,r)=>gya(e).json(t,r),getType:()=>gya(e).getType()}}function gya(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function Pno(e){return Object.entries(e)}function jno(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function s8i(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function wno(e){return Object.keys(e)}function xz_(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function yHt(e){return{withParsedProperties:t=>Sol(e,t)}}function Sol(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let o=Object.entries(t).reduce((c,[d,s])=>({...c,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...o}}},json:(i,n)=>{if(!s8i(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:GA(i,"object")}]};let a=new Set(Object.keys(t)),o=jno(i,Object.keys(i).filter(c=>!a.has(c)));return e.json(o,n)},getType:()=>e.getType()};return{...r,...DP(r),...yHt(r)}}function Hz_(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function aen(e){return e.isProperty}function gMu(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>aen(i)?i.rawKey:r),_getParsedProperties:()=>wno(e),parse:(r,i)=>{let n={},a=[];for(let[o,c]of Pno(e)){let d=aen(c)?c.rawKey:o,s=aen(c)?c.valueSchema:c,u={rawKey:d,parsedKey:o,valueSchema:s};n[d]=u,$z_(s)&&a.push(d)}return Gz_({value:r,requiredKeys:a,getProperty:o=>{let c=n[o];if(c!=null)return{transformedKey:c.parsedKey,transform:d=>c.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],o]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,o]of Pno(e)){let c=aen(o)?o.valueSchema:o;$z_(c)&&n.push(a)}return Gz_({value:r,requiredKeys:n,getProperty:a=>{let o=e[a];if(o!=null)return aen(o)?{transformedKey:o.rawKey,transform:c=>o.valueSchema.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:c=>o.json(c,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>cp.OBJECT};return{...TU(t),...DP(t),...yHt(t),...awn(t)}}function Gz_({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!s8i(e))return{ok:!1,errors:[{path:a,message:GA(e,"object")}]};let o=new Set(t),c=[],d={};for(let[s,u]of Object.entries(e)){let f=r(s);if(f!=null){o.delete(s);let p=f.transform(u);p.ok?d[f.transformedKey]=p.value:(d[s]=u,c.push(...p.errors))}else switch(i){case"fail":c.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=u;break}}return c.push(...t.filter(s=>o.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),c.length===0||n?{ok:!0,value:d}:{ok:!1,errors:c}}function awn(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>Kz_({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>Kz_({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>cp.OBJECT};return{...r,...DP(r),...yHt(r),...awn(r)}},passthrough:()=>{let t=new Set(e._getRawProperties()),r=new Set(e._getParsedProperties()),i={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(n,a)=>{let o=e.parse(n,{...a,unrecognizedObjectKeys:"passthrough"});if(!o.ok)return o;let c={};if(typeof n=="object"&&n!=null)for(let[d,s]of Object.entries(n))t.has(d)||(c[d]=s);return{ok:!0,value:{...c,...o.value}}},json:(n,a)=>{let o=e.json(n,{...a,unrecognizedObjectKeys:"passthrough"});if(!o.ok)return o;let c={};if(typeof n=="object"&&n!=null)for(let[d,s]of Object.entries(n))r.has(d)||(c[d]=s);return{ok:!0,value:{...c,...o.value}}},getType:()=>cp.OBJECT};return{...i,...DP(i),...yHt(i),...awn(i)}}}}function Kz_({extensionKeys:e,value:t,transformBase:r,transformExtension:i,breadcrumbsPrefix:n=[]}){if(!s8i(t))return{ok:!1,errors:[{path:n,message:GA(t,"object")}]};let a=new Set(e),[o,c]=xz_(wno(t),u=>a.has(u)),d=r(jno(t,c)),s=i(jno(t,o));return d.ok&&s.ok?{ok:!0,value:{...d.value,...s.value}}:{ok:!1,errors:[...d.ok?[]:d.errors,...s.ok?[]:s.errors]}}function $z_(e){return!XUI(e)}function XUI(e){switch(e.getType()){case cp.ANY:case cp.UNKNOWN:case cp.OPTIONAL:case cp.OPTIONAL_NULLABLE:return!0;default:return!1}}function Jz_(e){return gMu(e)}function Yz_(e){let t={...Eol(e),_getRawProperties:()=>gya(e)._getRawProperties(),_getParsedProperties:()=>gya(e)._getParsedProperties()};return{...t,...DP(t),...yHt(t),...awn(t)}}function OMu(e){let t={parse:(r,i)=>Xz_(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>Xz_(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>cp.LIST};return{...TU(t),...DP(t)}}function Xz_(e,t){return Array.isArray(e)?e.map((i,n)=>t(i,n)).reduce((i,n)=>{if(i.ok&&n.ok)return{ok:!0,value:[...i.value,n.value]};let a=[];return i.ok||a.push(...i.errors),n.ok||a.push(...n.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:GA(e,"list"),path:[]}]}}function Zz_(e){return RU(cp.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:GA(r,`${e.toString()}`)}]})()}function kz_(e){return RU(cp.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:GA(r,`"${e}"`)}]})()}var eN_=RU(cp.ANY,e=>({ok:!0,value:e}));var tN_=RU(cp.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:GA(e,"boolean")}]});var rN_=RU(cp.NEVER,(e,{breadcrumbsPrefix:t=[]}={})=>({ok:!1,errors:[{path:t,message:"Expected never"}]}));var iN_=RU(cp.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:GA(e,"number")}]});var nN_=RU(cp.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:GA(e,"string")}]});var aN_=RU(cp.UNKNOWN,e=>({ok:!0,value:e}));function uN_(e,t){let r={parse:(i,n)=>oN_({value:i,isKeyNumeric:e.getType()===cp.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>oN_({value:i,isKeyNumeric:e.getType()===cp.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,o)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${o}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>cp.RECORD};return{...TU(r),...DP(r)}}function oN_({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return s8i(e)?Pno(e).reduce((a,[o,c])=>{if(c===void 0)return a;let d=a,s=o;if(t){let h=o.length>0?Number(o):NaN;Number.isNaN(h)||(s=h)}let u=r(s),f=i(c,s);if(d.ok&&u.ok&&f.ok)return{ok:!0,value:{...d.value,[u.value]:f.value}};let p=[];return d.ok||p.push(...d.errors),u.ok||p.push(...u.errors),f.ok||p.push(...f.errors),{ok:!1,errors:p}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:GA(e,"object")}]}}function sN_(e){let t=OMu(e),r={parse:(i,n)=>{let a=t.parse(i,n);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(i,n)=>i instanceof Set?t.json([...i],n):{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:GA(i,"Set")}]},getType:()=>cp.SET};return{...TU(r),...DP(r)}}function lN_(e){let t={parse:(r,i)=>cN_((n,a)=>n.parse(r,a),e,i),json:(r,i)=>cN_((n,a)=>n.json(r,a),e,i),getType:()=>cp.UNDISCRIMINATED_UNION};return{...TU(t),...DP(t)}}function cN_(e,t,r){let i=[];for(let[n,a]of t.entries()){let o=e(a,{...r,skipValidation:!1});if(o.ok)return o;for(let c of o.errors)i.push({path:c.path,message:`[Variant ${n}] ${c.message}`})}return{ok:!1,errors:i}}function fN_(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function pN_(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=vMu(wno(t)),a={parse:(o,c)=>dN_({value:o,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),json:(o,c)=>dN_({value:o,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:c?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...c?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:c?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,c),breadcrumbsPrefix:c?.breadcrumbsPrefix}),getType:()=>cp.UNION};return{...TU(a),...DP(a),...yHt(a)}}function dN_({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:o,breadcrumbsPrefix:c=[]}){if(!s8i(e))return{ok:!1,errors:[{path:c,message:GA(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:c,message:`Missing discriminant ("${t}")`}]};let u=i(d);if(!u.ok)return{ok:!1,errors:u.errors};let f=n(u.value);if(f==null)return a?{ok:!0,value:{[r]:u.value,...s}}:{ok:!1,errors:[{path:[...c,t],message:"Unexpected discriminant value"}]};let p=o(s,f);return p.ok?{ok:!0,value:{[r]:d,...p.value}}:p}var Jkt=ga.objectWithoutOptionalProperties({docs:ga.string().optional()});var Dol={};$t(Dol,{ConjureServiceName:()=>mMu,DefinitionFile:()=>hN_});var mMu=ga.string();var AMu=ga.enum_(["none","header"]);var Oya=ga.undiscriminatedUnion([AMu,ga.string()]);var PMu=ga.enum_(["rid","string","safelong","integer","double","boolean","binary"]);var oen=ga.undiscriminatedUnion([PMu,ga.string()]);var jMu=ga.objectWithoutOptionalProperties({type:oen,docs:ga.string().optional()});var uen=ga.undiscriminatedUnion([oen,jMu]);var wMu=ga.enum_(["path","query","body"]);var EMu=ga.objectWithoutOptionalProperties({paramType:ga.property("param-type",wMu),type:ga.string()}).extend(Jkt);var SMu=ga.undiscriminatedUnion([ga.string(),EMu]);var MMu=ga.objectWithoutOptionalProperties({http:ga.string(),auth:Oya.optional(),args:ga.record(ga.string(),SMu).optional(),returns:uen.optional()}).extend(Jkt);var DMu=ga.objectWithoutOptionalProperties({name:ga.string().optional(),package:ga.string().optional(),basePath:ga.property("base-path",ga.string().optional()),defaultAuth:ga.property("default-auth",Oya.optional()),endpoints:ga.record(ga.string(),MMu).optional()}).extend(Jkt);var IMu=ga.objectWithoutOptionalProperties({alias:oen,docs:ga.string().optional()});var BMu=ga.objectWithoutOptionalProperties({value:ga.string()}).extend(Jkt);var CMu=ga.undiscriminatedUnion([ga.string(),BMu]);var qMu=ga.objectWithoutOptionalProperties({values:ga.list(CMu)});var TMu=ga.objectWithoutOptionalProperties({fields:ga.record(ga.string(),uen)});var RMu=ga.objectWithoutOptionalProperties({union:ga.record(ga.string(),uen)});var zMu=ga.undiscriminatedUnion([IMu,RMu,TMu,qMu]);var NMu=ga.objectWithoutOptionalProperties({objects:ga.record(ga.string(),zMu).optional()});var FMu=ga.objectWithoutOptionalProperties({conjureImports:ga.property("conjure-imports",ga.record(ga.string(),ga.string()).optional()),definitions:NMu.optional()});var hN_=ga.objectWithoutOptionalProperties({types:FMu.optional(),services:ga.record(mMu,DMu).optional()});var Iol={};$t(Iol,{ConjureArgument:()=>SMu,ConjureArgumentWithParamType:()=>EMu,ConjureAuthDefinition:()=>Oya,ConjureAuthDefinitionType:()=>AMu,ConjureEndpointDefinition:()=>MMu,ConjureParamType:()=>wMu,ConjureService:()=>DMu});var Bol={};$t(Bol,{ConjureAliasDeclaration:()=>IMu,ConjureDefinitions:()=>NMu,ConjureEnumDeclaration:()=>qMu,ConjureEnumVariant:()=>CMu,ConjureEnumWithDocs:()=>BMu,ConjureObjectDeclaration:()=>TMu,ConjurePrimitive:()=>PMu,ConjureType:()=>oen,ConjureTypeDeclaration:()=>zMu,ConjureTypeReference:()=>uen,ConjureTypeWithDocs:()=>jMu,ConjureTypes:()=>FMu,ConjureUnionDeclaration:()=>RMu});var _N_=require("fs/promises");async function yN_(e,t){let r=[];for(let i of await p3(e,t))r.push(await ZUI({relativeFilepath:Jl(e,i),absoluteFilepath:i}));return r}async function ZUI({relativeFilepath:e,absoluteFilepath:t}){let r=(await(0,_N_.readFile)(t)).toString().replaceAll(/: rid(?:$|\s)/g,`: string
|
|
1598
1598
|
`).replaceAll("<rid>","<string>").replaceAll("rid>","string>").replaceAll(": safelong",": long").replaceAll("<safelong>","<long>").replaceAll("safelong>","long>").replaceAll(": any",": unknown").replaceAll("<any>","<unknown>").replaceAll("any>","unknown>");return{relativeFilepath:e,absoluteFilepath:t,fileContents:QMu.conjure.DefinitionFile.parseOrThrow(Mi.load(r),{unrecognizedObjectKeys:"passthrough",allowUnrecognizedEnumValues:!0,allowUnrecognizedUnionMembers:!0})}}function bN_(e,t){if(kUI(e))return t.alias(e);if(eLI(e))return t.enum(e);if(tLI(e))return t.object(e);if(rLI(e))return t.union(e);fe(e)}function kUI(e){return e?.alias!=null}function eLI(e){return e?.values!=null}function tLI(e){return e?.fields!=null}function rLI(e){return e?.union!=null}var Eno=class extends lro{fernDefinitionBuilder=new JPn(!1);conjureFilepathToFernFilepath={};async import({absolutePathToConjureFolder:t,authOverrides:r,environmentOverrides:i,globalHeaderOverrides:n}){if(r!=null){for(let[a,o]of Object.entries(r["auth-schemes"]??{}))this.fernDefinitionBuilder.addAuthScheme({name:a,schema:o});r.auth!=null&&this.fernDefinitionBuilder.setAuth(r.auth)}if(i!=null){for(let[a,o]of Object.entries(i.environments??{}))this.fernDefinitionBuilder.addEnvironment({name:a,schema:o});i["default-environment"]!=null&&this.fernDefinitionBuilder.setDefaultEnvironment(i["default-environment"]),i["default-url"]!=null&&this.fernDefinitionBuilder.setDefaultUrl(i["default-url"])}return await vN_(t,(a,o,c)=>{for(let[u,f]of Object.entries(c.services??{})){let p=JXo({value:u,suffix:"Service"});this.conjureFilepathToFernFilepath[o]=me.of(`${p}/__package__.yml`);return}let s=S3i(o)?.split(".")[0];s!=null&&(this.conjureFilepathToFernFilepath[o]=me.of(`${s}/__package__.yml`))}),await vN_(t,(a,o,c)=>{if(c.services==null||Object.keys(c.services??{}).length===0){let d=this.conjureFilepathToFernFilepath[o];if(d==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${o}`);for(let[s,u]of Object.entries(c.types?.conjureImports??{})){let f=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:me.of(u)});this.fernDefinitionBuilder.addImport({file:d,fileToImport:me.of(f),alias:s})}this.importAllTypes({conjureFile:c,fernFilePath:d});return}for(let[d,s]of Object.entries(c.services)){let u=JXo({value:d,suffix:"Service"}),f=me.of(`${u}/__package__.yml`),p={};s.basePath!=null&&(p["base-path"]=s.basePath),s.docs!=null&&(p.docs=s.docs),this.fernDefinitionBuilder.setServiceInfo(f,p),this.importAllTypes({conjureFile:c,fernFilePath:f});for(let[h,_]of Object.entries(c.types?.conjureImports??{})){let y=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:me.of(_)});this.fernDefinitionBuilder.addImport({file:f,fileToImport:me.of(y),alias:h})}for(let[h,_]of Object.entries(s.endpoints??{})){let y=dzc(_.http);if(y.type==="failure"){this.context?.logger.error(`Failed to parse ${_.http}. Skipping.`);continue}let v={auth:(_.auth??s.defaultAuth)!==Qz_.None,path:y.path,method:y.method,response:_.returns==="binary"?"file":_.returns};_.docs!=null&&(v.docs=_.docs);let O={};if(_.args!=null)for(let m of y.pathParameters){let g=_.args[m];if(g==null)throw new Error(`Failed to find path parameter ${m} in ${_.http}`);O[m]=typeof g=="string"?g:{type:g.type}}Object.entries(O).length>0&&(v["path-parameters"]=O);for(let[m,g]of Object.entries(_.args??{}))if(O[m]==null)if(typeof g=="string")v.request?typeof v.request=="string"&&(v.request={body:v.request}):v.request={},v.request.body=g==="binary"?"bytes":g;else switch(g.paramType){case"body":v.request={body:g.type==="binary"?"bytes":g.type};break;case"query":v.request==null?v.request={"query-parameters":{[m]:g.type}}:typeof v.request!="string"&&v.request?.["query-parameters"]==null?v.request["query-parameters"]={[m]:g.type}:typeof v.request!="string"&&v.request?.["query-parameters"]!=null&&(v.request["query-parameters"][m]=g.type)}v.request!=null&&typeof v.request!="string"&&v.request?.["query-parameters"]!=null&&(v.request.name=`${h}Request`),this.fernDefinitionBuilder.addEndpoint(f,{name:h,schema:v,source:void 0})}}}),this.fernDefinitionBuilder.build()}convertBinaryType(t){return typeof t=="string"?t==="binary"?{type:"string",validation:{format:"binary"}}:t:t.type==="binary"?{...t,type:"string",validation:{format:"binary"}}:t}importAllTypes({conjureFile:t,fernFilePath:r}){for(let[i,n]of Object.entries(t.types?.definitions?.objects??{}))bN_(n,{alias:a=>{let o=a.alias==="binary"?{type:"string",validation:{format:"binary"}}:a.alias;this.fernDefinitionBuilder.addType(r,{name:i,schema:typeof o=="string"?{type:o,docs:a.docs}:{...o,docs:a.docs}})},object:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{properties:Object.fromEntries(Object.entries(a.fields).map(([o,c])=>[o,this.convertBinaryType(c)]))}})},enum:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{enum:a.values}})},union:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{union:Object.fromEntries(Object.entries(a.union).map(([o,c])=>{let d=this.convertBinaryType(c);return[o,{type:typeof d=="string"?d:d.type,docs:typeof d=="string"?void 0:d.docs,key:o}]}))}})}})}getFernFileToImport({absoluteFilePathToConjureFile:t,importFilePath:r,absoluteFilePathToConjureFolder:i}){let n=ut(rn(t),me.of(r)),a=tR(i,n),o=this.conjureFilepathToFernFilepath[a];if(o==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${a}`);return o}};async function vN_(e,t){for(let r of await yN_(e,"{yml,yaml}"))await t(r.absoluteFilepath,r.relativeFilepath,r.fileContents)}function gN_(e,t){return On(e,t)}var mya=class extends W5t{type="conjure";absolutePathToConjureFolder;constructor({relativePathToConjureDirectory:t,...r}){super(r),this.absolutePathToConjureFolder=ut(r.absoluteFilePath,t)}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new xZ({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion,sources:void 0})}async getDefinition({context:t},r){let n=await new Eno(t).import({absolutePathToConjureFolder:this.absolutePathToConjureFolder,authOverrides:this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0,environmentOverrides:this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:vr.of("/DUMMY_PATH"),rootApiFile:{defaultUrl:n.rootApiFile["default-url"],contents:n.rootApiFile,rawContents:Mi.dump(n.rootApiFile)},namedDefinitionFiles:{...gN_(n.definitionFiles,a=>({absoluteFilepath:vr.of("/DUMMY_PATH"),rawContents:Mi.dump(a),contents:a})),[me.of(Gv)]:{absoluteFilepath:vr.of("/DUMMY_PATH"),rawContents:Mi.dump(n.packageMarkerFile),contents:n.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}getAbsoluteFilePaths(){return[this.absolutePathToConjureFolder]}};var LF_=ce(wN_(),1);var sh;(function(e){e.FILE_READ="FILE_READ",e.FILE_PARSE="FILE_PARSE",e.FILE_MISSING="FILE_MISSING",e.STRUCTURE_VALIDATION="STRUCTURE_VALIDATION",e.JSONSCHEMA_VALIDATION="JSONSCHEMA_VALIDATION",e.DEPENDENCY_NOT_LISTED="DEPENDENCY_NOT_LISTED",e.FAILED_TO_LOAD_DEPENDENCY="FAILED_TO_LOAD_DEPENDENCY",e.EXPORTING_PACKAGE_MARKER_OTHER_KEYS="EXPORTING_PACKAGE_MARKER_OTHER_KEYS",e.EXPORT_PACKAGE_HAS_DEFINITIONS="EXPORT_PACKAGE_HAS_DEFINITIONS",e.MISCONFIGURED_DIRECTORY="MISCONFIGURED_DIRECTORY"})(sh||(sh={}));function EN_(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function UMu(e,t){for(let[r,i]of KI(e))nLI({relativeFilepath:r,failure:i,logger:t})}function nLI({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case sh.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case sh.FILE_READ:r.error("Failed to open file: "+e);break;case sh.FILE_MISSING:r.error("Missing file: "+e);break;case sh.FILE_PARSE:t.error instanceof leo?r.error(ADe({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case sh.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of aLI(i))r.error(ADe({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case sh.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case sh.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${hbu}: `+t.dependencyName);break;case sh.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case sh.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case sh.JSONSCHEMA_VALIDATION:if(t.error.error!=null){let i=t.error.error.instancePath.split("/").filter(n=>n!=="").map(EN_);t.error.error.keyword==="required"&&t.error.error.params?.missingProperty?i.push(t.error.error.params.missingProperty):t.error.error.keyword==="additionalProperties"&&t.error.error.params?.additionalProperty&&i.push(t.error.error.params.additionalProperty),r.error(ADe({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...i]}))}for(let i of t.error.allErrors)if(i!==t.error.error){let n=i.instancePath.split("/").filter(a=>a!=="").map(EN_);i.keyword==="required"&&i.params?.missingProperty?n.push(i.params.missingProperty):i.keyword==="additionalProperties"&&i.params?.additionalProperty&&n.push(i.params.additionalProperty),r.debug(ADe({title:i.message??"Unknown error",breadcrumbs:[e,...n]}))}break;default:fe(t)}}function aLI(e){switch(e.code){case Fi.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Je.underline(e.expected)} but received ${Je.underline(e.received)}`}];case Fi.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Je.underline(t)}`}));case Fi.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Je.underline(t)).join(", ")}`}];case Fi.invalid_union:case Fi.invalid_arguments:case Fi.invalid_return_type:case Fi.invalid_date:case Fi.invalid_string:case Fi.too_small:case Fi.too_big:case Fi.invalid_intersection_types:case Fi.not_multiple_of:case Fi.custom:default:return[{title:e.message}]}}var SN_=require("fs/promises");async function MN_(e,t){let r=[];for(let i of await p3(e,t))r.push(await oLI({relativeFilepath:Jl(e,i),absoluteFilepath:i}));return r}async function oLI({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,SN_.readFile)(t)).toString()}}async function DN_(e){let t={},r={};function i(n){try{t[n.relativeFilepath]={defaultUrl:void 0,contents:Mi.load(n.fileContents,{schema:Mi.CORE_SCHEMA}),rawContents:n.fileContents}}catch(a){r[n.relativeFilepath]={type:sh.FILE_PARSE,error:a}}}return await Promise.all(e.map(i)),Object.keys(r).length>0?{didSucceed:!1,failures:r}:{didSucceed:!0,files:t}}var Mno=ce(hZ(),1);function Tol(e,t){if(e=Mno.default.parse(e),t=Mno.default.parse(t),!(Mno.default.compareBuild(e,t)>=0))return Mno.default.diff(e,t)||"build"}var uLI=/^([0-9]+)\.([0-9]+)\.([0-9]+)-([0-9]+)-([a-z0-9])+$/,sLI=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)-([0-9]+)-([a-z0-9])+$/,cLI=/^([0-9]+)\.([0-9]+)\.([0-9]+)-rc[.-]?([0-9]+)$/,lLI=/^([0-9]+)\.([0-9]+)\.([0-9]+)$/,fLI=/^([0-9]+)\.([0-9]+)\.([0-9]+)-alpha[.-]?([0-9]+)$/,dLI=/^([0-9]+)\.([0-9]+)\.([0-9]+)-beta[.-]?([0-9]+)$/;function uwn(e){let t=e.match(fLI);if(t!=null){let[c,d,s,u,f]=t,p=rI(d),h=rI(s),_=rI(u),y=rI(f);if(p==null||h==null||_==null||y==null)throw new Error("Cannot parse alpha version: "+e);return{type:"alpha",major:p,minor:h,patch:_,index:y}}let r=e.match(dLI);if(r!=null){let[c,d,s,u,f]=r,p=rI(d),h=rI(s),_=rI(u),y=rI(f);if(p==null||h==null||_==null||y==null)throw new Error("Cannot parse beta version: "+e);return{type:"beta",major:p,minor:h,patch:_,index:y}}let i=e.match(uLI);if(i!=null){let[c,d,s,u,f]=i,p=rI(d),h=rI(s),_=rI(u),y=rI(f);if(p==null||h==null||_==null||y==null)throw new Error("Cannot parse post-release commit version: "+e);return{type:"post-release-commit",major:p,minor:h,patch:_,commitIndex:y}}let n=e.match(cLI);if(n!=null){let[c,d,s,u,f]=n,p=rI(d),h=rI(s),_=rI(u),y=rI(f);if(p==null||h==null||_==null||y==null)throw new Error("Cannot parse RC version: "+e);return{type:"rc",major:p,minor:h,patch:_,releaseCandidateIndex:y}}let a=e.match(sLI);if(a!=null){let[c,d,s,u,f,p]=a,h=rI(d),_=rI(s),y=rI(u),b=rI(f),v=rI(p);if(h==null||_==null||y==null||b==null||v==null)throw new Error("Cannot parse post-RC version: "+e);return{type:"post-rc-commit",major:h,minor:_,patch:y,releaseCandidateIndex:b,commitIndex:v}}let o=e.match(lLI);if(o!=null){let[c,d,s,u]=o,f=rI(d),p=rI(s),h=rI(u);if(f==null||p==null||h==null)throw new Error("Cannot parse release version: "+e);return{type:"release",major:f,minor:p,patch:h}}throw new Error("Failed to parse version: "+e)}function rI(e){if(e==null||e.length===0)return;let t=Number(e);if(!isNaN(t))return t}function p2(e,t){if(e===t)return!1;let r=uwn(e),i=uwn(t);if(r.major!==i.major||r.minor!==i.minor||r.patch!==i.patch)return Tol(IN_(r),IN_(i))==null;if(r.type==="post-release-commit")return i.type!=="post-release-commit"||r.commitIndex>i.commitIndex;if(r.type==="release")return i.type!=="post-release-commit";if(r.type==="rc"){switch(i.type){case"release":case"post-release-commit":return!1;case"alpha":case"beta":return!0}return r.releaseCandidateIndex!==i.releaseCandidateIndex&&r.releaseCandidateIndex>i.releaseCandidateIndex}if(r.type==="post-rc-commit"){switch(i.type){case"release":case"post-release-commit":return!1;case"alpha":case"beta":return!0}if(i.type==="post-rc-commit")return r.releaseCandidateIndex!==i.releaseCandidateIndex?r.releaseCandidateIndex>i.releaseCandidateIndex:r.commitIndex>i.commitIndex}if(r.type==="beta"){switch(i.type){case"release":case"post-release-commit":case"rc":case"post-rc-commit":return!1;case"alpha":return!0}return r.index>i.index}if(r.type==="alpha"){switch(i.type){case"release":case"post-release-commit":case"rc":case"post-rc-commit":return!1}return r.index>i.index}return!p2(t,e)}function IN_(e){return`${e.major}.${e.minor}.${e.patch}`}var Lul=ce(w3i(),1);var BF_=require("fs"),Rya=require("fs/promises");var CF_=require("os"),qF_=ce(require("path"),1),TF_=require("stream/promises");var BN_=ce(require("events"),1),Z7=ce(require("fs"),1);var pLI=Z7.default.writev,cen=Symbol("_autoClose"),vHt=Symbol("_close"),Dno=Symbol("_ended"),sw=Symbol("_fd"),Rol=Symbol("_finished"),l8i=Symbol("_flags"),zol=Symbol("_flush"),Uol=Symbol("_handleChunk"),Lol=Symbol("_makeBuf"),Bno=Symbol("_mode"),LMu=Symbol("_needDrain"),wya=Symbol("_onerror"),Eya=Symbol("_onopen"),Nol=Symbol("_onread"),Pya=Symbol("_onwrite"),len=Symbol("_open"),bHt=Symbol("_path"),sen=Symbol("_pos"),Ykt=Symbol("_queue"),jya=Symbol("_read"),Fol=Symbol("_readSize"),c8i=Symbol("_reading"),Ino=Symbol("_remain"),Qol=Symbol("_size"),VMu=Symbol("_write"),swn=Symbol("_writing"),WMu=Symbol("_defaultFlag"),cwn=Symbol("_errored"),lwn=class extends bN{[cwn]=!1;[sw];[bHt];[Fol];[c8i]=!1;[Qol];[Ino];[cen];constructor(t,r){if(r=r||{},super(r),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[cwn]=!1,this[sw]=typeof r.fd=="number"?r.fd:void 0,this[bHt]=t,this[Fol]=r.readSize||16*1024*1024,this[c8i]=!1,this[Qol]=typeof r.size=="number"?r.size:1/0,this[Ino]=this[Qol],this[cen]=typeof r.autoClose=="boolean"?r.autoClose:!0,typeof this[sw]=="number"?this[jya]():this[len]()}get fd(){return this[sw]}get path(){return this[bHt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[len](){Z7.default.open(this[bHt],"r",(t,r)=>this[Eya](t,r))}[Eya](t,r){t?this[wya](t):(this[sw]=r,this.emit("open",r),this[jya]())}[Lol](){return Buffer.allocUnsafe(Math.min(this[Fol],this[Ino]))}[jya](){if(!this[c8i]){this[c8i]=!0;let t=this[Lol]();if(t.length===0)return process.nextTick(()=>this[Nol](null,0,t));Z7.default.read(this[sw],t,0,t.length,null,(r,i,n)=>this[Nol](r,i,n))}}[Nol](t,r,i){this[c8i]=!1,t?this[wya](t):this[Uol](r,i)&&this[jya]()}[vHt](){if(this[cen]&&typeof this[sw]=="number"){let t=this[sw];this[sw]=void 0,Z7.default.close(t,r=>r?this.emit("error",r):this.emit("close"))}}[wya](t){this[c8i]=!0,this[vHt](),this.emit("error",t)}[Uol](t,r){let i=!1;return this[Ino]-=t,t>0&&(i=super.write(t<r.length?r.subarray(0,t):r)),(t===0||this[Ino]<=0)&&(i=!1,this[vHt](),super.end()),i}emit(t,...r){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[sw]=="number"&&this[jya](),!1;case"error":return this[cwn]?!1:(this[cwn]=!0,super.emit(t,...r));default:return super.emit(t,...r)}}},xMu=class extends lwn{[len](){let t=!0;try{this[Eya](null,Z7.default.openSync(this[bHt],"r")),t=!1}finally{t&&this[vHt]()}}[jya](){let t=!0;try{if(!this[c8i]){this[c8i]=!0;do{let r=this[Lol](),i=r.length===0?0:Z7.default.readSync(this[sw],r,0,r.length,null);if(!this[Uol](i,r))break}while(!0);this[c8i]=!1}t=!1}finally{t&&this[vHt]()}}[vHt](){if(this[cen]&&typeof this[sw]=="number"){let t=this[sw];this[sw]=void 0,Z7.default.closeSync(t),this.emit("close")}}},f8i=class extends BN_.default{readable=!1;writable=!0;[cwn]=!1;[swn]=!1;[Dno]=!1;[Ykt]=[];[LMu]=!1;[bHt];[Bno];[cen];[sw];[WMu];[l8i];[Rol]=!1;[sen];constructor(t,r){r=r||{},super(r),this[bHt]=t,this[sw]=typeof r.fd=="number"?r.fd:void 0,this[Bno]=r.mode===void 0?438:r.mode,this[sen]=typeof r.start=="number"?r.start:void 0,this[cen]=typeof r.autoClose=="boolean"?r.autoClose:!0;let i=this[sen]!==void 0?"r+":"w";this[WMu]=r.flags===void 0,this[l8i]=r.flags===void 0?i:r.flags,this[sw]===void 0&&this[len]()}emit(t,...r){if(t==="error"){if(this[cwn])return!1;this[cwn]=!0}return super.emit(t,...r)}get fd(){return this[sw]}get path(){return this[bHt]}[wya](t){this[vHt](),this[swn]=!0,this.emit("error",t)}[len](){Z7.default.open(this[bHt],this[l8i],this[Bno],(t,r)=>this[Eya](t,r))}[Eya](t,r){this[WMu]&&this[l8i]==="r+"&&t&&t.code==="ENOENT"?(this[l8i]="w",this[len]()):t?this[wya](t):(this[sw]=r,this.emit("open",r),this[swn]||this[zol]())}end(t,r){return t&&this.write(t,r),this[Dno]=!0,!this[swn]&&!this[Ykt].length&&typeof this[sw]=="number"&&this[Pya](null,0),this}write(t,r){return typeof t=="string"&&(t=Buffer.from(t,r)),this[Dno]?(this.emit("error",new Error("write() after end()")),!1):this[sw]===void 0||this[swn]||this[Ykt].length?(this[Ykt].push(t),this[LMu]=!0,!1):(this[swn]=!0,this[VMu](t),!0)}[VMu](t){Z7.default.write(this[sw],t,0,t.length,this[sen],(r,i)=>this[Pya](r,i))}[Pya](t,r){t?this[wya](t):(this[sen]!==void 0&&typeof r=="number"&&(this[sen]+=r),this[Ykt].length?this[zol]():(this[swn]=!1,this[Dno]&&!this[Rol]?(this[Rol]=!0,this[vHt](),this.emit("finish")):this[LMu]&&(this[LMu]=!1,this.emit("drain"))))}[zol](){if(this[Ykt].length===0)this[Dno]&&this[Pya](null,0);else if(this[Ykt].length===1)this[VMu](this[Ykt].pop());else{let t=this[Ykt];this[Ykt]=[],pLI(this[sw],t,this[sen],(r,i)=>this[Pya](r,i))}}[vHt](){if(this[cen]&&typeof this[sw]=="number"){let t=this[sw];this[sw]=void 0,Z7.default.close(t,r=>r?this.emit("error",r):this.emit("close"))}}},Sya=class extends f8i{[len](){let t;if(this[WMu]&&this[l8i]==="r+")try{t=Z7.default.openSync(this[bHt],this[l8i],this[Bno])}catch(r){if(r?.code==="ENOENT")return this[l8i]="w",this[len]();throw r}else t=Z7.default.openSync(this[bHt],this[l8i],this[Bno]);this[Eya](null,t)}[vHt](){if(this[cen]&&typeof this[sw]=="number"){let t=this[sw];this[sw]=void 0,Z7.default.closeSync(t),this.emit("close")}}[VMu](t){let r=!0;try{this[Pya](null,Z7.default.writeSync(this[sw],t,0,t.length,this[sen])),r=!1}finally{if(r)try{this[vHt]()}catch{}}}};var gul=ce(require("path"),1);var gwn=ce(require("fs"),1),cDu=require("path");var hLI=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),CN_=e=>!!e.sync&&!!e.file,qN_=e=>!e.sync&&!!e.file,TN_=e=>!!e.sync&&!e.file,RN_=e=>!e.sync&&!e.file;var zN_=e=>!!e.file;var _LI=e=>{let t=hLI.get(e);return t||e},Cno=(e={})=>{if(!e)return{};let t={};for(let[r,i]of Object.entries(e)){let n=_LI(r);t[n]=i}return t.chmod===void 0&&t.noChmod===!1&&(t.chmod=!0),delete t.noChmod,t};var Xkt=(e,t,r,i,n)=>Object.assign((a=[],o,c)=>{Array.isArray(a)&&(o=a,a={}),typeof o=="function"&&(c=o,o=void 0),o?o=Array.from(o):o=[];let d=Cno(a);if(n?.(d,o),CN_(d)){if(typeof c=="function")throw new TypeError("callback not supported for sync tar functions");return e(d,o)}else if(qN_(d)){let s=t(d,o),u=c||void 0;return u?s.then(()=>u(),u):s}else if(TN_(d)){if(typeof c=="function")throw new TypeError("callback not supported for sync tar functions");return r(d,o)}else if(RN_(d)){if(typeof c=="function")throw new TypeError("callback only supported with file option");return i(d,o)}else throw new Error("impossible options??")},{syncFile:e,asyncFile:t,syncNoFile:r,asyncNoFile:i,validate:n});var ZN_=require("events");var HMu=ce(require("assert"),1),fen=require("buffer");var FN_=ce(require("zlib"),1);var NN_=ce(require("zlib"),1),yLI=NN_.default.constants||{ZLIB_VERNUM:4736},bIe=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},yLI));var bLI=fen.Buffer.concat,QN_=Object.getOwnPropertyDescriptor(fen.Buffer,"concat"),vLI=e=>e,Wol=QN_?.writable===!0||QN_?.set!==void 0?e=>{fen.Buffer.concat=e?vLI:bLI}:e=>{},fwn=Symbol("_superWrite"),Mya=class extends Error{code;errno;constructor(t,r){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,r??this.constructor)}get name(){return"ZlibError"}},xol=Symbol("flushFlag"),qno=class extends bN{#e=!1;#t=!1;#r;#i;#n;#a;#o;get sawError(){return this.#e}get handle(){return this.#a}get flushFlag(){return this.#r}constructor(t,r){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#i=t.finishFlush??0,this.#n=t.fullFlushFlag??0,typeof FN_[r]!="function")throw new TypeError("Compression method not supported: "+r);try{this.#a=new FN_[r](t)}catch(i){throw new Mya(i,this.constructor)}this.#o=i=>{this.#e||(this.#e=!0,this.close(),this.emit("error",i))},this.#a?.on("error",i=>this.#o(new Mya(i))),this.once("end",()=>this.close)}close(){this.#a&&(this.#a.close(),this.#a=void 0,this.emit("close"))}reset(){if(!this.#e)return(0,HMu.default)(this.#a,"zlib binding closed"),this.#a.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#n),this.write(Object.assign(fen.Buffer.alloc(0),{[xol]:t})))}end(t,r,i){return typeof t=="function"&&(i=t,r=void 0,t=void 0),typeof r=="function"&&(i=r,r=void 0),t&&(r?this.write(t,r):this.write(t)),this.flush(this.#i),this.#t=!0,super.end(i)}get ended(){return this.#t}[fwn](t){return super.write(t)}write(t,r,i){if(typeof r=="function"&&(i=r,r="utf8"),typeof t=="string"&&(t=fen.Buffer.from(t,r)),this.#e)return;(0,HMu.default)(this.#a,"zlib binding closed");let n=this.#a._handle,a=n.close;n.close=()=>{};let o=this.#a.close;this.#a.close=()=>{},Wol(!0);let c;try{let s=typeof t[xol]=="number"?t[xol]:this.#r;c=this.#a._processChunk(t,s),Wol(!1)}catch(s){Wol(!1),this.#o(new Mya(s,this.write))}finally{this.#a&&(this.#a._handle=n,n.close=a,this.#a.close=o,this.#a.removeAllListeners("error"))}this.#a&&this.#a.on("error",s=>this.#o(new Mya(s,this.write)));let d;if(c)if(Array.isArray(c)&&c.length>0){let s=c[0];d=this[fwn](fen.Buffer.from(s));for(let u=1;u<c.length;u++)d=this[fwn](c[u])}else d=this[fwn](fen.Buffer.from(c));return i&&i(),d}},GMu=class extends qno{#e;#t;constructor(t,r){t=t||{},t.flush=t.flush||bIe.Z_NO_FLUSH,t.finishFlush=t.finishFlush||bIe.Z_FINISH,t.fullFlushFlag=bIe.Z_FULL_FLUSH,super(t,r),this.#e=t.level,this.#t=t.strategy}params(t,r){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#t!==r){this.flush(bIe.Z_SYNC_FLUSH),(0,HMu.default)(this.handle,"zlib binding closed");let i=this.handle.flush;this.handle.flush=(n,a)=>{typeof n=="function"&&(a=n,n=this.flushFlag),this.flush(n),a?.()};try{this.handle.params(t,r)}finally{this.handle.flush=i}this.handle&&(this.#e=t,this.#t=r)}}}};var KMu=class extends GMu{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[fwn](t){return this.#e?(this.#e=!1,t[9]=255,super[fwn](t)):super[fwn](t)}};var $Mu=class extends GMu{constructor(t){super(t,"Unzip")}},JMu=class extends qno{constructor(t,r){t=t||{},t.flush=t.flush||bIe.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||bIe.BROTLI_OPERATION_FINISH,t.fullFlushFlag=bIe.BROTLI_OPERATION_FLUSH,super(t,r)}},YMu=class extends JMu{constructor(t){super(t,"BrotliCompress")}},XMu=class extends JMu{constructor(t){super(t,"BrotliDecompress")}},ZMu=class extends qno{constructor(t,r){t=t||{},t.flush=t.flush||bIe.ZSTD_e_continue,t.finishFlush=t.finishFlush||bIe.ZSTD_e_end,t.fullFlushFlag=bIe.ZSTD_e_flush,super(t,r)}},kMu=class extends ZMu{constructor(t){super(t,"ZstdCompress")}},eDu=class extends ZMu{constructor(t){super(t,"ZstdDecompress")}};var hwn=require("path");var UN_=(e,t)=>{if(Number.isSafeInteger(e))e<0?mLI(e,t):OLI(e,t);else throw Error("cannot encode number outside of javascript safe integer range");return t},OLI=(e,t)=>{t[0]=128;for(var r=t.length;r>1;r--)t[r-1]=e&255,e=Math.floor(e/256)},mLI=(e,t)=>{t[0]=255;var r=!1;e=e*-1;for(var i=t.length;i>1;i--){var n=e&255;e=Math.floor(e/256),r?t[i-1]=VN_(n):n===0?t[i-1]=0:(r=!0,t[i-1]=WN_(n))}},LN_=e=>{let t=e[0],r=t===128?PLI(e.subarray(1,e.length)):t===255?ALI(e):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},ALI=e=>{for(var t=e.length,r=0,i=!1,n=t-1;n>-1;n--){var a=Number(e[n]),o;i?o=VN_(a):a===0?o=a:(i=!0,o=WN_(a)),o!==0&&(r-=o*Math.pow(256,t-n-1))}return r},PLI=e=>{for(var t=e.length,r=0,i=t-1;i>-1;i--){var n=Number(e[i]);n!==0&&(r+=n*Math.pow(256,t-i-1))}return r},VN_=e=>(255^e)&255,WN_=e=>(255^e)+1&255;var tDu=e=>rDu.has(e);var rDu=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),xN_=new Map(Array.from(rDu).map(e=>[e[1],e[0]]));var _Ae=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,r=0,i,n){Buffer.isBuffer(t)?this.decode(t,r||0,i,n):t&&this.#t(t)}decode(t,r,i,n){if(r||(r=0),!t||!(t.length>=r+512))throw new Error("need 512 bytes for header");this.path=i?.path??dwn(t,r,100),this.mode=i?.mode??n?.mode??den(t,r+100,8),this.uid=i?.uid??n?.uid??den(t,r+108,8),this.gid=i?.gid??n?.gid??den(t,r+116,8),this.size=i?.size??n?.size??den(t,r+124,12),this.mtime=i?.mtime??n?.mtime??Hol(t,r+136,12),this.cksum=den(t,r+148,12),n&&this.#t(n,!0),i&&this.#t(i);let a=dwn(t,r+156,1);if(tDu(a)&&(this.#e=a||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=dwn(t,r+157,100),t.subarray(r+257,r+265).toString()==="ustar\x0000")if(this.uname=i?.uname??n?.uname??dwn(t,r+265,32),this.gname=i?.gname??n?.gname??dwn(t,r+297,32),this.devmaj=i?.devmaj??n?.devmaj??den(t,r+329,8)??0,this.devmin=i?.devmin??n?.devmin??den(t,r+337,8)??0,t[r+475]!==0){let c=dwn(t,r+345,155);this.path=c+"/"+this.path}else{let c=dwn(t,r+345,130);c&&(this.path=c+"/"+this.path),this.atime=i?.atime??n?.atime??Hol(t,r+476,12),this.ctime=i?.ctime??n?.ctime??Hol(t,r+488,12)}let o=256;for(let c=r;c<r+148;c++)o+=t[c];for(let c=r+156;c<r+512;c++)o+=t[c];this.cksumValid=o===this.cksum,this.cksum===void 0&&o===256&&(this.nullBlock=!0)}#t(t,r=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,n])=>!(n==null||i==="path"&&r||i==="linkpath"&&r||i==="global"))))}encode(t,r=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=r+512))throw new Error("need 512 bytes for header");let i=this.ctime||this.atime?130:155,n=wLI(this.path||"",i),a=n[0],o=n[1];this.needPax=!!n[2],this.needPax=pwn(t,r,100,a)||this.needPax,this.needPax=pen(t,r+100,8,this.mode)||this.needPax,this.needPax=pen(t,r+108,8,this.uid)||this.needPax,this.needPax=pen(t,r+116,8,this.gid)||this.needPax,this.needPax=pen(t,r+124,12,this.size)||this.needPax,this.needPax=Gol(t,r+136,12,this.mtime)||this.needPax,t[r+156]=this.#e.charCodeAt(0),this.needPax=pwn(t,r+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",r+257,8),this.needPax=pwn(t,r+265,32,this.uname)||this.needPax,this.needPax=pwn(t,r+297,32,this.gname)||this.needPax,this.needPax=pen(t,r+329,8,this.devmaj)||this.needPax,this.needPax=pen(t,r+337,8,this.devmin)||this.needPax,this.needPax=pwn(t,r+345,i,o)||this.needPax,t[r+475]!==0?this.needPax=pwn(t,r+345,155,o)||this.needPax:(this.needPax=pwn(t,r+345,130,o)||this.needPax,this.needPax=Gol(t,r+476,12,this.atime)||this.needPax,this.needPax=Gol(t,r+488,12,this.ctime)||this.needPax);let c=256;for(let d=r;d<r+148;d++)c+=t[d];for(let d=r+156;d<r+512;d++)c+=t[d];return this.cksum=c,pen(t,r+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:rDu.get(this.#e)}get typeKey(){return this.#e}set type(t){let r=String(xN_.get(t));if(tDu(r)||r==="Unsupported")this.#e=r;else if(tDu(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},wLI=(e,t)=>{let i=e,n="",a,o=hwn.posix.parse(e).root||".";if(Buffer.byteLength(i)<100)a=[i,n,!1];else{n=hwn.posix.dirname(i),i=hwn.posix.basename(i);do Buffer.byteLength(i)<=100&&Buffer.byteLength(n)<=t?a=[i,n,!1]:Buffer.byteLength(i)>100&&Buffer.byteLength(n)<=t?a=[i.slice(0,99),n,!0]:(i=hwn.posix.join(hwn.posix.basename(n),i),n=hwn.posix.dirname(n));while(n!==o&&a===void 0);a||(a=[e.slice(0,99),"",!0])}return a},dwn=(e,t,r)=>e.subarray(t,t+r).toString("utf8").replace(/\0.*/,""),Hol=(e,t,r)=>ELI(den(e,t,r)),ELI=e=>e===void 0?void 0:new Date(e*1e3),den=(e,t,r)=>Number(e[t])&128?LN_(e.subarray(t,t+r)):MLI(e,t,r),SLI=e=>isNaN(e)?void 0:e,MLI=(e,t,r)=>SLI(parseInt(e.subarray(t,t+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),DLI={12:8589934591,8:2097151},pen=(e,t,r,i)=>i===void 0?!1:i>DLI[r]||i<0?(UN_(i,e.subarray(t,t+r)),!0):(ILI(e,t,r,i),!1),ILI=(e,t,r,i)=>e.write(BLI(i,r),t,r,"ascii"),BLI=(e,t)=>CLI(Math.floor(e).toString(8),t),CLI=(e,t)=>(e.length===t-1?e:new Array(t-e.length-1).join("0")+e+" ")+"\0",Gol=(e,t,r,i)=>i===void 0?!1:pen(e,t,r,i.getTime()/1e3),qLI=new Array(156).join("\0"),pwn=(e,t,r,i)=>i===void 0?!1:(e.write(i+qLI,t,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r);var GN_=require("path");var hen=class e{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(t,r=!1){this.atime=t.atime,this.charset=t.charset,this.comment=t.comment,this.ctime=t.ctime,this.dev=t.dev,this.gid=t.gid,this.global=r,this.gname=t.gname,this.ino=t.ino,this.linkpath=t.linkpath,this.mtime=t.mtime,this.nlink=t.nlink,this.path=t.path,this.size=t.size,this.uid=t.uid,this.uname=t.uname}encode(){let t=this.encodeBody();if(t==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(t),i=512*Math.ceil(1+r/512),n=Buffer.allocUnsafe(i);for(let a=0;a<512;a++)n[a]=0;new _Ae({path:("PaxHeader/"+(0,GN_.basename)(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(n),n.write(t,512,r,"utf8");for(let a=r+512;a<n.length;a++)n[a]=0;return n}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(t){if(this[t]===void 0)return"";let r=this[t],i=r instanceof Date?r.getTime()/1e3:r,n=" "+(t==="dev"||t==="ino"||t==="nlink"?"SCHILY.":"")+t+"="+i+`
|
|
1599
1599
|
`,a=Buffer.byteLength(n),o=Math.floor(Math.log(a)/Math.log(10))+1;return a+o>=Math.pow(10,o)&&(o+=1),o+a+n}static parse(t,r,i=!1){return new e(TLI(RLI(t),r),i)}},TLI=(e,t)=>t?Object.assign({},t,e):e,RLI=e=>e.replace(/\n$/,"").split(`
|
|
1600
|
-
`).reduce(zLI,Object.create(null)),zLI=(e,t)=>{let r=parseInt(t,10);if(r!==Buffer.byteLength(t)+1)return e;t=t.slice((r+" ").length);let i=t.split("="),n=i.shift();if(!n)return e;let a=n.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),o=i.join("=");return e[a]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(a)?new Date(Number(o)*1e3):/^[0-9]+$/.test(o)?+o:o,e};var NLI=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,F_=NLI!=="win32"?e=>e:e=>e&&e.replace(/\\/g,"/");var Dya=class extends bN{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,r,i){switch(super({}),this.pause(),this.extended=r,this.globalExtended=i,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=F_(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?F_(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,r&&this.#e(r),i&&this.#e(i,!0)}write(t){let r=t.length;if(r>this.blockRemain)throw new Error("writing more to entry than is appropriate");let i=this.remain,n=this.blockRemain;return this.remain=Math.max(0,i-r),this.blockRemain=Math.max(0,n-r),this.ignore?!0:i>=r?super.write(t):super.write(t.subarray(0,i))}#e(t,r=!1){t.path&&(t.path=F_(t.path)),t.linkpath&&(t.linkpath=F_(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,n])=>!(n==null||i==="path"&&r))))}};var _wn=(e,t,r,i={})=>{e.file&&(i.file=e.file),e.cwd&&(i.cwd=e.cwd),i.code=r instanceof Error&&r.code||t,i.tarCode=t,!e.strict&&i.recoverable!==!1?(r instanceof Error&&(i=Object.assign(r,i),r=r.message),e.emit("warn",t,r,i)):r instanceof Error?e.emit("error",Object.assign(r,i)):e.emit("error",Object.assign(new Error(`${t}: ${r}`),i))};var FLI=1024*1024,Xol=Buffer.from([31,139]),Zol=Buffer.from([40,181,47,253]),QLI=Math.max(Xol.length,Zol.length),vIe=Symbol("state"),ywn=Symbol("writeEntry"),d8i=Symbol("readEntry"),Kol=Symbol("nextEntry"),KN_=Symbol("processEntry"),Zkt=Symbol("extendedHeader"),Tno=Symbol("globalExtendedHeader"),_en=Symbol("meta"),$N_=Symbol("emitMeta"),MS=Symbol("buffer"),p8i=Symbol("queue"),yen=Symbol("ended"),$ol=Symbol("emittedEnd"),bwn=Symbol("emit"),AR=Symbol("unzip"),iDu=Symbol("consumeChunk"),nDu=Symbol("consumeChunkSub"),Jol=Symbol("consumeBody"),JN_=Symbol("consumeMeta"),YN_=Symbol("consumeHeader"),Rno=Symbol("consuming"),Yol=Symbol("bufferConcat"),aDu=Symbol("maybeEnd"),Iya=Symbol("writing"),ben=Symbol("aborted"),oDu=Symbol("onDone"),vwn=Symbol("sawValidEntry"),uDu=Symbol("sawNullBlock"),sDu=Symbol("sawEOF"),XN_=Symbol("closeStream"),ULI=()=>!0,h8i=class extends ZN_.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[p8i]=[];[MS];[d8i];[ywn];[vIe]="begin";[_en]="";[Zkt];[Tno];[yen]=!1;[AR];[ben]=!1;[vwn];[uDu]=!1;[sDu]=!1;[Iya]=!1;[Rno]=!1;[$ol]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(oDu,()=>{(this[vIe]==="begin"||this[vwn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(oDu,t.ondone):this.on(oDu,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||FLI,this.filter=typeof t.filter=="function"?t.filter:ULI;let r=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:r?void 0:!1;let i=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:i?!0:void 0,this.on("end",()=>this[XN_]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,r,i={}){_wn(this,t,r,i)}[YN_](t,r){this[vwn]===void 0&&(this[vwn]=!1);let i;try{i=new _Ae(t,r,this[Zkt],this[Tno])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(i.nullBlock)this[uDu]?(this[sDu]=!0,this[vIe]==="begin"&&(this[vIe]="header"),this[bwn]("eof")):(this[uDu]=!0,this[bwn]("nullBlock"));else if(this[uDu]=!1,!i.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:i});else if(!i.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:i});else{let n=i.type;if(/^(Symbolic)?Link$/.test(n)&&!i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:i});else if(!/^(Symbolic)?Link$/.test(n)&&!/^(Global)?ExtendedHeader$/.test(n)&&i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:i});else{let a=this[ywn]=new Dya(i,this[Zkt],this[Tno]);if(!this[vwn])if(a.remain){let o=()=>{a.invalid||(this[vwn]=!0)};a.on("end",o)}else this[vwn]=!0;a.meta?a.size>this.maxMetaEntrySize?(a.ignore=!0,this[bwn]("ignoredEntry",a),this[vIe]="ignore",a.resume()):a.size>0&&(this[_en]="",a.on("data",o=>this[_en]+=o),this[vIe]="meta"):(this[Zkt]=void 0,a.ignore=a.ignore||!this.filter(a.path,a),a.ignore?(this[bwn]("ignoredEntry",a),this[vIe]=a.remain?"ignore":"header",a.resume()):(a.remain?this[vIe]="body":(this[vIe]="header",a.end()),this[d8i]?this[p8i].push(a):(this[p8i].push(a),this[Kol]())))}}}[XN_](){queueMicrotask(()=>this.emit("close"))}[KN_](t){let r=!0;if(!t)this[d8i]=void 0,r=!1;else if(Array.isArray(t)){let[i,...n]=t;this.emit(i,...n)}else this[d8i]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Kol]()),r=!1);return r}[Kol](){do;while(this[KN_](this[p8i].shift()));if(!this[p8i].length){let t=this[d8i];!t||t.flowing||t.size===t.remain?this[Iya]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Jol](t,r){let i=this[ywn];if(!i)throw new Error("attempt to consume body without entry??");let n=i.blockRemain??0,a=n>=t.length&&r===0?t:t.subarray(r,r+n);return i.write(a),i.blockRemain||(this[vIe]="header",this[ywn]=void 0,i.end()),a.length}[JN_](t,r){let i=this[ywn],n=this[Jol](t,r);return!this[ywn]&&i&&this[$N_](i),n}[bwn](t,r,i){!this[p8i].length&&!this[d8i]?this.emit(t,r,i):this[p8i].push([t,r,i])}[$N_](t){switch(this[bwn]("meta",this[_en]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Zkt]=hen.parse(this[_en],this[Zkt],!1);break;case"GlobalExtendedHeader":this[Tno]=hen.parse(this[_en],this[Tno],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let r=this[Zkt]??Object.create(null);this[Zkt]=r,r.path=this[_en].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let r=this[Zkt]||Object.create(null);this[Zkt]=r,r.linkpath=this[_en].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[ben]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,r,i){if(typeof r=="function"&&(i=r,r=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof r=="string"?r:"utf8")),this[ben])return i?.(),!1;if((this[AR]===void 0||this.brotli===void 0&&this[AR]===!1)&&t){if(this[MS]&&(t=Buffer.concat([this[MS],t]),this[MS]=void 0),t.length<QLI)return this[MS]=t,i?.(),!0;for(let d=0;this[AR]===void 0&&d<Xol.length;d++)t[d]!==Xol[d]&&(this[AR]=!1);let o=!1;if(this[AR]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Zol.length;d++)if(t[d]!==Zol[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[AR]===!1&&c)if(t.length<512)if(this[yen])this.brotli=!0;else return this[MS]=t,i?.(),!0;else try{new _Ae(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[AR]===void 0||this[AR]===!1&&(this.brotli||o)){let d=this[yen];this[yen]=!1,this[AR]=this[AR]===void 0?new $Mu({}):o?new eDu({}):new XMu({}),this[AR].on("data",u=>this[iDu](u)),this[AR].on("error",u=>this.abort(u)),this[AR].on("end",()=>{this[yen]=!0,this[iDu]()}),this[Iya]=!0;let s=!!this[AR][d?"end":"write"](t);return this[Iya]=!1,i?.(),s}}this[Iya]=!0,this[AR]?this[AR].write(t):this[iDu](t),this[Iya]=!1;let a=this[p8i].length?!1:this[d8i]?this[d8i].flowing:!0;return!a&&!this[p8i].length&&this[d8i]?.once("drain",()=>this.emit("drain")),i?.(),a}[Yol](t){t&&!this[ben]&&(this[MS]=this[MS]?Buffer.concat([this[MS],t]):t)}[aDu](){if(this[yen]&&!this[$ol]&&!this[ben]&&!this[Rno]){this[$ol]=!0;let t=this[ywn];if(t&&t.blockRemain){let r=this[MS]?this[MS].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${r} available)`,{entry:t}),this[MS]&&t.write(this[MS]),t.end()}this[bwn](oDu)}}[iDu](t){if(this[Rno]&&t)this[Yol](t);else if(!t&&!this[MS])this[aDu]();else if(t){if(this[Rno]=!0,this[MS]){this[Yol](t);let r=this[MS];this[MS]=void 0,this[nDu](r)}else this[nDu](t);for(;this[MS]&&this[MS]?.length>=512&&!this[ben]&&!this[sDu];){let r=this[MS];this[MS]=void 0,this[nDu](r)}this[Rno]=!1}(!this[MS]||this[yen])&&this[aDu]()}[nDu](t){let r=0,i=t.length;for(;r+512<=i&&!this[ben]&&!this[sDu];)switch(this[vIe]){case"begin":case"header":this[YN_](t,r),r+=512;break;case"ignore":case"body":r+=this[Jol](t,r);break;case"meta":r+=this[JN_](t,r);break;default:throw new Error("invalid state: "+this[vIe])}r<i&&(this[MS]?this[MS]=Buffer.concat([t.subarray(r),this[MS]]):this[MS]=t.subarray(r))}end(t,r,i){return typeof t=="function"&&(i=t,r=void 0,t=void 0),typeof r=="function"&&(i=r,r=void 0),typeof t=="string"&&(t=Buffer.from(t,r)),i&&this.once("finish",i),this[ben]||(this[AR]?(t&&this[AR].write(t),this[AR].end()):(this[yen]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[aDu]())),this}};var ven=e=>{let t=e.length-1,r=-1;for(;t>-1&&e.charAt(t)==="/";)r=t,t--;return r===-1?e:e.slice(0,r)};var LLI=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},kol=(e,t)=>{let r=new Map(t.map(a=>[ven(a),!0])),i=e.filter,n=(a,o="")=>{let c=o||(0,cDu.parse)(a).root||".",d;if(a===c)d=!1;else{let s=r.get(a);s!==void 0?d=s:d=n((0,cDu.dirname)(a),c)}return r.set(a,d),d};e.filter=i?(a,o)=>i(a,o)&&n(ven(a)):a=>n(ven(a))},VLI=e=>{let t=new h8i(e),r=e.file,i;try{i=gwn.default.openSync(r,"r");let n=gwn.default.fstatSync(i),a=e.maxReadSize||16*1024*1024;if(n.size<a){let o=Buffer.allocUnsafe(n.size),c=gwn.default.readSync(i,o,0,n.size,0);t.end(c===o.byteLength?o:o.subarray(0,c))}else{let o=0,c=Buffer.allocUnsafe(a);for(;o<n.size;){let d=gwn.default.readSync(i,c,0,a,o);if(d===0)break;o+=d,t.write(c.subarray(0,d))}t.end()}}finally{if(typeof i=="number")try{gwn.default.closeSync(i)}catch{}}},WLI=(e,t)=>{let r=new h8i(e),i=e.maxReadSize||16*1024*1024,n=e.file;return new Promise((o,c)=>{r.on("error",c),r.on("end",o),gwn.default.stat(n,(d,s)=>{if(d)c(d);else{let u=new lwn(n,{readSize:i,size:s.size});u.on("error",c),u.pipe(r)}})})},Own=Xkt(VLI,WLI,e=>new h8i(e),e=>new h8i(e),(e,t)=>{t?.length&&kol(e,t),e.noResume||LLI(e)});var Vno=ce(require("fs"),1);var gHt=ce(require("fs"),1);var nul=ce(require("path"),1);var eul=(e,t,r)=>(e&=4095,r&&(e=(e|384)&-19),t&&(e&256&&(e|=64),e&32&&(e|=8),e&4&&(e|=1)),e);var eF_=require("path"),{isAbsolute:xLI,parse:kN_}=eF_.win32,zno=e=>{let t="",r=kN_(e);for(;xLI(e)||r.root;){let i=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(i.length),t+=i,r=kN_(e)}return[t,e]};var lDu=["|","<",">","?",":"],tul=lDu.map(e=>String.fromCharCode(61440+e.charCodeAt(0))),HLI=new Map(lDu.map((e,t)=>[e,tul[t]])),GLI=new Map(tul.map((e,t)=>[e,lDu[t]])),rul=e=>lDu.reduce((t,r)=>t.split(r).join(HLI.get(r)),e),tF_=e=>tul.reduce((t,r)=>t.split(r).join(GLI.get(r)),e);var uF_=(e,t)=>t?(e=F_(e).replace(/^\.(\/|$)/,""),ven(t)+"/"+e):F_(e),KLI=16*1024*1024,iF_=Symbol("process"),nF_=Symbol("file"),aF_=Symbol("directory"),aul=Symbol("symlink"),oF_=Symbol("hardlink"),Nno=Symbol("header"),fDu=Symbol("read"),oul=Symbol("lstat"),dDu=Symbol("onlstat"),uul=Symbol("onread"),sul=Symbol("onreadlink"),cul=Symbol("openfile"),lul=Symbol("onopenfile"),gen=Symbol("close"),pDu=Symbol("mode"),ful=Symbol("awaitDrain"),iul=Symbol("ondrain"),kkt=Symbol("prefix"),Fno=class extends bN{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,r={}){let i=Cno(r);super(),this.path=F_(t),this.portable=!!i.portable,this.maxReadSize=i.maxReadSize||KLI,this.linkCache=i.linkCache||new Map,this.statCache=i.statCache||new Map,this.preservePaths=!!i.preservePaths,this.cwd=F_(i.cwd||process.cwd()),this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.mtime=i.mtime,this.prefix=i.prefix?F_(i.prefix):void 0,this.onWriteEntry=i.onWriteEntry,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let n=!1;if(!this.preservePaths){let[o,c]=zno(this.path);o&&typeof c=="string"&&(this.path=c,n=o)}this.win32=!!i.win32||process.platform==="win32",this.win32&&(this.path=tF_(this.path.replace(/\\/g,"/")),t=t.replace(/\\/g,"/")),this.absolute=F_(i.absolute||nul.default.resolve(this.cwd,t)),this.path===""&&(this.path="./"),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path});let a=this.statCache.get(this.absolute);a?this[dDu](a):this[oul]()}warn(t,r,i={}){return _wn(this,t,r,i)}emit(t,...r){return t==="error"&&(this.#e=!0),super.emit(t,...r)}[oul](){gHt.default.lstat(this.absolute,(t,r)=>{if(t)return this.emit("error",t);this[dDu](r)})}[dDu](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=$LI(t),this.emit("stat",t),this[iF_]()}[iF_](){switch(this.type){case"File":return this[nF_]();case"Directory":return this[aF_]();case"SymbolicLink":return this[aul]();default:return this.end()}}[pDu](t){return eul(t,this.type==="Directory",this.portable)}[kkt](t){return uF_(t,this.prefix)}[Nno](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new _Ae({path:this[kkt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[kkt](this.linkpath):this.linkpath,mode:this[pDu](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new hen({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[kkt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[kkt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[aF_](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Nno](),this.end()}[aul](){gHt.default.readlink(this.absolute,(t,r)=>{if(t)return this.emit("error",t);this[sul](r)})}[sul](t){this.linkpath=F_(t),this[Nno](),this.end()}[oF_](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=F_(nul.default.relative(this.cwd,t)),this.stat.size=0,this[Nno](),this.end()}[nF_](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,r=this.linkCache.get(t);if(r?.indexOf(this.cwd)===0)return this[oF_](r);this.linkCache.set(t,this.absolute)}if(this[Nno](),this.stat.size===0)return this.end();this[cul]()}[cul](){gHt.default.open(this.absolute,"r",(t,r)=>{if(t)return this.emit("error",t);this[lul](r)})}[lul](t){if(this.fd=t,this.#e)return this[gen]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let r=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(r),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[fDu]()}[fDu](){let{fd:t,buf:r,offset:i,length:n,pos:a}=this;if(t===void 0||r===void 0)throw new Error("cannot read file without first opening");gHt.default.read(t,r,i,n,a,(o,c)=>{if(o)return this[gen](()=>this.emit("error",o));this[uul](c)})}[gen](t=()=>{}){this.fd!==void 0&&gHt.default.close(this.fd,t)}[uul](t){if(t<=0&&this.remain>0){let n=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[gen](()=>this.emit("error",n))}if(t>this.remain){let n=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[gen](()=>this.emit("error",n))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let n=t;n<this.length&&t<this.blockRemain;n++)this.buf[n+this.offset]=0,t++,this.remain++;let r=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(r)?this[iul]():this[ful](()=>this[iul]())}[ful](t){this.once("drain",t)}write(t,r,i){if(typeof r=="function"&&(i=r,r=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof r=="string"?r:"utf8")),this.blockRemain<t.length){let n=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",n)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,i)}[iul](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[gen](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[fDu]()}},hDu=class extends Fno{sync=!0;[oul](){this[dDu](gHt.default.lstatSync(this.absolute))}[aul](){this[sul](gHt.default.readlinkSync(this.absolute))}[cul](){this[lul](gHt.default.openSync(this.absolute,"r"))}[fDu](){let t=!0;try{let{fd:r,buf:i,offset:n,length:a,pos:o}=this;if(r===void 0||i===void 0)throw new Error("fd and buf must be set in READ method");let c=gHt.default.readSync(r,i,n,a,o);this[uul](c),t=!1}finally{if(t)try{this[gen](()=>{})}catch{}}}[ful](t){t()}[gen](t=()=>{}){this.fd!==void 0&&gHt.default.closeSync(this.fd),t()}},_Du=class extends bN{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,r,i={}){return _wn(this,t,r,i)}constructor(t,r={}){let i=Cno(r);super(),this.preservePaths=!!i.preservePaths,this.portable=!!i.portable,this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.onWriteEntry=i.onWriteEntry,this.readEntry=t;let{type:n}=t;if(n==="Unsupported")throw new Error("writing entry that should be ignored");this.type=n,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=i.prefix,this.path=F_(t.path),this.mode=t.mode!==void 0?this[pDu](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:i.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?F_(t.linkpath):void 0,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let a=!1;if(!this.preservePaths){let[c,d]=zno(this.path);c&&typeof d=="string"&&(this.path=d,a=c)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new _Ae({path:this[kkt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[kkt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),a&&this.warn("TAR_ENTRY_INFO",`stripping ${a} from absolute path`,{entry:this,path:a+this.path}),this.header.encode()&&!this.noPax&&super.write(new hen({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[kkt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[kkt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),t.pipe(this)}[kkt](t){return uF_(t,this.prefix)}[pDu](t){return eul(t,this.type==="Directory",this.portable)}write(t,r,i){typeof r=="function"&&(i=r,r=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof r=="string"?r:"utf8"));let n=t.length;if(n>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=n,super.write(t,i)}end(t,r,i){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(i=t,r=void 0,t=void 0),typeof r=="function"&&(i=r,r=void 0),typeof t=="string"&&(t=Buffer.from(t,r??"utf8")),i&&this.once("finish",i),t?super.end(t,i):super.end(i),this}},$LI=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported";var yDu=class e{tail;head;length=0;static create(t=[]){return new e(t)}constructor(t=[]){for(let r of t)this.push(r)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw new Error("removing node which does not belong to this list");let r=t.next,i=t.prev;return r&&(r.prev=i),i&&(i.next=r),t===this.head&&(this.head=r),t===this.tail&&(this.tail=i),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,r}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let r=this.head;t.list=this,t.next=r,r&&(r.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let r=this.tail;t.list=this,t.prev=r,r&&(r.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let r=0,i=t.length;r<i;r++)YLI(this,t[r]);return this.length}unshift(...t){for(var r=0,i=t.length;r<i;r++)XLI(this,t[r]);return this.length}pop(){if(!this.tail)return;let t=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,t}shift(){if(!this.head)return;let t=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,t}forEach(t,r){r=r||this;for(let i=this.head,n=0;i;n++)t.call(r,i.value,n,this),i=i.next}forEachReverse(t,r){r=r||this;for(let i=this.tail,n=this.length-1;i;n--)t.call(r,i.value,n,this),i=i.prev}get(t){let r=0,i=this.head;for(;i&&r<t;r++)i=i.next;if(r===t&&i)return i.value}getReverse(t){let r=0,i=this.tail;for(;i&&r<t;r++)i=i.prev;if(r===t&&i)return i.value}map(t,r){r=r||this;let i=new e;for(let n=this.head;n;)i.push(t.call(r,n.value,this)),n=n.next;return i}mapReverse(t,r){r=r||this;var i=new e;for(let n=this.tail;n;)i.push(t.call(r,n.value,this)),n=n.prev;return i}reduce(t,r){let i,n=this.head;if(arguments.length>1)i=r;else if(this.head)n=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var a=0;n;a++)i=t(i,n.value,a),n=n.next;return i}reduceReverse(t,r){let i,n=this.tail;if(arguments.length>1)i=r;else if(this.tail)n=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let a=this.length-1;n;a--)i=t(i,n.value,a),n=n.prev;return i}toArray(){let t=new Array(this.length);for(let r=0,i=this.head;i;r++)t[r]=i.value,i=i.next;return t}toArrayReverse(){let t=new Array(this.length);for(let r=0,i=this.tail;i;r++)t[r]=i.value,i=i.prev;return t}slice(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let i=new e;if(r<t||r<0)return i;t<0&&(t=0),r>this.length&&(r=this.length);let n=this.head,a=0;for(a=0;n&&a<t;a++)n=n.next;for(;n&&a<r;a++,n=n.next)i.push(n.value);return i}sliceReverse(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let i=new e;if(r<t||r<0)return i;t<0&&(t=0),r>this.length&&(r=this.length);let n=this.length,a=this.tail;for(;a&&n>r;n--)a=a.prev;for(;a&&n>t;n--,a=a.prev)i.push(a.value);return i}splice(t,r=0,...i){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let n=this.head;for(let o=0;n&&o<t;o++)n=n.next;let a=[];for(let o=0;n&&o<r;o++)a.push(n.value),n=this.removeNode(n);n?n!==this.tail&&(n=n.prev):n=this.tail;for(let o of i)n=JLI(this,n,o);return a}reverse(){let t=this.head,r=this.tail;for(let i=t;i;i=i.prev){let n=i.prev;i.prev=i.next,i.next=n}return this.head=r,this.tail=t,this}};function JLI(e,t,r){let i=t,n=t?t.next:e.head,a=new Qno(r,i,n,e);return a.next===void 0&&(e.tail=a),a.prev===void 0&&(e.head=a),e.length++,a}function YLI(e,t){e.tail=new Qno(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function XLI(e,t){e.head=new Qno(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}var Qno=class{list;next;prev;value;constructor(t,r,i,n){this.list=n,this.value=t,r?(r.next=this,this.prev=r):this.prev=void 0,i?(i.prev=this,this.next=i):this.next=void 0}};var vul=ce(require("path"),1);var ADu=class{path;absolute;entry;stat;readdir;pending=!1;ignore=!1;piped=!1;constructor(t,r){this.path=t||"./",this.absolute=r}},sF_=Buffer.alloc(1024),bDu=Symbol("onStat"),Uno=Symbol("ended"),OHt=Symbol("queue"),mwn=Symbol("current"),Awn=Symbol("process"),Lno=Symbol("processing"),dul=Symbol("processJob"),mHt=Symbol("jobs"),pul=Symbol("jobDone"),vDu=Symbol("addFSEntry"),cF_=Symbol("addTarEntry"),yul=Symbol("stat"),bul=Symbol("readdir"),gDu=Symbol("onreaddir"),ODu=Symbol("pipe"),lF_=Symbol("entry"),hul=Symbol("entryOpt"),mDu=Symbol("writeEntryClass"),fF_=Symbol("write"),_ul=Symbol("ondrain"),Oen=class extends bN{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[mDu];onWriteEntry;[OHt];[mHt]=0;[Lno]=!1;[Uno]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=F_(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[mDu]=Fno,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new KMu(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new YMu(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new kMu(t.zstd)),!this.zip)throw new Error("impossible");let r=this.zip;r.on("data",i=>super.write(i)),r.on("end",()=>super.end()),r.on("drain",()=>this[_ul]()),this.on("resume",()=>r.resume())}else this.on("drain",this[_ul]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[OHt]=new yDu,this[mHt]=0,this.jobs=Number(t.jobs)||4,this[Lno]=!1,this[Uno]=!1}[fF_](t){return super.write(t)}add(t){return this.write(t),this}end(t,r,i){return typeof t=="function"&&(i=t,t=void 0),typeof r=="function"&&(i=r,r=void 0),t&&this.add(t),this[Uno]=!0,this[Awn](),i&&i(),this}write(t){if(this[Uno])throw new Error("write after end");return t instanceof Dya?this[cF_](t):this[vDu](t),this.flowing}[cF_](t){let r=F_(vul.default.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let i=new ADu(t.path,r);i.entry=new _Du(t,this[hul](i)),i.entry.on("end",()=>this[pul](i)),this[mHt]+=1,this[OHt].push(i)}this[Awn]()}[vDu](t){let r=F_(vul.default.resolve(this.cwd,t));this[OHt].push(new ADu(t,r)),this[Awn]()}[yul](t){t.pending=!0,this[mHt]+=1;let r=this.follow?"stat":"lstat";Vno.default[r](t.absolute,(i,n)=>{t.pending=!1,this[mHt]-=1,i?this.emit("error",i):this[bDu](t,n)})}[bDu](t,r){this.statCache.set(t.absolute,r),t.stat=r,this.filter(t.path,r)?r.isFile()&&r.nlink>1&&t===this[mwn]&&!this.linkCache.get(`${r.dev}:${r.ino}`)&&!this.sync&&this[dul](t):t.ignore=!0,this[Awn]()}[bul](t){t.pending=!0,this[mHt]+=1,Vno.default.readdir(t.absolute,(r,i)=>{if(t.pending=!1,this[mHt]-=1,r)return this.emit("error",r);this[gDu](t,i)})}[gDu](t,r){this.readdirCache.set(t.absolute,r),t.readdir=r,this[Awn]()}[Awn](){if(!this[Lno]){this[Lno]=!0;for(let t=this[OHt].head;t&&this[mHt]<this.jobs;t=t.next)if(this[dul](t.value),t.value.ignore){let r=t.next;this[OHt].removeNode(t),t.next=r}this[Lno]=!1,this[Uno]&&!this[OHt].length&&this[mHt]===0&&(this.zip?this.zip.end(sF_):(super.write(sF_),super.end()))}}get[mwn](){return this[OHt]&&this[OHt].head&&this[OHt].head.value}[pul](t){this[OHt].shift(),this[mHt]-=1,this[Awn]()}[dul](t){if(!t.pending){if(t.entry){t===this[mwn]&&!t.piped&&this[ODu](t);return}if(!t.stat){let r=this.statCache.get(t.absolute);r?this[bDu](t,r):this[yul](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let r=this.readdirCache.get(t.absolute);if(r?this[gDu](t,r):this[bul](t),!t.readdir)return}if(t.entry=this[lF_](t),!t.entry){t.ignore=!0;return}t===this[mwn]&&!t.piped&&this[ODu](t)}}}[hul](t){return{onwarn:(r,i,n)=>this.warn(r,i,n),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[lF_](t){this[mHt]+=1;try{return new this[mDu](t.path,this[hul](t)).on("end",()=>this[pul](t)).on("error",i=>this.emit("error",i))}catch(r){this.emit("error",r)}}[_ul](){this[mwn]&&this[mwn].entry&&this[mwn].entry.resume()}[ODu](t){t.piped=!0,t.readdir&&t.readdir.forEach(n=>{let a=t.path,o=a==="./"?"":a.replace(/\/*$/,"/");this[vDu](o+n)});let r=t.entry,i=this.zip;if(!r)throw new Error("cannot pipe without source");i?r.on("data",n=>{i.write(n)||r.pause()}):r.on("data",n=>{super.write(n)||r.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,r,i={}){_wn(this,t,r,i)}},Pwn=class extends Oen{sync=!0;constructor(t){super(t),this[mDu]=hDu}pause(){}resume(){}[yul](t){let r=this.follow?"statSync":"lstatSync";this[bDu](t,Vno.default[r](t.absolute))}[bul](t){this[gDu](t,Vno.default.readdirSync(t.absolute))}[ODu](t){let r=t.entry,i=this.zip;if(t.readdir&&t.readdir.forEach(n=>{let a=t.path,o=a==="./"?"":a.replace(/\/*$/,"/");this[vDu](o+n)}),!r)throw new Error("Cannot pipe without source");i?r.on("data",n=>{i.write(n)}):r.on("data",n=>{super[fF_](n)})}};var ZLI=(e,t)=>{let r=new Pwn(e),i=new Sya(e.file,{mode:e.mode||438});r.pipe(i),dF_(r,t)},kLI=(e,t)=>{let r=new Oen(e),i=new f8i(e.file,{mode:e.mode||438});r.pipe(i);let n=new Promise((a,o)=>{i.on("error",o),i.on("close",a),r.on("error",o)});return pF_(r,t),n},dF_=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?Own({file:gul.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>e.add(i)}):e.add(r)}),e.end()},pF_=async(e,t)=>{for(let r=0;r<t.length;r++){let i=String(t[r]);i.charAt(0)==="@"?await Own({file:gul.default.resolve(String(e.cwd),i.slice(1)),noResume:!0,onReadEntry:n=>{e.add(n)}}):e.add(i)}e.end()},e4I=(e,t)=>{let r=new Pwn(e);return dF_(r,t),r},t4I=(e,t)=>{let r=new Oen(e);return pF_(r,t),r},Oul=Xkt(ZLI,kLI,e4I,t4I,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")});var Ful=ce(require("fs"),1);var DF_=ce(require("assert"),1),Nul=require("crypto"),KA=ce(require("fs"),1),yAe=ce(require("path"),1);var mul=ce(require("fs"),1),r4I=process.env.__FAKE_PLATFORM__||process.platform,i4I=r4I==="win32",{O_CREAT:n4I,O_TRUNC:a4I,O_WRONLY:o4I}=mul.default.constants,hF_=Number(process.env.__FAKE_FS_O_FILENAME__)||mul.default.constants.UV_FS_O_FILEMAP||0,u4I=i4I&&!!hF_,s4I=512*1024,c4I=hF_|a4I|n4I|o4I,Aul=u4I?e=>e<s4I?c4I:"w":()=>"w";var Wno=ce(require("fs"),1),Bya=ce(require("path"),1),Pul=(e,t,r)=>{try{return Wno.default.lchownSync(e,t,r)}catch(i){if(i?.code!=="ENOENT")throw i}},PDu=(e,t,r,i)=>{Wno.default.lchown(e,t,r,n=>{i(n&&n?.code!=="ENOENT"?n:null)})},l4I=(e,t,r,i,n)=>{if(t.isDirectory())jul(Bya.default.resolve(e,t.name),r,i,a=>{if(a)return n(a);let o=Bya.default.resolve(e,t.name);PDu(o,r,i,n)});else{let a=Bya.default.resolve(e,t.name);PDu(a,r,i,n)}},jul=(e,t,r,i)=>{Wno.default.readdir(e,{withFileTypes:!0},(n,a)=>{if(n){if(n.code==="ENOENT")return i();if(n.code!=="ENOTDIR"&&n.code!=="ENOTSUP")return i(n)}if(n||!a.length)return PDu(e,t,r,i);let o=a.length,c=null,d=s=>{if(!c){if(s)return i(c=s);if(--o===0)return PDu(e,t,r,i)}};for(let s of a)l4I(e,s,t,r,d)})},f4I=(e,t,r,i)=>{t.isDirectory()&&wul(Bya.default.resolve(e,t.name),r,i),Pul(Bya.default.resolve(e,t.name),r,i)},wul=(e,t,r)=>{let i;try{i=Wno.default.readdirSync(e,{withFileTypes:!0})}catch(n){let a=n;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return Pul(e,t,r);throw a}for(let n of i)f4I(e,n,t,r);return Pul(e,t,r)};var h2=ce(require("fs"),1),_F_=ce(require("fs/promises"),1),Gno=ce(require("path"),1);var xno=class extends Error{path;code;syscall="chdir";constructor(t,r){super(`${r}: Cannot cd into '${t}'`),this.path=t,this.code=r}get name(){return"CwdError"}};var Hno=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,r){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=r}get name(){return"SymlinkError"}};var d4I=(e,t)=>{h2.default.stat(e,(r,i)=>{(r||!i.isDirectory())&&(r=new xno(e,r?.code||"ENOTDIR")),t(r)})},yF_=(e,t,r)=>{e=F_(e);let i=t.umask??18,n=t.mode|448,a=(n&i)!==0,o=t.uid,c=t.gid,d=typeof o=="number"&&typeof c=="number"&&(o!==t.processUid||c!==t.processGid),s=t.preserve,u=t.unlink,f=F_(t.cwd),p=(y,b)=>{y?r(y):b&&d?jul(b,o,c,v=>p(v)):a?h2.default.chmod(e,n,r):r()};if(e===f)return d4I(e,p);if(s)return _F_.default.mkdir(e,{mode:n,recursive:!0}).then(y=>p(null,y??void 0),p);let _=F_(Gno.default.relative(f,e)).split("/");Eul(f,_,n,u,f,void 0,p)},Eul=(e,t,r,i,n,a,o)=>{if(!t.length)return o(null,a);let c=t.shift(),d=F_(Gno.default.resolve(e+"/"+c));h2.default.mkdir(d,r,bF_(d,t,r,i,n,a,o))},bF_=(e,t,r,i,n,a,o)=>c=>{c?h2.default.lstat(e,(d,s)=>{if(d)d.path=d.path&&F_(d.path),o(d);else if(s.isDirectory())Eul(e,t,r,i,n,a,o);else if(i)h2.default.unlink(e,u=>{if(u)return o(u);h2.default.mkdir(e,r,bF_(e,t,r,i,n,a,o))});else{if(s.isSymbolicLink())return o(new Hno(e,e+"/"+t.join("/")));o(c)}}):(a=a||e,Eul(e,t,r,i,n,a,o))},p4I=e=>{let t=!1,r;try{t=h2.default.statSync(e).isDirectory()}catch(i){r=i?.code}finally{if(!t)throw new xno(e,r??"ENOTDIR")}},vF_=(e,t)=>{e=F_(e);let r=t.umask??18,i=t.mode|448,n=(i&r)!==0,a=t.uid,o=t.gid,c=typeof a=="number"&&typeof o=="number"&&(a!==t.processUid||o!==t.processGid),d=t.preserve,s=t.unlink,u=F_(t.cwd),f=y=>{y&&c&&wul(y,a,o),n&&h2.default.chmodSync(e,i)};if(e===u)return p4I(u),f();if(d)return f(h2.default.mkdirSync(e,{mode:i,recursive:!0})??void 0);let h=F_(Gno.default.relative(u,e)).split("/"),_;for(let y=h.shift(),b=u;y&&(b+="/"+y);y=h.shift()){b=F_(Gno.default.resolve(b));try{h2.default.mkdirSync(b,i),_=_||b}catch{let O=h2.default.lstatSync(b);if(O.isDirectory())continue;if(s){h2.default.unlinkSync(b),h2.default.mkdirSync(b,i),_=_||b;continue}else if(O.isSymbolicLink())return new Hno(b,b+"/"+h.join("/"))}}return f(_)};var Mul=require("path");var Sul=Object.create(null),gF_=1e4,Cya=new Set,OF_=e=>{Cya.has(e)?Cya.delete(e):Sul[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Cya.add(e);let t=Sul[e],r=Cya.size-gF_;if(r>gF_/10){for(let i of Cya)if(Cya.delete(i),delete Sul[i],--r<=0)break}return t};var h4I=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,_4I=h4I==="win32",y4I=e=>e.split("/").slice(0,-1).reduce((r,i)=>{let n=r[r.length-1];return n!==void 0&&(i=(0,Mul.join)(n,i)),r.push(i||"/"),r},[]),jDu=class{#e=new Map;#t=new Map;#r=new Set;reserve(t,r){t=_4I?["win32 parallelization disabled"]:t.map(n=>ven((0,Mul.join)(OF_(n))));let i=new Set(t.map(n=>y4I(n)).reduce((n,a)=>n.concat(a)));this.#t.set(r,{dirs:i,paths:t});for(let n of t){let a=this.#e.get(n);a?a.push(r):this.#e.set(n,[r])}for(let n of i){let a=this.#e.get(n);if(!a)this.#e.set(n,[new Set([r])]);else{let o=a[a.length-1];o instanceof Set?o.add(r):a.push(new Set([r]))}}return this.#n(r)}#i(t){let r=this.#t.get(t);if(!r)throw new Error("function does not have any path reservations");return{paths:r.paths.map(i=>this.#e.get(i)),dirs:[...r.dirs].map(i=>this.#e.get(i))}}check(t){let{paths:r,dirs:i}=this.#i(t);return r.every(n=>n&&n[0]===t)&&i.every(n=>n&&n[0]instanceof Set&&n[0].has(t))}#n(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#a(t)),!0)}#a(t){if(!this.#r.has(t))return!1;let r=this.#t.get(t);if(!r)throw new Error("invalid reservation");let{paths:i,dirs:n}=r,a=new Set;for(let o of i){let c=this.#e.get(o);if(!c||c?.[0]!==t)continue;let d=c[1];if(!d){this.#e.delete(o);continue}if(c.shift(),typeof d=="function")a.add(d);else for(let s of d)a.add(s)}for(let o of n){let c=this.#e.get(o),d=c?.[0];if(!(!c||!(d instanceof Set)))if(d.size===1&&c.length===1){this.#e.delete(o);continue}else if(d.size===1){c.shift();let s=c[0];typeof s=="function"&&a.add(s)}else d.delete(t)}return this.#r.delete(t),a.forEach(o=>this.#n(o)),!0}};var mF_=Symbol("onEntry"),Cul=Symbol("checkFs"),AF_=Symbol("checkFs2"),qul=Symbol("isReusable"),gIe=Symbol("makeFs"),Tul=Symbol("file"),Rul=Symbol("directory"),SDu=Symbol("link"),PF_=Symbol("symlink"),jF_=Symbol("hardlink"),wF_=Symbol("unsupported"),EF_=Symbol("checkPath"),Dul=Symbol("stripAbsolutePath"),men=Symbol("mkdir"),X5=Symbol("onError"),wDu=Symbol("pending"),SF_=Symbol("pend"),qya=Symbol("unpend"),Iul=Symbol("ended"),Bul=Symbol("maybeClose"),zul=Symbol("skip"),Kno=Symbol("doChown"),$no=Symbol("uid"),Jno=Symbol("gid"),Yno=Symbol("checkedCwd"),b4I=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Xno=b4I==="win32",v4I=1024,g4I=(e,t)=>{if(!Xno)return KA.default.unlink(e,t);let r=e+".DELETE."+(0,Nul.randomBytes)(16).toString("hex");KA.default.rename(e,r,i=>{if(i)return t(i);KA.default.unlink(r,t)})},O4I=e=>{if(!Xno)return KA.default.unlinkSync(e);let t=e+".DELETE."+(0,Nul.randomBytes)(16).toString("hex");KA.default.renameSync(e,t),KA.default.unlinkSync(t)},MF_=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,Tya=class extends h8i{[Iul]=!1;[Yno]=!1;[wDu]=0;reservations=new jDu;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[Iul]=!0,this[Bul]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;t.preserveOwner===void 0&&typeof t.uid!="number"?this.preserveOwner=!!(process.getuid&&process.getuid()===0):this.preserveOwner=!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:v4I,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Xno,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=F_(yAe.default.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:process.umask():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",r=>this[mF_](r))}warn(t,r,i={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(i.recoverable=!1),super.warn(t,r,i)}[Bul](){this[Iul]&&this[wDu]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Dul](t,r){let i=t[r],{type:n}=t;if(!i||this.preservePaths)return!0;let a=i.split("/");if(a.includes("..")||Xno&&/^[a-z]:\.\.$/i.test(a[0]??"")){if(r==="path"||n==="Link")return this.warn("TAR_ENTRY_ERROR",`${r} contains '..'`,{entry:t,[r]:i}),!1;{let d=yAe.default.posix.dirname(t.path),s=yAe.default.posix.normalize(yAe.default.posix.join(d,i));if(s.startsWith("../")||s==="..")return this.warn("TAR_ENTRY_ERROR",`${r} escapes extraction directory`,{entry:t,[r]:i}),!1}}let[o,c]=zno(i);return o&&(t[r]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${r}`,{entry:t,[r]:i})),!0}[EF_](t){let r=F_(t.path),i=r.split("/");if(this.strip){if(i.length<this.strip)return!1;if(t.type==="Link"){let n=F_(String(t.linkpath)).split("/");if(n.length>=this.strip)t.linkpath=n.slice(this.strip).join("/");else return!1}i.splice(0,this.strip),t.path=i.join("/")}if(isFinite(this.maxDepth)&&i.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:r,depth:i.length,maxDepth:this.maxDepth}),!1;if(!this[Dul](t,"path")||!this[Dul](t,"linkpath"))return!1;if(yAe.default.isAbsolute(t.path)?t.absolute=F_(yAe.default.resolve(t.path)):t.absolute=F_(yAe.default.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:F_(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:n}=yAe.default.win32.parse(String(t.absolute));t.absolute=n+rul(String(t.absolute).slice(n.length));let{root:a}=yAe.default.win32.parse(t.path);t.path=a+rul(t.path.slice(a.length))}return!0}[mF_](t){if(!this[EF_](t))return t.resume();switch(DF_.default.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Cul](t);default:return this[wF_](t)}}[X5](t,r){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:r}),this[qya](),r.resume())}[men](t,r,i){yF_(F_(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:r},i)}[Kno](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[$no](t){return MF_(this.uid,t.uid,this.processUid)}[Jno](t){return MF_(this.gid,t.gid,this.processGid)}[Tul](t,r){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,n=new f8i(String(t.absolute),{flags:Aul(t.size),mode:i,autoClose:!1});n.on("error",d=>{n.fd&&KA.default.close(n.fd,()=>{}),n.write=()=>!0,this[X5](d,t),r()});let a=1,o=d=>{if(d){n.fd&&KA.default.close(n.fd,()=>{}),this[X5](d,t),r();return}--a===0&&n.fd!==void 0&&KA.default.close(n.fd,s=>{s?this[X5](s,t):this[qya](),r()})};n.on("finish",()=>{let d=String(t.absolute),s=n.fd;if(typeof s=="number"&&t.mtime&&!this.noMtime){a++;let u=t.atime||new Date,f=t.mtime;KA.default.futimes(s,u,f,p=>p?KA.default.utimes(d,u,f,h=>o(h&&p)):o())}if(typeof s=="number"&&this[Kno](t)){a++;let u=this[$no](t),f=this[Jno](t);typeof u=="number"&&typeof f=="number"&&KA.default.fchown(s,u,f,p=>p?KA.default.chown(d,u,f,h=>o(h&&p)):o())}o()});let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>{this[X5](d,t),r()}),t.pipe(c)),c.pipe(n)}[Rul](t,r){let i=typeof t.mode=="number"?t.mode&4095:this.dmode;this[men](String(t.absolute),i,n=>{if(n){this[X5](n,t),r();return}let a=1,o=()=>{--a===0&&(r(),this[qya](),t.resume())};t.mtime&&!this.noMtime&&(a++,KA.default.utimes(String(t.absolute),t.atime||new Date,t.mtime,o)),this[Kno](t)&&(a++,KA.default.chown(String(t.absolute),Number(this[$no](t)),Number(this[Jno](t)),o)),o()})}[wF_](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[PF_](t,r){this[SDu](t,String(t.linkpath),"symlink",r)}[jF_](t,r){let i=F_(yAe.default.resolve(this.cwd,String(t.linkpath)));this[SDu](t,i,"link",r)}[SF_](){this[wDu]++}[qya](){this[wDu]--,this[Bul]()}[zul](t){this[qya](),t.resume()}[qul](t,r){return t.type==="File"&&!this.unlink&&r.isFile()&&r.nlink<=1&&!Xno}[Cul](t){this[SF_]();let r=[t.path];t.linkpath&&r.push(t.linkpath),this.reservations.reserve(r,i=>this[AF_](t,i))}[AF_](t,r){let i=c=>{r(c)},n=()=>{this[men](this.cwd,this.dmode,c=>{if(c){this[X5](c,t),i();return}this[Yno]=!0,a()})},a=()=>{if(t.absolute!==this.cwd){let c=F_(yAe.default.dirname(String(t.absolute)));if(c!==this.cwd)return this[men](c,this.dmode,d=>{if(d){this[X5](d,t),i();return}o()})}o()},o=()=>{KA.default.lstat(String(t.absolute),(c,d)=>{if(d&&(this.keep||this.newer&&d.mtime>(t.mtime??d.mtime))){this[zul](t),i();return}if(c||this[qul](t,d))return this[gIe](null,t,i);if(d.isDirectory()){if(t.type==="Directory"){let s=this.chmod&&t.mode&&(d.mode&4095)!==t.mode,u=f=>this[gIe](f??null,t,i);return s?KA.default.chmod(String(t.absolute),Number(t.mode),u):u()}if(t.absolute!==this.cwd)return KA.default.rmdir(String(t.absolute),s=>this[gIe](s??null,t,i))}if(t.absolute===this.cwd)return this[gIe](null,t,i);g4I(String(t.absolute),s=>this[gIe](s??null,t,i))})};this[Yno]?a():n()}[gIe](t,r,i){if(t){this[X5](t,r),i();return}switch(r.type){case"File":case"OldFile":case"ContiguousFile":return this[Tul](r,i);case"Link":return this[jF_](r,i);case"SymbolicLink":return this[PF_](r,i);case"Directory":case"GNUDumpDir":return this[Rul](r,i)}}[SDu](t,r,i,n){KA.default[i](r,String(t.absolute),a=>{a?this[X5](a,t):(this[qya](),t.resume()),n()})}},EDu=e=>{try{return[null,e()]}catch(t){return[t,null]}},Zno=class extends Tya{sync=!0;[gIe](t,r){return super[gIe](t,r,()=>{})}[Cul](t){if(!this[Yno]){let a=this[men](this.cwd,this.dmode);if(a)return this[X5](a,t);this[Yno]=!0}if(t.absolute!==this.cwd){let a=F_(yAe.default.dirname(String(t.absolute)));if(a!==this.cwd){let o=this[men](a,this.dmode);if(o)return this[X5](o,t)}}let[r,i]=EDu(()=>KA.default.lstatSync(String(t.absolute)));if(i&&(this.keep||this.newer&&i.mtime>(t.mtime??i.mtime)))return this[zul](t);if(r||this[qul](t,i))return this[gIe](null,t);if(i.isDirectory()){if(t.type==="Directory"){let o=this.chmod&&t.mode&&(i.mode&4095)!==t.mode,[c]=o?EDu(()=>{KA.default.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[gIe](c,t)}let[a]=EDu(()=>KA.default.rmdirSync(String(t.absolute)));this[gIe](a,t)}let[n]=t.absolute===this.cwd?[]:EDu(()=>O4I(String(t.absolute)));this[gIe](n,t)}[Tul](t,r){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,n=c=>{let d;try{KA.default.closeSync(a)}catch(s){d=s}(c||d)&&this[X5](c||d,t),r()},a;try{a=KA.default.openSync(String(t.absolute),Aul(t.size),i)}catch(c){return n(c)}let o=this.transform&&this.transform(t)||t;o!==t&&(o.on("error",c=>this[X5](c,t)),t.pipe(o)),o.on("data",c=>{try{KA.default.writeSync(a,c,0,c.length)}catch(d){n(d)}}),o.on("end",()=>{let c=null;if(t.mtime&&!this.noMtime){let d=t.atime||new Date,s=t.mtime;try{KA.default.futimesSync(a,d,s)}catch(u){try{KA.default.utimesSync(String(t.absolute),d,s)}catch{c=u}}}if(this[Kno](t)){let d=this[$no](t),s=this[Jno](t);try{KA.default.fchownSync(a,Number(d),Number(s))}catch(u){try{KA.default.chownSync(String(t.absolute),Number(d),Number(s))}catch{c=c||u}}}n(c)})}[Rul](t,r){let i=typeof t.mode=="number"?t.mode&4095:this.dmode,n=this[men](String(t.absolute),i);if(n){this[X5](n,t),r();return}if(t.mtime&&!this.noMtime)try{KA.default.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Kno](t))try{KA.default.chownSync(String(t.absolute),Number(this[$no](t)),Number(this[Jno](t)))}catch{}r(),t.resume()}[men](t,r){try{return vF_(F_(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:r})}catch(i){return i}}[SDu](t,r,i,n){let a=`${i}Sync`;try{KA.default[a](r,String(t.absolute)),n(),t.resume()}catch(o){return this[X5](o,t)}}};var m4I=e=>{let t=new Zno(e),r=e.file,i=Ful.default.statSync(r),n=e.maxReadSize||16*1024*1024;new xMu(r,{readSize:n,size:i.size}).pipe(t)},A4I=(e,t)=>{let r=new Tya(e),i=e.maxReadSize||16*1024*1024,n=e.file;return new Promise((o,c)=>{r.on("error",c),r.on("close",o),Ful.default.stat(n,(d,s)=>{if(d)c(d);else{let u=new lwn(n,{readSize:i,size:s.size});u.on("error",c),u.pipe(r)}})})},Qul=Xkt(m4I,A4I,e=>new Zno(e),e=>new Tya(e),(e,t)=>{t?.length&&kol(e,t)});var _2=ce(require("fs"),1),Uul=ce(require("path"),1);var P4I=(e,t)=>{let r=new Pwn(e),i=!0,n,a;try{try{n=_2.default.openSync(e.file,"r+")}catch(d){if(d?.code==="ENOENT")n=_2.default.openSync(e.file,"w+");else throw d}let o=_2.default.fstatSync(n),c=Buffer.alloc(512);e:for(a=0;a<o.size;a+=512){for(let u=0,f=0;u<512;u+=f){if(f=_2.default.readSync(n,c,u,c.length-u,a+u),a===0&&c[0]===31&&c[1]===139)throw new Error("cannot append to compressed archives");if(!f)break e}let d=new _Ae(c);if(!d.cksumValid)break;let s=512*Math.ceil((d.size||0)/512);if(a+s+512>o.size)break;a+=s,e.mtimeCache&&d.mtime&&e.mtimeCache.set(String(d.path),d.mtime)}i=!1,j4I(e,r,a,n,t)}finally{if(i)try{_2.default.closeSync(n)}catch{}}},j4I=(e,t,r,i,n)=>{let a=new Sya(e.file,{fd:i,start:r});t.pipe(a),E4I(t,n)},w4I=(e,t)=>{t=Array.from(t);let r=new Oen(e),i=(a,o,c)=>{let d=(h,_)=>{h?_2.default.close(a,y=>c(h)):c(null,_)},s=0;if(o===0)return d(null,0);let u=0,f=Buffer.alloc(512),p=(h,_)=>{if(h||typeof _>"u")return d(h);if(u+=_,u<512&&_)return _2.default.read(a,f,u,f.length-u,s+u,p);if(s===0&&f[0]===31&&f[1]===139)return d(new Error("cannot append to compressed archives"));if(u<512)return d(null,s);let y=new _Ae(f);if(!y.cksumValid)return d(null,s);let b=512*Math.ceil((y.size??0)/512);if(s+b+512>o||(s+=b+512,s>=o))return d(null,s);e.mtimeCache&&y.mtime&&e.mtimeCache.set(String(y.path),y.mtime),u=0,_2.default.read(a,f,0,512,s,p)};_2.default.read(a,f,0,512,s,p)};return new Promise((a,o)=>{r.on("error",o);let c="r+",d=(s,u)=>{if(s&&s.code==="ENOENT"&&c==="r+")return c="w+",_2.default.open(e.file,c,d);if(s||!u)return o(s);_2.default.fstat(u,(f,p)=>{if(f)return _2.default.close(u,()=>o(f));i(u,p.size,(h,_)=>{if(h)return o(h);let y=new f8i(e.file,{fd:u,start:_});r.pipe(y),y.on("error",o),y.on("close",a),S4I(r,t)})})};_2.default.open(e.file,c,d)})},E4I=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?Own({file:Uul.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>e.add(i)}):e.add(r)}),e.end()},S4I=async(e,t)=>{for(let r=0;r<t.length;r++){let i=String(t[r]);i.charAt(0)==="@"?await Own({file:Uul.default.resolve(String(e.cwd),i.slice(1)),noResume:!0,onReadEntry:n=>e.add(n)}):e.add(i)}e.end()},jwn=Xkt(P4I,w4I,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!zN_(e))throw new TypeError("file is required");if(e.gzip||e.brotli||e.zstd||e.file.endsWith(".br")||e.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!t?.length)throw new TypeError("no paths specified to add/replace")});var M4I=Xkt(jwn.syncFile,jwn.asyncFile,jwn.syncNoFile,jwn.asyncNoFile,(e,t=[])=>{jwn.validate?.(e,t),D4I(e)}),D4I=e=>{let t=e.filter;e.mtimeCache||(e.mtimeCache=new Map),e.filter=t?(r,i)=>t(r,i)&&!((e.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0)):(r,i)=>!((e.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0))};var RF_=ce(GQ(),1);var I4I=E3i();async function zF_({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:i,cliVersion:n,settings:a,loadAPIWorkspace:o}){let c,d={type:sh.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},s=t.dependencies[e];return s==null?d={type:sh.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${N4I(s)}`},async u=>{switch(s.type){case"version":c=await R4I({context:u,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:o});return;case"local":c=await T4I({context:u,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:o});return;default:fe(s)}}),c!=null?{didSucceed:!0,definition:c}:{didSucceed:!1,failure:d}}var NF_="dependencies";var B4I="metadata.json",C4I=".fern";function q4I(e){return ut(vr.of((0,CF_.homedir)()),me.of(C4I),me.of(NF_),me.of(e.organization),me.of(e.apiName),me.of(e.version))}async function T4I({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){if(n==null){t.failWithoutThrowing("Failed to load api definition");return}t.logger.info("Parsing...");let a=await n({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!a.didSucceed){t.failWithoutThrowing("Failed to load api definition",a.failures);return}t.logger.info("Modifying source filepath ...");let o=await a.workspace.getDefinition({context:t,relativePathToDependency:me.of(e.path)},i);return t.logger.info("Loaded..."),o}async function R4I({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){let a=q4I(e),o=ut(a,me.of(NF_)),c=ut(a,me.of(B4I)),d;if(!await ii(o)||!await ii(c)){t.logger.info("Downloading manifest...");let f=await I4I.definitionRegistry.get(Lul.FernFiddle.OrganizationId(e.organization),Lul.FernFiddle.ApiId(e.apiName),e.version);if(!f.ok){f.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:y=>{t.failWithoutThrowing("Failed to download API manifest",y)}});return}let p=f.body.yamlSchemaVersion!=null?parseInt(f.body.yamlSchemaVersion):void 0,h=uwn(r),_=uwn(f.body.cliVersion);if(p!=null){if(p>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${f.body.cliVersion}`);return}else if(p<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(h.major!==_.major||h.minor!==_.minor){t.failWithoutThrowing(`CLI version is ${f.body.cliVersion}. Expected ${h.major}.${h.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+f.body.definitionS3DownloadUrl),await(0,Rya.mkdir)(o,{recursive:!0});try{await z4I({s3PreSignedReadUrl:f.body.definitionS3DownloadUrl,absolutePathToLocalOutput:o})}catch(y){t.failWithoutThrowing("Failed to download API",y);return}d=f.body,await(0,Rya.writeFile)(c,JSON.stringify(d))}else d=JSON.parse((await(0,Rya.readFile)(c)).toString());if(t.logger.info("Parsing..."),n==null){t.failWithoutThrowing("Failed to load API");return}let s=await n({absolutePathToWorkspace:o,context:t,cliVersion:d.cliVersion,workspaceName:void 0});if(!s.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",s.failures);return}if(s.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await s.workspace.getDefinition({context:t},i)}async function z4I({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await BC.get(e,{responseType:"stream"}),i=await RF_.default.dir(),n=qF_.default.join(i.path,"api.tgz");await(0,TF_.pipeline)(r.data,(0,BF_.createWriteStream)(n)),await Qul({file:n,cwd:t})}function N4I(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:fe(e)}}async function FF_({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:i,settings:n,loadAPIWorkspace:a}){let o={},c={},d={};return await Promise.all(KI(t.packageMarkers).map(async([s,u])=>{if(u.contents.export==null)o[s]=u;else{let{export:f,...p}=u.contents;if(tj(p)>0)d[s]={type:sh.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:s};else{let h=rn(s);if(v7(t.namedDefinitionFiles).some(y=>y!==s&&y.startsWith(h)))d[s]={type:sh.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:h};else{let y=await zF_({dependencyName:typeof u.contents.export=="string"?u.contents.export:u.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:i,settings:n,loadAPIWorkspace:a});y.didSucceed?c[rn(s)]={definition:y.definition,url:typeof u.contents.export=="object"?u.contents.export.url:void 0}:d[s]=y.failure}}}})),tj(d)>0?{didSucceed:!1,failures:d}:{didSucceed:!0,packageMarkers:o,importedDefinitions:c}}var QF_=ce(require("path"),1);var Vul={};$t(Vul,{additionalProperties:()=>L4I,default:()=>W4I,definitions:()=>V4I,properties:()=>Q4I,required:()=>U4I,type:()=>F4I});var F4I="object",Q4I={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},product:{oneOf:[{$ref:"#/definitions/products.ProductDeclarationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},U4I=["name"],L4I=!1,V4I={"environments.ServerVariableSchema":{type:"object",properties:{id:{type:"string"},default:{oneOf:[{type:"string"},{type:"null"}]},values:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]}},required:["id"],additionalProperties:!1},"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"url-template":{oneOf:[{type:"string"},{type:"null"}]},variables:{oneOf:[{type:"array",items:{$ref:"#/definitions/environments.ServerVariableSchema"}},{type:"null"}]}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.EndpointSecuritySchemaDetails":{type:"object",additionalProperties:!1},"auth.EndpointSecuritySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"endpoint-security":{$ref:"#/definitions/auth.EndpointSecuritySchemaDetails"}},required:["endpoint-security"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"},{$ref:"#/definitions/auth.EndpointSecuritySchema"}]},"auth.AuthScope":{type:"string"},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"token-header":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},omit:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.TokenBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.InferredAuthenticatedRequestHeader":{type:"object",properties:{"response-property":{type:"string"},"header-name":{type:"string"},"value-prefix":{oneOf:[{type:"string"},{type:"null"}]}},required:["response-property","header-name"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchemaObject":{type:"object",properties:{endpoint:{type:"string"},"expiry-response-property":{oneOf:[{type:"string"},{type:"null"}]},"authenticated-request-headers":{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.InferredAuthenticatedRequestHeader"}},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.InferredGetTokenEndpointSchemaObject"}]},"auth.InferredBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},"get-token":{$ref:"#/definitions/auth.InferredGetTokenEndpointSchema"}},required:["scheme","get-token"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{anyOf:[{$ref:"#/definitions/auth.TokenBearerAuthSchema"},{$ref:"#/definitions/auth.InferredBearerAuthSchema"}]},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1},"products.ProductValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},versions:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"products.ProductValue":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductValueDetailed"}]},"products.ProductDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"products.ProductDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductDeclarationHeaderObjectSchema"}]},"products.ProductDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/products.ProductValue"}},header:{$ref:"#/definitions/products.ProductDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},W4I={type:F4I,properties:Q4I,required:U4I,additionalProperties:L4I,definitions:V4I};var Wul={};$t(Wul,{additionalProperties:()=>G4I,default:()=>$4I,definitions:()=>K4I,properties:()=>H4I,type:()=>x4I});var x4I="object",H4I={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},G4I=!1,K4I={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/service.HttpEndpointAuth"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"method-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},$4I={type:x4I,properties:H4I,additionalProperties:G4I,definitions:K4I};var xul={};$t(xul,{additionalProperties:()=>X4I,default:()=>k4I,definitions:()=>Z4I,properties:()=>Y4I,type:()=>J4I});var J4I="object",Y4I={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},X4I=!1,Z4I={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/service.HttpEndpointAuth"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"method-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},k4I={type:J4I,properties:Y4I,additionalProperties:X4I,definitions:Z4I};function UF_({files:e,absolutePathToDefinition:t}){let r,i={},n={},a={};for(let[o,c]of KI(e)){let d=c.contents,s=u=>{a[o]={type:sh.JSONSCHEMA_VALIDATION,error:u}};if(o===zC){let u=l5t(d,Vul);if(u.success){let f=TC.serialization.RootApiFileSchema.parseOrThrow(d);r={defaultUrl:f["default-url"],contents:f,rawContents:c.rawContents}}else s(u)}else if(QF_.default.basename(o)===Gv){let u=l5t(d,xul);if(u.success){let f=TC.serialization.PackageMarkerFileSchema.parseOrThrow(d);n[o]={defaultUrl:typeof f.export=="object"?f.export.url:void 0,contents:f,rawContents:c.rawContents}}else s(u)}else{let u=l5t(d,Wul);if(u.success){let f=TC.serialization.DefinitionFileSchema.parseOrThrow(d);i[o]={defaultUrl:void 0,contents:f,rawContents:c.rawContents,absoluteFilePath:ut(t,o)}}else s(u)}}return r==null?{didSucceed:!1,failures:{[me.of(zC)]:{type:sh.FILE_MISSING},...a}}:Object.keys(a).length>0?{didSucceed:!1,failures:a}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:r,packageMarkers:n}}var Z5=class extends W5t{type="fern";context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...i}){super(i),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){return(await this.toFernWorkspace({context:t},r)).definition}async toFernWorkspace({context:t},r){let i=(0,LF_.default)(r??{}),n=this.fernWorkspaces[i];if(n==null){let a=t||this.context,o=ut(this.absoluteFilePath,me.of(HM)),c=await Iil({absolutePathToWorkspace:this.absoluteFilePath,context:a}),d=await MN_(o,"{yml,yaml}"),s=await DN_(d);if(!s.didSucceed)return UMu(s.failures,a.logger),a.failAndThrow();let u=UF_({files:s.files,absolutePathToDefinition:o});if(!u.didSucceed)return UMu(u.failures,a.logger),a.failAndThrow();let f=await FF_({dependenciesConfiguration:c,structuralValidationResult:u,context:a,cliVersion:this.cliVersion,settings:r,loadAPIWorkspace:this.loadAPIWorkspace});if(!f.didSucceed)return UMu(f.failures,a.logger),a.failAndThrow();let p={absoluteFilePath:o,rootApiFile:u.rootApiFile,namedDefinitionFiles:u.namedDefinitionFiles,packageMarkers:f.packageMarkers,importedDefinitions:f.importedDefinitions};r?.auth!=null&&(p={...p,rootApiFile:{...p.rootApiFile,contents:{...p.rootApiFile.contents,auth:r?.auth}}}),n=new xZ({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:c,workspaceName:this.workspaceName,definition:p,cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[i]=n}return n}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var gU_=require("fs/promises");var dU_=ce(fU_(),1);async function yao(e){return(await(0,dU_.convertObj)(e,{})).openapi}var hU_=require("fs/promises");var pU_=require("fs/promises");async function Wya({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:i}){let n=null;try{let a=(await(0,pU_.readFile)(e,"utf8")).toString();try{n=JSON.parse(a)}catch{n=Mi.load(a,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return szc({data:t,overrides:n,allowNullKeys:i})}async function psl({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,hU_.readFile)(t)).toString(),n=await Mi.load(i);return r!=null?await Wya({absoluteFilePathToOverrides:r,context:e,data:n}):n}var vU_=require("fs/promises");var HDu=require("fs/promises");var xDu=ce(require("path"),1),_U_=ce(GQ(),1),hsl;async function V3I(){return hsl===void 0&&(hsl=(await _U_.default.dir({prefix:"fern-overlay-"})).path),hsl}async function yU_({absoluteFilePathToOverlay:e,absoluteFilePathToOpenAPI:t,data:r,context:i}){let n=await W3I(e,i);if(!x3I(n,i))return r;i.logger.debug(`Applying overlay "${n.info.title}" v${n.info.version}`);let a=ezc({data:r,overlay:n}),o=await V3I(),c=xDu.default.basename(t),d=`${xDu.default.parse(c).name}.overlaid.json`,s=xDu.default.join(o,d);return await(0,HDu.writeFile)(s,JSON.stringify(a,null,2),"utf8"),i.logger.info(`Wrote overlaid OpenAPI spec to: ${s}`),a}async function W3I(e,t){let r;try{r=await(0,HDu.readFile)(e,"utf8")}catch(i){return t.failAndThrow(`Failed to read overlay file at ${e}: ${i}`)}try{try{return JSON.parse(r)}catch{return Mi.load(r,{json:!0})}}catch(i){return t.failAndThrow(`Failed to parse overlay file at ${e}: ${i}`)}}function x3I(e,t){if(!e.overlay)return t.logger.error("Overlay file missing required 'overlay' version field"),!1;if(!e.info?.title||!e.info?.version)return t.logger.error("Overlay file missing required 'info.title' or 'info.version' field"),!1;if(!Array.isArray(e.actions)||e.actions.length===0)return t.logger.error("Overlay file must have at least one action"),!1;for(let r=0;r<e.actions.length;r++){let i=e.actions[r];if(!i?.target)return t.logger.error(`Overlay action at index ${r} missing required 'target' field`),!1;if(i.update===void 0&&!i.remove)return t.logger.error(`Overlay action at index ${r} must have either 'update' or 'remove'`),!1}return!0}var gao=ce(NEu(),1);var bU_=ce(NEu(),1),bao=ce(require("path"),1),vao=class extends bU_.BaseResolver{absolutePathToOpenAPIOverrides;absolutePathToOpenAPIOverlays;constructor({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r}){super(),this.absolutePathToOpenAPIOverrides=t,this.absolutePathToOpenAPIOverlays=r}resolveExternalRef(t,r){let i=super.resolveExternalRef(t,r);if(i.startsWith("http://")||i.startsWith("https://")||WMe(vr.of(i)))return i;if(this.absolutePathToOpenAPIOverlays!=null){let n=bao.default.resolve(bao.default.dirname(this.absolutePathToOpenAPIOverlays),r);if(WMe(vr.of(n)))return n}return this.absolutePathToOpenAPIOverrides!=null?bao.default.resolve(bao.default.dirname(this.absolutePathToOpenAPIOverrides),r):i}};async function _sl({absolutePathToOpenAPI:e,absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r,parsed:i}){return(i!=null?await(0,gao.bundle)({...FEu,doc:{source:new gao.Source(e,"<openapi>"),parsed:i},externalRefResolver:new vao({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r})}):await(0,gao.bundle)({...FEu,ref:e,externalRefResolver:new vao({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r})})).bundle.parsed}function H3I(e,t){if(t.includes(e))return e;for(let r of t){let i=r.replace(/\{[^}]+\}/g,"([^/]+)");if(new RegExp(`^${i}$`).test(e))return r}}var G3I=["examples","example",nn.EXAMPLES,V3.REDOCLY_CODE_SAMPLES_CAMEL,V3.REDOCLY_CODE_SAMPLES_KEBAB];async function Oao({context:e,absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r,absolutePathToOpenAPIOverlays:i,loadAiExamples:n=!1}){let a=await _sl({absolutePathToOpenAPI:t}),o;r!=null?o=r:typeof a=="object"&&a[nn.OPENAPI_OVERIDES_FILEPATH]!=null&&(o=ut(rn(t),me.of(a[nn.OPENAPI_OVERIDES_FILEPATH])));let c=a;if(o!=null&&(c=await Wya({absoluteFilePathToOverrides:o,context:e,data:c,allowNullKeys:G3I})),i!=null&&(c=await yU_({absoluteFilePathToOverlay:i,absoluteFilePathToOpenAPI:t,context:e,data:c})),n){let d=ut(rn(t),me.of("ai_examples_override.yml"));try{let s=await(0,vU_.readFile)(d,"utf-8"),u=Mi.load(s);if(u?.paths&&c.paths){for(let[f,p]of Object.entries(u.paths))if(p&&typeof p=="object")for(let[h,_]of Object.entries(p)){let y=h.toLowerCase(),b=c.paths[f];if(!b&&c.paths){let v=H3I(f,Object.keys(c.paths));v&&(b=c.paths[v],e.logger.debug(`Matched override path "${f}" to OpenAPI path "${v}" using pattern matching`))}if(b&&typeof b=="object"){let O=b[y];if(O&&typeof O=="object"){let m=O;!m["x-fern-examples"]&&_["x-fern-examples"]&&(m["x-fern-examples"]=_["x-fern-examples"],e.logger.debug(`Added AI examples for ${h.toUpperCase()} ${f} from override file`))}}}}e.logger.debug(`Processed AI examples from ${d}`)}catch{}}return o!=null||i!=null||c!==a?await _sl({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:o,absolutePathToOpenAPIOverlays:i,parsed:c}):c}var PHt=class{absoluteFilePath;constructor(t){this.absoluteFilePath=t}async loadDocuments({context:t,specs:r,loadAiExamples:i=!1}){let n=[];for(let a of r)try{let o=(await(0,gU_.readFile)(a.absoluteFilepath)).toString(),c=Jl(this.absoluteFilePath,a.source.file);a.source.relativePathToDependency!=null&&(c=ut(a.source.relativePathToDependency,c));let d=a.source.type==="protobuf"?q5.protobuf({file:c}):q5.openapi({file:c});if(o.includes("openapi")||o.includes("swagger"))try{let s=await Oao({absolutePathToOpenAPI:a.absoluteFilepath,context:t,absolutePathToOpenAPIOverrides:a.absoluteFilepathToOverrides,absolutePathToOpenAPIOverlays:a.absoluteFilepathToOverlays,loadAiExamples:i});if(Dil(s)){n.push({type:"openapi",value:s,source:d,namespace:a.namespace,settings:iIe({options:a.settings})});continue}else if(Tio(s)){(!s.schemes||s.schemes.length===0)&&(s.schemes=["https"]);let u=await yao(s);n.push({type:"openapi",value:u,source:d,namespace:a.namespace,settings:iIe({options:a.settings})});continue}}catch(s){t.logger.debug(`Failed to parse OpenAPI document at ${a.absoluteFilepath}: ${s}. Skipping...`);continue}if(o.includes("asyncapi"))try{let s=await psl({context:t,absoluteFilePath:a.absoluteFilepath,absoluteFilePathToOverrides:a.absoluteFilepathToOverrides});n.push({type:"asyncapi",value:s,source:d,namespace:a.namespace,settings:iIe({options:a.settings})});continue}catch(s){t.logger.error(`Failed to parse AsyncAPI document at ${a.absoluteFilepath}: ${s}. Skipping...`);continue}if(o.includes("openrpc"))try{let s=await psl({context:t,absoluteFilePath:a.absoluteFilepath,absoluteFilePathToOverrides:a.absoluteFilepathToOverrides});n.push({type:"asyncapi",value:s,source:d,namespace:a.namespace,settings:iIe({options:a.settings})});continue}catch(s){t.logger.error(`Failed to parse OpenRPC document at ${a.absoluteFilepath}: ${s}. Skipping...`);continue}t.logger.warn(`${a.absoluteFilepath} is not a valid OpenAPI, AsyncAPI, or OpenRPC file. Skipping...`)}catch(o){t.logger.error(`Failed to read or process file ${a.absoluteFilepath}: ${o}. Skipping...`);continue}return n}};var Va=class e{breadcrumbs=[];context;static STRING=Ir.TypeReference.primitive({v1:"STRING",v2:Ir.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Ir.TypeReference.container(Ir.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var mU_=require("fs/promises");var ysl=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:i,position:n,lineStart:a}=t;this._map[r]={line:i,position:n,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(i=>{this.resolveNode(i,(r==="."?"":r)+"."+i.path)})}iterFragments(t,r){for(let i=this._fragments.length-1;i>=0;i--){if(!this._fragments[i].path.startsWith(t)||this._fragments[i].path===t)continue;let n=this._fragments.pop();r(n)}}handleState(t,r){if(t==="close"){let i=r.result,n=r.kind,a=this._path.join(".");if(n==="scalar"){this._path.pop(),this._lastScalar=`${i}`;let{line:o,position:c,lineStart:d}=r;this._path.length===0?this._map["."+i]={line:o,position:c,lineStart:d}:this._fragments.push({path:this._path.join(".")+"."+i,line:o,position:c,lineStart:d})}else if(n==="mapping"){let o={path:a,children:[],line:0,position:0,lineStart:0},c=0;this.iterFragments(a,d=>{c++,!((!d.children||d.children.length===0)&&c%2===1)&&(this._path.length===1?this.resolveNode(d,d.path):(o.children.push({...d,path:d.path.slice(a.length+1)}),o.line=d.line,o.position=d.position,o.lineStart=d.lineStart))}),o.children&&o.children.length>0&&this._fragments.push(o),this._path.pop()}else if(n==="sequence"){let o={path:a,children:[],line:0,position:0,lineStart:0},c=new Set,d=i.length;this.iterFragments(a,s=>{c.has(s.position)||(d--,c.add(s.position),this._path.length===1?this.resolveNode(s,`${a}.${d}`):(o.children.push({...s,path:d.toString()}),o.line=s.line,o.position=s.position,o.lineStart=s.lineStart))}),o.children&&o.children.length>0&&this._fragments.push(o),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:i,position:n,lineStart:a}=r;this._map["."]={line:i,position:n,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(n=>`${n}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let i=this._map[r];if(i)return{line:i.line+1,column:i.position-i.lineStart+1,position:i.position}}},OU_=ysl;var PR;(function(e){e.WARNING="warning",e.ERROR="error"})(PR||(PR={}));var mIe=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new bsl({logger:t,relativePathToFile:me.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,i=0;for(let n of this.errors){let a=n.path?n.path.join("->"):"",o=`${n.message}|${n.level||PR.WARNING}|${a}`;r.has(o)?i++:(r.add(o),t.push(n))}return this.errors=t,i}getErrorStats(){this.dedupe();let t=0,r=0;for(let i of this.errors)i.level===PR.ERROR?t++:(i.level===PR.WARNING||i.level===void 0)&&r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors){let i=r.level??PR.WARNING;if(!(i===PR.WARNING&&!t))switch(i){case PR.ERROR:if(this.logger.log(na.Debug,r.message),r.path&&r.path.length>0){let n=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),a=n?`${this.relativeFilepathToSpec}:${n.line}:${n.column}`:r.path.join(" -> ");this.logger.log(na.Debug,` - at location (${a})`)}break;case PR.WARNING:if(this.logger.log(na.Warn,r.message),r.path&&r.path.length>0){let n=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),a=n?`${this.relativeFilepathToSpec}:${n.line}:${n.column}`:r.path.join(" -> ");this.logger.log(na.Warn,` - at location (${a})`)}r.resolution&&this.logger.log(na.Warn,` - resolution: ${r.resolution}`);break}}}},bsl=class{logger;relativePathToFile;map=new OU_;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,mU_.readFile)(this.relativePathToFile,"utf-8");Mi.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(na.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var kq=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=X7({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples,this.documentBaseDir=t.documentBaseDir}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=An(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i}){let n=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(o=>o.replace(/~1/g,"/"));for(let o of a){if(typeof n!="object"||n==null)return i||this.errorCollector.collect({level:PR.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[o]}return n==null?(i||this.errorCollector.collect({level:PR.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:n}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,i,n=!1,a=null,o;if(this.isExternalReference(t.$ref)){n=!0;let s=t.$ref.split("#"),u=s[0];if(i=s[1],!u)return{resolved:!1};o=u;let f=await fetch(u);if(!f.ok)return{resolved:!1};try{let p=await f.text();try{a=JSON.parse(p),r=a}catch{a=Mi.load(p),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let c=i??t.$ref;if(c==null||typeof c!="string")return{resolved:!1};let d=c.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of d){if(typeof r!="object"||r==null)return{resolved:!1};r=r[s]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let s=new Set;s.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,s,o)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let o=[];for(let c of t)o.push(await this.resolveNestedExternalReferences(c,r,i,n));return o}if(this.isReferenceObject(t)){let o=t.$ref;if(this.isExternalReference(o)){if(i.has(o))return t;i.add(o);let c=await this.resolveMaybeExternalReference({$ref:o});if(i.delete(o),c.resolved)return c.value}else{let c=`${n}${o}`;if(i.has(c))return t;i.add(c);let d=r,s=o.substring(2).split("/").map(u=>u.replace(/~1/g,"/").replace(/~0/g,"~"));for(let u of s){if(typeof d!="object"||d===null)return t;d=d[u]}if(d!=null){let u=await this.resolveNestedExternalReferences(d,r,i,n);return i.delete(o),u}i.delete(o)}return t}let a={};for(let[o,c]of Object.entries(t))typeof c=="object"&&c!==null?a[o]=await this.resolveNestedExternalReferences(c,r,i,n):a[o]=c;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,{value:t.example}])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:i}){if(this.isReferenceObject(t)){let n=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i});return n.resolved?n.value:void 0}return t}resolveExampleRecursively({example:t,breadcrumbs:r,maxDepth:i=10}){let n=t,a=0;for(;this.isReferenceObject(n);){if(a>=i){this.errorCollector.collect({message:`Maximum reference depth (${i}) exceeded while resolving example reference`,path:r});return}let o=this.resolveReference({reference:n,breadcrumbs:r,skipErrorCollector:!0});if(!o.resolved)return;n=o.value,a++}return n}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let a=this.resolveReference({reference:r});if(!a.resolved)return;r=a.value}let{readOnly:i,writeOnly:n}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(i&&n)){if(i)return k2t.ReadOnly;if(n)return k2t.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,i=!0;for(let n of t.allOf){let a=n;if(this.isReferenceObject(n)){let c=this.resolveReference({reference:n});if(!c.resolved)continue;a=c.value}let o=this.getReadOnlyWriteOnlyFromSchema(a);r=r&&o.readOnly,i=i&&o.writeOnly}return{readOnly:r,writeOnly:i}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new BN.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(n!=null)return n.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=this.resolveReference({reference:t});if(!a.resolved)return;t=a.value}let n=new BN.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:lR.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return hi.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:t,displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t||"summary"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t&&typeof t.summary=="string"&&t.summary.length>0}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var Nl=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let i=t[this.key];if(i!=null)return i;if(r!=null)return t[r]}};var BN={};$t(BN,{AudienceExtension:()=>GDu,FernAvailabilityExtension:()=>KDu,FernEnumExtension:()=>$Du,FernIgnoreExtension:()=>Bwn,FernOptionalExtension:()=>JDu,FernTypeExtension:()=>kDu,FernTypeNameExtension:()=>eIu,SdkGroupNameExtension:()=>YDu,SdkMethodNameExtension:()=>XDu,ServerFromOperationNameExtension:()=>ZDu});var GDu=class extends Nl{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var KDu=class extends Nl{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return lR.InDevelopment;case"PRE_RELEASE":case"BETA":return lR.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return lR.GeneralAvailability;case"DEPRECATED":return lR.Deprecated;default:return}}};var K3I=Bt.object({snake:Bt.string().optional(),camel:Bt.string().optional(),screamingSnake:Bt.string().optional(),pascal:Bt.string().optional()}),$3I=Bt.object({description:Bt.string().optional(),name:Bt.string().optional(),casing:K3I.optional()}),AU_=Bt.record($3I);var $Du=class extends Nl{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=AU_.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var Bwn=class extends Nl{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var JDu=class extends Nl{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var YDu=class extends Nl{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var XDu=class extends Nl{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var ZDu=class extends Nl{operation;key="x-fern-server-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation,"x-name");if(!(t==null||typeof t!="string"))return t}};var kDu=class extends Nl{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var eIu=class extends Nl{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var jHt=class extends Va{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new Jjn(i),this.ir={auth:{docs:void 0,requirement:Ir.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Ir.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((i,n)=>!new Bwn({breadcrumbs:[...r,String(n)],operation:i,context:this.context}).convert()).map((i,n)=>this.removeXFernIgnores({document:i,breadcrumbs:[...r,String(n)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([i,n])=>!new Bwn({breadcrumbs:[...r,i],operation:n,context:this.context}).convert()).map(([i,n])=>[i,this.removeXFernIgnores({document:n,breadcrumbs:[...r,i]})])):t}finalizeIr(){let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(t=this.filterIrForAudiences(t));let r=this.context.exampleGenerationArgs,i=ral({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=uno({ir:t,exampleGeneration:r});return{...t,...n,...i}}return{...t,...i}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),i=this.irGraph.getFilteredChannels(),n=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let o=[];for(let c of a.endpoints)r.has(c.id)&&o.push(c);a.endpoints=o}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>i.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).map(([a,o])=>{let c=o.filter(d=>d.id!=null&&n.has(d.id));return[a,c]})),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let i=r.shift();i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let i=0;i<t.length;i++)t[i]=await this.resolveReferenceChain(t[i],r)}async resolveExternalRefsInObject(t,r){for(let[i,n]of Object.entries(t))t[i]=await this.resolveReferenceChain(n,r)}async resolveReferenceChain(t,r){let i=t;if(!this.context.isReferenceObject(i))return r.push(i),t;for(;this.context.isReferenceObject(i);){let n=this.context.isExternalReference(i.$ref),a=await this.context.resolveMaybeExternalReference(i);if(a.resolved){if(i=a.value,n)return i}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:i="openapi"}){return i==="openapi"?!r.some(n=>n.url===t.url&&"x-fern-server-name"in n&&"x-fern-server-name"in t&&n["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(n=>n.url===t.url&&"name"in n&&"name"in t&&n.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let o=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:i}),d=[...o].map(f=>this.context.casingsGenerator.generateName(f)),s=d[d.length-1];c.service==null&&(c.service=a??`service_${o.map(f=>An(f)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[c.service]?.endpoints.push(t);let u=this.ir.services[c.service];u!=null&&(this.irGraph.addEndpoint(u,t),this.irGraph.markEndpointForAudience(u.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:i,group:n}){let a=n?.join(".")??r,o=this.getOrCreatePackage({group:n});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),o.webhooks=a;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),i!=null&&this.irGraph.markWebhookForAudiences(c,t,i)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:i,websocketGroup:n}){let a=An(n?.join(".")),o=An(r),c=this.context.namespace?`${An(this.context.namespace)}/`:"",d=a?`channel_${c}${a}`:`channel_${c}${o}`,s=n?this.getOrCreatePackage({group:n}):this.getOrCreatePackage({group:[o]});this.ir.websocketChannels={...this.ir.websocketChannels,[d]:t},d!==""?s.websocket==null&&(s.websocket=d):this.ir.rootPackage.websocket="";let u=this.context.createFernFilepath();this.irGraph.addChannel(u,d,t),i!=null&&this.irGraph.markChannelForAudiences(u,d,i)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[i,n]of Object.entries(t??{}))r[i]!=null&&this.irGraph.markEnvironmentForAudiences(n,r[i])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:i,inlinedTypes:n}=r,o=Object.keys(n).some(c=>c===t)?`${t}Wrapper`:t;this.addTypeToPackage(o),this.addTypesToIr({...n,[o]:i})}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,i])=>[r,i.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let i of r.endpoints)i.baseUrl==null&&(i.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:i}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:i,basePath:eI(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(n=>An(n))),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",c=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[c]==null&&(this.ir.subpackages[c]={name:this.context.casingsGenerator.generateName(a),displayName:void 0,...this.createPackage({name:a})});let d=this.ir.subpackages[c];i.subpackages.includes(c)||i.subpackages.push(c),i=d}return i}};var $A={};$t($A,{AbstractConverters:()=>gsl,ExampleConverter:()=>NU,SchemaConverters:()=>vsl,ServersConverter:()=>vAe});var gsl={};$t(gsl,{AbstractMediaTypeObjectConverter:()=>iIu,AbstractParameterConverter:()=>nIu});var J3I=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/;function Y3I(e){return e.type==="array"||e.properties||e.oneOf||e.anyOf||e.allOf||e.additionalProperties?!1:!!(e.type==="string"||e.type==="number"||e.type==="integer"||e.type==="boolean"||e.const!==void 0||Array.isArray(e.enum)&&e.enum.length>0)}function PU_(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var NU=class e extends Va{MAX_DEPTH=12;EXAMPLE_STRING=pa.STRING;EXAMPLE_NUMBER=pa.DOUBLE;EXAMPLE_BOOLEAN=pa.BOOLEAN;EXAMPLE_INTEGER=pa.INT;EXAMPLE_DATE=pa.DATE;EXAMPLE_DATE_TIME=pa.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:o,generateOptionalProperties:c=!1,seenRefs:d=new Set}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=o,this.generateOptionalProperties=c,this.seenRefs=d}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let i=this.schema.$ref;if(this.seenRefs.has(i))return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(t==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]};if(typeof t!="object")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]};if("nullable"in t&&t.nullable===!0&&this.example===null)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.maybeConvertLiteralFernType(t);return r??(Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]})}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof i=="boolean"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i??r,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,usedProvidedExample:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,i=r?.default;return typeof i=="number"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:i,maximum:n,exclusiveMinimum:a,exclusiveMaximum:o}=r,c;a!=null?typeof a=="boolean"?c=i!=null?i+Math.max(Number.EPSILON,Math.abs(i)*1e-10):void 0:c=a+Math.max(Number.EPSILON,Math.abs(a)*1e-10):i!=null&&(c=i);let d;return o!=null?typeof o=="boolean"?d=n!=null?n-Math.max(Number.EPSILON,Math.abs(n)*Number.EPSILON):void 0:d=o-Math.max(Number.EPSILON,Math.abs(o)*Number.EPSILON):n!=null&&(d=n),c!==void 0&&d!==void 0?(t<c||t>d)&&(t=c+(d-c)/2):c!==void 0&&t<c?t=c+Math.abs(c*.1):d!==void 0&&t>d&&(t=d-Math.abs(d*.1)),Number(Number(t).toPrecision(3))}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,i=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??i,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,i=this.example??t.example,a=(Array.isArray(i)?i:[i]).map(d=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:d,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),o=a.every(d=>d?.isValid??!1)&&!r,c=!r&&a.some(d=>d.usedProvidedExample);return{isValid:o,coerced:!1,usedProvidedExample:c,validExample:a.map(d=>d.validExample),errors:o?[]:a.flatMap(d=>d.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=Object.entries(t.properties??{}).map(([f,p])=>{if(typeof p!="object")return{key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(p)&&!this.isRequiredProperty({key:f,resolvedSchema:t}))return{key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in p&&p.readOnly===!0&&"writeOnly"in p&&p.writeOnly===!0)return{key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in p&&p.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in p&&p.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let h=!(f in r)||!("nullable"in p)&&r[f]==null||"nullable"in p&&p.nullable===!0&&r[f]===void 0,_=!t.required?.includes(f);if(h&&_){if(this.example===void 0&&this.generateOptionalProperties){let y=this.maybeResolveSchemaExample(p),b=new e({breadcrumbs:[...this.breadcrumbs,f],context:this.context,schema:p,example:y,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:f,result:b.convert()}}return{key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let y=r[f],b=y!==void 0?y:this.maybeResolveSchemaExample(p),O=new e({breadcrumbs:[...this.breadcrumbs,f],context:this.context,schema:p,example:b,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:f,result:O}}}),n=(t.allOf??[]).map((f,p)=>{let h=this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:[...this.breadcrumbs,`allOf[${p}]`],skipErrorCollector:!0});return h&&this.isConstraintOnlySchema(h)?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:new e({breadcrumbs:[...this.breadcrumbs,`allOf[${p}]`],context:this.context,schema:{...t,...f,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()}),a=i.every(f=>f.result.isValid)&&n.every(f=>f.isValid),o=this.example!==void 0&&(i.some(({result:f})=>f.usedProvidedExample)||n.some(f=>f.usedProvidedExample)),c=Object.fromEntries(i.map(({key:f,result:p})=>[f,p.validExample]).filter(([f,p])=>p!==void 0));for(let f of n)if(typeof f.validExample=="object"&&f.validExample!==null){let p=f.validExample;c={...c,...Object.fromEntries(Object.entries(p).filter(([h,_])=>_!==void 0))}}let d=[],s=this.collectAllPropertyKeys(t),u=Object.keys(r).filter(f=>!s.has(f));u.length>0&&(t.additionalProperties===!1?u.forEach(f=>{let p=[...this.breadcrumbs,f].join("."),h={message:`Found unexpected property '${f}' in example. This property does not exist in the schema${p?` at path: ${p}`:""}`,path:[...this.breadcrumbs,f]};d.push({key:f,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[h]}})}):u.forEach(f=>{let p=[...this.breadcrumbs,f].join("."),h={message:`Additional property ${f} is not allowed`,path:[...this.breadcrumbs,f]};d.push({key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[h]}})}));for(let{key:f,result:p}of d)p.validExample!==void 0&&c[f]===void 0&&(c[f]=p.validExample);if(Object.keys(c).length===0){let f=n.find(p=>p.validExample!==void 0&&(typeof p.validExample!="object"||p.validExample===null));f&&(c=f.validExample)}return{isValid:a,coerced:!1,usedProvidedExample:o,validExample:c,errors:[...i.flatMap(({result:f})=>f.errors),...n.flatMap(f=>f.errors),...d.flatMap(({result:f})=>f.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((c,d)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${d}]`],context:this.context,schema:{...t,type:c},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.some(c=>c?.isValid??!1),a=r.find(c=>c.isValid)?.validExample??r[0]?.validExample??null,o=r.some(c=>c.usedProvidedExample);return{isValid:i,coerced:!1,usedProvidedExample:o,validExample:a,errors:i?[]:r.flatMap(c=>c?.errors??[])}}convertUnion({resolvedSchema:t,unionType:r}){let i=r==="oneOf"?t.oneOf:t.anyOf;if(!(r in t)||i==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};let n=this.example??this.maybeResolveSchemaExample(t);if(this.example===void 0){let p=[];for(let _ of i){if(!_)continue;let y=this.context.resolveMaybeReference({schemaOrReference:_,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});y&&p.push(y)}if(p.length>0&&p.every(_=>Y3I(_))){let _=p.findIndex(y=>PU_(y)!==void 0);if(_!==-1){let y=i[_],b=p[_];if(y&&b){let v=PU_(b),m=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${_}]`],context:this.context,schema:r==="oneOf"?{...t,...y,oneOf:void 0}:y,example:v,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(m.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:m.validExample,errors:[]}}}}}let a=[],o=null,c=null;for(let p=0;p<i.length;p++){let h=i[p];if(!h)continue;let _=r==="oneOf"?{...t,...h,oneOf:void 0}:h,y=n??this.maybeResolveSchemaExample(_),v=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${p}]`],context:this.context,schema:_,example:y,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(v.isValid&&!v.coerced&&v.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:v.validExample,errors:[]};if(v.isValid&&!v.coerced)return{isValid:!0,coerced:!1,usedProvidedExample:v.usedProvidedExample,validExample:v.validExample,errors:[]};a.push(v),v.isValid&&v.usedProvidedExample&&c===null&&(c=v),v.isValid&&o===null&&(o=v)}let d=c??o,s=d!==null,u=d?.validExample??a[0]?.validExample,f=d?.usedProvidedExample??!1;return{isValid:s,coerced:!1,usedProvidedExample:f,validExample:u,errors:s?[]:a.flatMap(p=>p.errors)}}convertOneOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"oneOf"})}convertAnyOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"anyOf"})}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){if("example"in t)return t.example;if("examples"in t){let i=t.examples;if(Array.isArray(i)&&i.length>0)return i[0];if(i!=null&&typeof i=="object")return Object.values(i)[0]}let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r){let i=r.examples;return Array.isArray(i)&&i.length>0?i[0]:Object.values(i??{})[0]}}}maybeConvertLiteralFernType(t){let r=t["x-fern-type"];if(typeof r!="string")return;let i=r.match(J3I);if(i!=null){if(i[1]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i[1],errors:[]};if(i[2]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i[2]==="true",errors:[]}}}isConstraintOnlySchema(t){if(t.type!==void 0||t.properties!==void 0||t.allOf!==void 0||t.oneOf!==void 0||t.anyOf!==void 0||"items"in t||t.additionalProperties!==void 0||t.enum!==void 0||t.const!==void 0)return!1;let r=new Set(["required","description","title","deprecated","readOnly","writeOnly","nullable","example","examples","default","minLength","maxLength","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minItems","maxItems","uniqueItems","pattern","format"]),i=Object.keys(t);return i.length>0&&i.every(n=>r.has(n))}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}collectAllPropertyKeys(t,r=new Set){let i=new Set;if(t.properties)for(let n of Object.keys(t.properties))i.add(n);for(let n of t.allOf??[]){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(a){let o=this.context.isReferenceObject(n)?n.$ref:JSON.stringify(a);if(!r.has(o)){r.add(o);let c=this.collectAllPropertyKeys(a,r);for(let d of c)i.add(d)}}}for(let n of[...t.oneOf??[],...t.anyOf??[]]){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(a){let o=this.context.isReferenceObject(n)?n.$ref:JSON.stringify(a);if(!r.has(o)){r.add(o);let c=this.collectAllPropertyKeys(a,r);for(let d of c)i.add(d)}}}return i}};var vsl={};$t(vsl,{ArraySchemaConverter:()=>Kya,EnumSchemaConverter:()=>xya,ObjectSchemaConverter:()=>Hya,OneOfSchemaConverter:()=>Cwn,PrimitiveSchemaConverter:()=>Gya,SchemaConverter:()=>Den,SchemaOrReferenceConverter:()=>rH});function jU_(e){return xq({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return hi.primitive({v1:"BASE_64",v2:Cn.base64({})});case"BOOLEAN":return hi.primitive({v1:"BOOLEAN",v2:Cn.boolean({default:void 0})});case"DATE":return hi.primitive({v1:"DATE",v2:Cn.date({})});case"DATE_TIME":return hi.primitive({v1:"DATE_TIME",v2:Cn.dateTime({})});case"FLOAT":return hi.primitive({v1:"FLOAT",v2:Cn.float({default:void 0,validation:void 0})});case"DOUBLE":return hi.primitive({v1:"DOUBLE",v2:Cn.double({default:void 0,validation:void 0})});case"UINT":return hi.primitive({v1:"UINT",v2:Cn.uint({default:void 0,validation:void 0})});case"UINT_64":return hi.primitive({v1:"UINT_64",v2:Cn.uint64({default:void 0,validation:void 0})});case"INTEGER":return hi.primitive({v1:"INTEGER",v2:Cn.integer({default:void 0,validation:void 0})});case"LONG":return hi.primitive({v1:"LONG",v2:Cn.long({default:void 0,validation:void 0})});case"STRING":return hi.primitive({v1:"STRING",v2:Cn.string({default:void 0,validation:void 0})});case"UUID":return hi.primitive({v1:"UUID",v2:Cn.uuid({})});case"BIG_INTEGER":return hi.primitive({v1:"BIG_INTEGER",v2:Cn.bigInteger({default:void 0})});default:return}},unknown:()=>hi.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return hi.container(Js.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return hi.container(Js.list(t))},optional:t=>{if(t!=null)return hi.container(Js.optional(t))},nullable:t=>{if(t!=null)return hi.container(Js.nullable(t))},set:t=>{if(t!=null)return hi.container(Js.set(t))},literal:t=>hi.container(Js.literal(t._visit({string:r=>sU.string(r),boolean:r=>sU.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var xya=class extends Va{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),o=this.maybeFernEnum?.[a],c=o?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:c,wireValue:a}),docs:o?.description,availability:void 0,casing:o?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:Yl.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var tIu=class extends Va{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:i}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=i}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=hi.container(Js.map({keyType:Va.STRING,valueType:hi.unknown()}));return{type:Yl.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new rH({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=hi.container(Js.map({keyType:Va.STRING,valueType:r.type})),n=new Set;for(let a of r.schema?.typeDeclaration.referencedTypes??[])n.add(a);for(let a of Object.keys(r.inlinedTypes))n.add(a);return{type:Yl.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function mao({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],o={},c={},d=new Set;for(let[s,u]of Object.entries(e??{})){let f=[...r,"properties",s];if(typeof u!="object"){n.collect({message:`Schema property ${s} should be an object`,path:f});continue}let p=X3I(r,u,i)??i.convertBreadcrumbsToName(f),h="nullable"in u?u.nullable:!1,y=new rH({context:i,breadcrumbs:f,schemaOrReference:u,schemaIdOverride:p,wrapAsOptional:!t.includes(s),wrapAsNullable:h}).convert();if(y!=null){a.push({name:i.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),valueType:y.type,docs:u.description,availability:y.availability,propertyAccess:i.getPropertyAccess(u),v2Examples:y.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),o={...o,...y.inlinedTypes},y.schema?.typeDeclaration.referencedTypes!=null&&y.schema.typeDeclaration.referencedTypes.forEach(b=>{d.add(b)});for(let b of y.schema?.audiences??[])c[b]==null&&(c[b]=new Set),c[b].add(s)}}for(let s of Object.keys(o))d.add(s);return{convertedProperties:a,propertiesByAudience:c,inlinedTypesFromProperties:o,referencedTypes:d}}function X3I(e,t,r){return r.isReferenceObject(t)?void 0:new BN.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var Hya=class extends Va{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:Yl.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=mao({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),o=[],c=n,d=this.schema.required!=null&&this.schema.required.length>0,s=i,u=a;for(let[f,p]of(this.schema.allOf??[]).entries()){let h=[...this.breadcrumbs,"allOf",f.toString()],_;if(this.context.isReferenceObject(p)){let m=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:h});if(m==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${f}] reference could not be resolved. Skipping: ${JSON.stringify(p)}`);continue}if(_=m,typeof _.additionalProperties=="boolean"&&_.additionalProperties&&(t=!0),!d||Object.keys(_.properties??{}).every(g=>!this.schema.required?.includes(g))){this.addTypeReferenceToExtends({reference:p,breadcrumbs:h,extends_:o,referencedTypes:c});continue}}else _=p;typeof _.additionalProperties=="boolean"&&_.additionalProperties&&(t=!0);let{convertedProperties:y,inlinedTypesFromProperties:b,referencedTypes:v,propertiesByAudience:O}=mao({properties:_.properties??{},required:[...this.schema.required??[],..._.required??[]],breadcrumbs:h,context:this.context,errorCollector:this.context.errorCollector});r.push(...y),s={...s,...b},u={...u,...O},v.forEach(m=>{c.add(m)})}for(let f of Object.keys(s))c.add(f);return{type:Yl.object({properties:r,extends:o.map(f=>this.context.typeReferenceToDeclaredTypeName(f)).filter($s),extendedProperties:[],extraProperties:t}),propertiesByAudience:u,referencedTypes:c,inlinedTypes:s}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:i,referencedTypes:n}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&i.push(a.reference);let o=this.context.getTypeIdFromSchemaReference(t);o!=null&&n.add(o)}};var rIu=class extends Nl{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}};var Cwn=class extends Va{schema;id;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n}convert(){return this.shouldConvertAsNullableSchemaOrReference()?this.convertAsNullableSchemaOrReference():new rIu({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1?this.convertAsUndiscriminatedUnion():this.schema.discriminator!=null?this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}filterDiscriminantFromSchema(t,r){if(t.properties==null||!(r in t.properties))return t;let{[r]:i,...n}=t.properties,a=t.required?.filter(o=>o!==r);return{...t,properties:n,required:a}}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=this.schema.discriminator.propertyName,r=[],i=new Set,n={};for(let[s,u]of Object.entries(this.schema.discriminator.mapping??{})){let f=this.context.getTypeIdFromSchemaReference({$ref:u}),p=[...this.breadcrumbs,"discriminator","mapping",s],h=this.context.resolveReference({reference:{$ref:u},breadcrumbs:p}),_={$ref:u};h.resolved&&h.value.properties!=null&&t in h.value.properties&&(_=this.filterDiscriminantFromSchema(h.value,t));let y=new rH({context:this.context,schemaOrReference:_,schemaIdOverride:f??void 0,breadcrumbs:p});f!=null&&i.add(f);let b=y.convert();if(b?.type!=null&&f!=null){for(let O of Object.keys(b?.inlinedTypes??{}))i.add(O);for(let O of b.schema?.typeDeclaration.referencedTypes??[])i.add(O);let v=this.context.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s});r.push({docs:void 0,discriminantValue:v,availability:b.availability,displayName:s,shape:cU.samePropertiesAsObject({typeId:f,name:this.context.casingsGenerator.generateName(f),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:s})}),n={...n,...b.inlinedTypes}}}let{convertedProperties:a,referencedTypes:o,inlinedTypesFromProperties:c}=mao({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});i=new Set([...i,...o]);let d=[];for(let[s,u]of(this.schema.allOf??[]).entries()){let f=[...this.breadcrumbs,"allOf",s.toString()];if(this.context.isReferenceObject(u)){let p=this.context.convertReferenceToTypeReference({reference:u,breadcrumbs:f});if(p.ok){let _=this.context.typeReferenceToDeclaredTypeName(p.reference);_!=null&&d.push(_)}let h=this.context.getTypeIdFromSchemaReference(u);h!=null&&i.add(h);continue}}for(let s of Object.keys({...n,...c}))i.add(s);return{type:Yl.union({baseProperties:a,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:d,types:r}),referencedTypes:i,inlinedTypes:{...n,...c}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,i={},n=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(a=>!this.context.isReferenceObject(a));for(let[a,o]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(o)){let p;if(this.context.isReferenceObjectWithIdentifier(o))p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.summary??o.title??o.name??o.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(o)!=null){let _=this.getDiscriminatorKeyForRef(o);p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:_,displayNameOverrideSource:"discriminator_key"})}else p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});p.ok&&t.push({type:p.reference,docs:o.description});let h=this.context.getTypeIdFromSchemaReference(o);h!=null&&r.add(h);continue}let c=this.extendSubSchema(o),d=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),s=o.title,f=new Den({context:this.context,id:d,nameOverride:s,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:c??o}).convert();if(f!=null){let p=f.convertedSchema.typeDeclaration.shape;p.type==="alias"&&this.typeReferenceIsWrappedPrimitive(p.aliasOf)?t.push({type:p.aliasOf,docs:o.description}):p.type==="object"&&p.properties.length===0&&p.extends.length===0?t.push({type:hi.container(Js.map({keyType:Va.STRING,valueType:hi.unknown()})),docs:o.description}):(t.push({type:this.context.createNamedTypeReference(d,s),docs:o.description}),i={...i,...f.inlinedTypes,[d]:f.convertedSchema}),f.convertedSchema.typeDeclaration.referencedTypes.forEach(h=>{r.add(h)})}}return{type:Yl.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:i}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=new rH({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:Yl.alias({aliasOf:n,resolvedType:n}),referencedTypes:i.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:i.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return hi.container(Js.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,i])=>i===t.$ref)?.[0]}};var Gya=class extends Va{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return hi.container(Js.literal(sU.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return hi.primitive({v1:Ps.Date,v2:Cn.date({})});if(this.schema.format==="date-time")return hi.primitive({v1:Ps.DateTime,v2:Cn.dateTime({})})}return hi.primitive({v1:"STRING",v2:Cn.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return hi.primitive({v1:"DOUBLE",v2:Cn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return hi.primitive({v1:"FLOAT",v2:Cn.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return hi.primitive({v1:"INTEGER",v2:Cn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return hi.primitive({v1:"LONG",v2:Cn.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return hi.primitive({v1:"UINT",v2:Cn.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return hi.primitive({v1:"UINT_64",v2:Cn.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return hi.primitive({v1:"DOUBLE",v2:Cn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return hi.primitive({v1:"DOUBLE",v2:Cn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return hi.primitive({v1:"FLOAT",v2:Cn.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return hi.primitive({v1:"INTEGER",v2:Cn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return hi.primitive({v1:"LONG",v2:Cn.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return hi.primitive({v1:"UINT",v2:Cn.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return hi.primitive({v1:"UINT_64",v2:Cn.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return hi.primitive({v1:"INTEGER",v2:Cn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?hi.container(Js.literal(sU.boolean(t))):hi.primitive({v1:"BOOLEAN",v2:Cn.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){let r=t.minimum,i=t.maximum,n,a;return typeof t.exclusiveMinimum=="boolean"?n=t.exclusiveMinimum:typeof t.exclusiveMinimum=="number"&&(r=t.exclusiveMinimum,n=!0),typeof t.exclusiveMaximum=="boolean"?a=t.exclusiveMaximum:typeof t.exclusiveMaximum=="number"&&(i=t.exclusiveMaximum,a=!0),{max:i,min:r,exclusiveMax:a,exclusiveMin:n,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var Z3I=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],Den=class e extends Va{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1,nameOverride:o}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a,this.nameOverride=o,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let i=this.tryConvertSingularAllOfSchema();if(i!=null)return i;let n=this.tryConvertPrimitiveSchema();if(n!=null)return n;let a=this.tryConvertArraySchema();if(a!=null)return a;let o=this.tryConvertTypeArraySchema();if(o!=null)return o;let c=this.tryConvertOneOfAnyOfSchema();if(c!=null)return c;let d=this.tryConvertMapSchema();if(d!=null)return d;let s=this.tryConvertDiscriminatorMappingSchema();if(s!=null)return s;let u=this.tryConvertObjectAllOfSchema();if(u!=null)return u;let f=this.tryConvertUntypedSchema();if(f!=null)return f;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new BN.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new xya({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.context.resolveMaybeReference({schemaOrReference:this.schema.allOf[0],breadcrumbs:this.breadcrumbs});if(r!=null){let n=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(n?.convertedSchema.typeDeclaration?.shape.type!=="object")return n}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let n of this.schema.allOf??[]){if(this.context.isReferenceObject(n))return;r=Jua(r,n,(a,o)=>{if(o===n)return a;if(Array.isArray(a)&&Array.isArray(o))return[...a,...o]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new Gya({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Yl.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new Kya({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Yl.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new Cwn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new tIu({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertDiscriminatorMappingSchema(){if(this.schema.discriminator?.mapping!=null&&Object.keys(this.schema.discriminator.mapping).length>0&&this.schema.oneOf==null&&this.schema.anyOf==null){let t={...this.schema,oneOf:Object.values(this.schema.discriminator.mapping).map(n=>({$ref:n}))},i=new Cwn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:t,inlinedTypes:{}}).convert();if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:i.type,referencedTypes:i.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:i.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new Hya({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Yl.alias({aliasOf:hi.unknown(),resolvedType:hi.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new BN.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=jU_(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Yl.alias({aliasOf:i,resolvedType:i}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:i?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...Z3I,...t];return Object.keys(this.schema).every(n=>r.includes(n))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=this.context.resolveExample(n),o=`${this.id}_example_${i}`,c=this.generateOrValidateExample({example:a,exampleName:o});r[o]=c}return r}generateOrValidateExample({example:t}){let r=new NU({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:i}=r.convert();return i}};var rH=class extends Va{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:o=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=o}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new Den({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=i.convert();if(a!=null){let o=a.convertedSchema.typeDeclaration.shape;return o.type==="alias"?{type:this.wrapTypeReference(o.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return hi.container(Js.optional(t))}wrapInNullable(t){return hi.container(Js.nullable(t))}};var Kya=class e extends Va{static LIST_UNKNOWN=hi.container(Js.list(hi.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new rH({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let i=new Set;for(let n of r.schema?.typeDeclaration.referencedTypes??[])i.add(n);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(n=>{n.typeDeclaration.referencedTypes.forEach(a=>{i.add(a)})}),{typeReference:hi.container(Js.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var iIu=class extends Va{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:i,schemaId:n}){if(t.schema==null)return;if(r){let d=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",i]});if(d==null)return;t.schema=d}let o=new rH({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",i,"schema"],schemaOrReference:t.schema,schemaIdOverride:n}).convert();if(o==null)return;let c=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([d,s])=>{if(this.context.isReferenceObject(s)){let u=this.context.resolveReference({reference:s,breadcrumbs:[...this.breadcrumbs,"content",i,"examples"],skipErrorCollector:!0});return u.resolved?[d,u.value.value??u.value]:null}return[d,s.value??s]}).filter(d=>d!=null)):void 0;return{...o,examples:c}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let n=new rH({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(n!=null)return{...n,examples:void 0}}getIdForExample({key:t,example:r,usedExampleNames:i}){if(this.context.isExampleWithSummary(r)){let n=r.summary;if(!i.has(n))return n;let a=`${n} (${t})`;return i.has(a)?t:a}return t}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,o=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),c=new Set;for(let[d,s]of o){let u=this.context.resolveExampleWithValue(s),f=this.context.resolveExampleRecursively({example:s,breadcrumbs:this.breadcrumbs}),p=this.getIdForExample({key:d,example:f,usedExampleNames:c});c.add(p),u!=null&&(a!=null?n.userSpecifiedExamples[p]=this.generateOrValidateExample({schema:a,example:u,exampleGenerationStrategy:i,exampleName:p}):n.userSpecifiedExamples[p]=u)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let d=An(`${[...this.group,this.method].join("_")}_example`);n.autogeneratedExamples[d]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i,exampleName:d})}return n}generateOrValidateExample({schema:t,example:r,generateOptionalProperties:i,exampleGenerationStrategy:n}){let a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(a==null)return;let o=this.context.getExamplesFromSchema({schema:a,breadcrumbs:this.breadcrumbs}),c=new NU({breadcrumbs:this.breadcrumbs,context:this.context,schema:a,example:r??o[0],generateOptionalProperties:i??!1,exampleGenerationStrategy:n}),{validExample:d}=c.convert();return d}};var nIu=class extends Va{parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),o=this.getParameterSchemaWithExampleOverride({schema:a});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??Va.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:o??t}),availability:n,explode:this.getExplodeForQueryParameter()},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??Va.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:o??t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??Va.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:o??t}),explode:this.getExplodeForPathParameter()},inlinedTypes:i};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,o]of Object.entries(n??{})){let c=this.context.resolveExampleWithValue(o);c!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:c,exampleName:a}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:i,exampleName:a})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0,exampleName:a})}return r}generateOrValidateExample({schema:t,example:r}){let i=new NU({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:n}=i.convert();return n}getExplodeForQueryParameter(){let t=this.parameter.style??"form",r=this.parameter.explode;if(r!==void 0)return t==="form"?r===!0?void 0:r:r===!1?void 0:r}getExplodeForPathParameter(){let t=this.parameter.explode;if(t!==void 0)return t===!1?void 0:t}};var aIu=class extends Nl{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var wU_="Base",k3I="x-fern-default-url",vAe=class e extends Va{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let i=this.getDefaultBaseUrlName(),n={id:i,name:this.context.casingsGenerator.generateName(i)},a=this.endpointLevelServers.map(d=>{let s=e.getServerName({server:d,context:this.context});return{id:s,name:this.context.casingsGenerator.generateName(s)}}).filter((d,s,u)=>u.findIndex(f=>f.id===d.id)===s),o=[n,...a],c=this.servers.map(d=>{let s=e.getServerName({server:d,context:this.context}),u=this.endpointLevelServers?.map(_=>[e.getServerName({server:_,context:this.context}),this.getServerUrl(_)]),{defaultUrls:f,urlTemplates:p,urlVariables:h}=this.buildMultiUrlTemplateFields({defaultBaseUrlId:i,topLevelServer:d,endpointServers:this.endpointLevelServers??[]});return{id:s,name:this.context.casingsGenerator.generateName(s),urls:{[i]:this.getServerUrl(d),...Object.fromEntries(u??[])},docs:d.description,defaultUrls:f,urlTemplates:p,urlVariables:h}});return{value:{defaultEnvironment:c[0]?.id,environments:JD.multipleBaseUrls({baseUrls:o,environments:c})},defaultUrl:n.id}}let t=this.extractFernDefaultUrl(),r=this.servers.map(i=>{let n=e.getServerName({server:i,context:this.context});return i.variables!=null&&Object.keys(i.variables).length>0&&i.variables!=null?{id:n,name:this.context.casingsGenerator.generateName(n),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(i)),defaultUrl:t,urlTemplate:this.maybeRemoveTrailingSlashIfNotEmpty(i.url),urlVariables:this.convertServerVariables(i.variables),docs:i.description}:{id:n,name:this.context.casingsGenerator.generateName(n),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(i)),defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0,docs:i.description}}).filter($s);return{value:{defaultEnvironment:r[0]?.id,environments:JD.singleBaseUrl({environments:r})},defaultUrl:r[0]?.id}}convertServerVariables(t){return Object.entries(t).map(([r,i])=>({id:r,name:this.context.casingsGenerator.generateName(r),default:i.default,values:i.enum}))}static getServerExtensionName({server:t,context:r}){return new aIu({breadcrumbs:[],server:t,context:r}).convert()}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,encodeURIComponent(n.default)));return r}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?wU_:e.getServerExtensionName({server:this.servers[0],context:this.context})??wU_}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}buildMultiUrlTemplateFields({defaultBaseUrlId:t,topLevelServer:r,endpointServers:i}){let n={},a={},o={},c=!1;if(r.variables!=null&&Object.keys(r.variables).length>0){c=!0;let d=this.extractFernDefaultUrlFromServer(r);d!=null&&(n[t]=d),a[t]=this.maybeRemoveTrailingSlashIfNotEmpty(r.url),o[t]=this.convertServerVariables(r.variables)}for(let d of i){let s=e.getServerName({server:d,context:this.context});if(d.variables!=null&&Object.keys(d.variables).length>0){c=!0;let u=this.extractFernDefaultUrlFromServer(d);u!=null&&(n[s]=u),a[s]=this.maybeRemoveTrailingSlashIfNotEmpty(d.url),o[s]=this.convertServerVariables(d.variables)}}return c?{defaultUrls:Object.keys(n).length>0?n:void 0,urlTemplates:a,urlVariables:o}:{defaultUrls:void 0,urlTemplates:void 0,urlVariables:void 0}}extractFernDefaultUrlFromServer(t){let r=t[k3I];if(typeof r=="string")return this.maybeRemoveTrailingSlashIfNotEmpty(r)}extractFernDefaultUrl(){if(this.servers!=null)for(let t of this.servers){let r=this.extractFernDefaultUrlFromServer(t);if(r!=null)return r}}};var qwn=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:i,exampleGenerationStrategy:n}){return new NU({breadcrumbs:i,context:this.context,schema:r,example:t,depth:0,exampleGenerationStrategy:n,generateOptionalProperties:!1}).convert()}validateEndpointExample({exampleToValidate:t}){let r=[],i=[],n=!0,a=!1,o,c=[t.endpointPath,t.method];if(t.requestExample!==void 0&&t.requestSchema!==void 0){let s=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...c,"request"],exampleGenerationStrategy:"request"});if(!s.isValid){n=!1;let u=t.exampleSource==="human"?PR.WARNING:PR.ERROR;r.push(...s.errors.map(f=>({...f,level:u,message:`Invalid request example: ${f.message}`})))}s.coerced&&(a=!0,i.push({level:PR.WARNING,message:"Request example was coerced to match schema",path:[...c,"request"]})),o={request:s.validExample}}let d=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&d!==void 0){let s=this.validateExample({example:t.responseExample,schema:d,breadcrumbs:[...c,"response"],exampleGenerationStrategy:"response"});if(!s.isValid){n=!1;let u=t.exampleSource==="human"?PR.WARNING:PR.ERROR;r.push(...s.errors.map(f=>({...f,level:u,message:`Invalid response example: ${f.message}`})))}s.coerced&&(a=!0,i.push({level:PR.WARNING,message:"Response example was coerced to match schema",path:[...c,"response"]})),o={...typeof o=="object"&&o!==null?o:{},response:s.validExample}}return{isValid:n,errors:r,warnings:i,endpointPath:t.endpointPath,method:t.method,exampleSource:t.exampleSource,exampleName:t.exampleName,validExample:o,coerced:a}}getResponseSchemaForValidation(t){let{responseStatusCode:r,responseSchemas:i,responseSchema:n}=t;return i&&Object.keys(i).length>0?r&&i[r]?i[r]:i[200]??i[201]:n}validateAiExamples({aiExamples:t,spec:r}){let i=[],n=[];for(let a of t){let{requestSchema:o,responseSchema:c,responseSchemas:d}=this.getSchemasForEndpoint({spec:r,endpointPath:a.endpointPath,method:a.method}),s={endpointPath:a.endpointPath,method:a.method,exampleSource:"ai",requestExample:a.request?.body,responseExample:a.response?.body,requestSchema:o,responseSchema:c,responseSchemas:d},u=this.validateEndpointExample({exampleToValidate:s}),f=this.hasUnexpectedProperties({requestExample:a.request?.body,responseExample:a.response?.body,requestSchema:o,responseSchema:c}),p=u.errors.length>0||u.warnings.length>0;!u.isValid||p||f?n.push({example:a,validationResult:u}):i.push(a)}return{validExamples:i,invalidExamples:n}}hasUnexpectedProperties({requestExample:t,responseExample:r,requestSchema:i,responseSchema:n}){return!!(t&&i&&this.exampleHasUnexpectedProperties(t,i)||r&&n&&this.exampleHasUnexpectedProperties(r,n))}exampleHasUnexpectedProperties(t,r){if(!t||typeof t!="object"||t===null)return!1;let i=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[],skipErrorCollector:!0});if(!i||!i.properties&&!i.allOf&&!i.oneOf&&!i.anyOf)return!1;let n=t,a=this.collectAllPropertyKeys(i);return Object.keys(n).some(c=>!a.has(c))}collectAllPropertyKeys(t,r=new Set){let i=new Set;if(t.properties)for(let n of Object.keys(t.properties))i.add(n);for(let n of t.allOf??[]){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[],skipErrorCollector:!0});if(a){let o=this.context.isReferenceObject(n)?n.$ref:JSON.stringify(a);if(!r.has(o)){r.add(o);let c=this.collectAllPropertyKeys(a,r);for(let d of c)i.add(d)}}}for(let n of[...t.oneOf??[],...t.anyOf??[]]){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[],skipErrorCollector:!0});if(a){let o=this.context.isReferenceObject(n)?n.$ref:JSON.stringify(a);if(!r.has(o)){r.add(o);let c=this.collectAllPropertyKeys(a,r);for(let d of c)i.add(d)}}}return i}validateHumanExamples({spec:t}){let r=[],i=0,n=0,a=0,o=[],c=[];if(!t.paths)return{endpoints:r,totalExamples:i,validExamples:n,invalidExamples:a,hasInvalidHumanExamples:!1,hasInvalidAiExamples:!1,invalidHumanExamples:o,invalidAiExamples:c};for(let[d,s]of Object.entries(t.paths)){if(!s)continue;let u=["get","post","put","delete","patch","options","head","trace"];for(let f of u){let p=s[f];if(!p)continue;let h=[],{requestSchema:_,responseSchema:y,responseSchemas:b}=this.getSchemasForOperation({operation:p}),v=this.extractExamplesFromOperation({operation:p,path:d,method:f});for(let O of v){i++;let m={endpointPath:d,method:f,exampleName:O.name,exampleSource:O.source,requestExample:O.request,responseExample:O.response,requestSchema:_,responseSchema:y,responseStatusCode:O.statusCode,responseSchemas:b},g=this.validateEndpointExample({exampleToValidate:m});h.push(g),g.isValid?n++:(a++,O.source==="human"?o.push(g):O.source==="ai"&&c.push(g))}h.length>0&&r.push({endpointPath:d,method:f,results:h,hasInvalidExamples:h.some(O=>!O.isValid),invalidExampleCount:h.filter(O=>!O.isValid).length})}}return{endpoints:r,totalExamples:i,validExamples:n,invalidExamples:a,hasInvalidHumanExamples:o.length>0,hasInvalidAiExamples:c.length>0,invalidHumanExamples:o,invalidAiExamples:c}}getSchemasForEndpoint({spec:t,endpointPath:r,method:i}){let n=t.paths?.[r];if(!n)return{responseSchemas:{}};let a=n[i.toLowerCase()];return!a||typeof a!="object"||!("responses"in a)?{responseSchemas:{}}:this.getSchemasForOperation({operation:a})}getSchemasForOperation({operation:t}){let r,i,n={};if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let o=t.requestBody.content?.["application/json"];o?.schema&&(r=o.schema)}if(t.responses){for(let[a,o]of Object.entries(t.responses)){if(!o||this.context.isReferenceObject(o))continue;let d=o.content?.["application/json"];d?.schema&&(n[a]=d.schema)}i=n[200]??n[201]}return{requestSchema:r,responseSchema:i,responseSchemas:n}}extractExamplesFromOperation({operation:t,path:r,method:i}){let n=[];if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let c=t.requestBody.content?.["application/json"];if(c?.example!==void 0&&n.push({name:`${i}_${r}_request_example`,source:"openapi",request:c.example}),c?.examples)for(let[d,s]of Object.entries(c.examples)){let u=this.context.isReferenceObject(s)?this.context.resolveExample(s):s;u&&typeof u=="object"&&"value"in u&&n.push({name:d,source:"human",request:u.value})}}if(t.responses)for(let[o,c]of Object.entries(t.responses)){if(!c||this.context.isReferenceObject(c))continue;let s=c.content?.["application/json"];if(s?.example!==void 0){let u=n.find(f=>f.request!==void 0&&f.response===void 0);u?(u.response=s.example,u.statusCode=o):n.push({name:`${i}_${r}_response_${o}_example`,source:"openapi",response:s.example,statusCode:o})}if(s?.examples)for(let[u,f]of Object.entries(s.examples)){let p=this.context.isReferenceObject(f)?this.context.resolveExample(f):f;if(p&&typeof p=="object"&&"value"in p){let h=n.find(_=>_.name===u);h?(h.response=p.value,h.statusCode=o):n.push({name:u,source:"human",response:p.value,statusCode:o})}}}let a=t["x-fern-examples"];if(Array.isArray(a)){for(let o of a)if(typeof o=="object"&&o!==null){let c=o;n.push({name:c.name,source:"human",request:c.request?.body,response:c.response?.body})}}return n}};var oIu={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},eWI=new Set(Object.values(oIu));var tWI=Bt.object({type:Bt.string(),channelId:Bt.string().optional(),messageId:Bt.string(),value:Bt.any()}),rWI=Bt.object({summary:Bt.string().optional(),description:Bt.string().optional(),"query-parameters":Bt.record(Bt.string()).optional(),headers:Bt.record(Bt.string()).optional(),messages:Bt.array(tWI)}),EU_=Bt.array(rWI);var uIu=class extends Nl{channel;baseDir;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:i,baseDir:n}){super({breadcrumbs:t??[],context:i}),this.channel=r,this.baseDir=n}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=EU_.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(i=>({summary:i.summary,description:i.description,queryParameters:i["query-parameters"],headers:i.headers,messages:i.messages.map(n=>({type:n.type,channelId:n.channelId,messageId:n.messageId,value:n.value}))}))}};var $ya=class extends Va{channel;channelPath;inlinedTypes={};websocketGroup;constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r}),this.websocketGroup=i,this.channel=n,this.channelPath=a}convertExamples({fullPath:t,baseUrl:r,asyncApiVersion:i}){let a=new uIu({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel,baseDir:this.context.documentBaseDir}).convert();return a==null?{}:Object.fromEntries(a.map((o,c)=>[c.toString(),{channel:{method:"GET",path:t},baseUrl:t,environment:r,auth:void 0,pathParameters:{},queryParameters:o.queryParameters,headers:o.headers,messages:o.messages.map(d=>({type:i==="v2"?d.type:d.messageId,body:d.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var Ien=class extends $A.AbstractConverters.AbstractParameterConverter{parameterNamePrefix;constructor({context:t,breadcrumbs:r,parameter:i,parameterNamePrefix:n}){super({context:t,breadcrumbs:r,parameter:i}),this.parameterNamePrefix=n}convert(){let t,r={},n=new BN.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required===!1,a=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example??this.parameter.name,examples:Object.values(this.parameter.examples??{}),deprecated:this.parameter.deprecated,required:void 0},c=new $A.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameterNamePrefix?`${this.parameterNamePrefix}_${this.parameter.name}`:this.parameter.name,schemaOrReference:a,wrapAsOptional:n}).convert();return c!=null&&(t=c.type,r=c.inlinedTypes??{}),this.convertToOutput({schema:a,typeReference:t,inlinedTypes:r})}};var sIu=class extends Nl{channel;key="x-fern-address";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var Jya=class extends Nl{channel;key="x-fern-display-name";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var cIu=class extends $ya{inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a})}convert(){let t=[],r=[],i=[],a=new Jya({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".");this.channel.parameters&&this.convertPathParameters({context:this.context,pathParameters:t}),this.channel.bindings?.ws!=null&&(this.convertHeaders({context:this.context,headers:i}),this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let o;this.channel.subscribe!=null&&(o=this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let c;this.channel.publish!=null&&(c=this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let d=[];o!=null&&d.push(o),c!=null&&d.push(c);let u=new sIu({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),f=this.transformToValidPath(u??this.channelPath),p=this.channel.servers?.[0]??Object.keys(this.context.spec.servers??{})[0],h=eI(f),_=An(this.channelPath),y=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(_),displayName:a,baseUrl:p,path:h,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:d,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:f,baseUrl:p,asyncApiVersion:"v2"})}},audiences:y,inlinedTypes:this.inlinedTypes}}convertMessage({context:t,operation:r,origin:i}){let n,a=i==="server"?"subscribe":"publish",o=[...this.breadcrumbs,a],c=t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:o});c!=null&&(r.message=c);let d=Pmn(An(`${this.channelPath}_${a}`)).replace(/ /g,"");if("oneOf"in r.message){let u=new $A.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:o,schemaOrReference:r.message,schemaIdOverride:d}).convert();u!=null&&u.schema!=null&&(n=u.schema,this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let s=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:o});if(s!=null){let f=new $A.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:o,schemaOrReference:s,schemaIdOverride:d}).convert();f!=null&&f.schema!=null&&(n=f.schema,this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes})}}if(n!=null){let s=n,u=hi.named({fernFilepath:t.createFernFilepath(),name:s.typeDeclaration.name.name,typeId:s.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),f=R3.reference({bodyType:u,docs:r.description}),p=i==="server"?"subscribe":"publish";return{type:p,displayName:p,origin:i,body:f,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description,methodName:void 0}}}convertPathParameters({context:t,pathParameters:r}){for(let[i,n]of Object.entries(this.channel.parameters??{})){let a=t.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(a==null)continue;let c=new Ien({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:i,in:"path",description:a.description,required:a.required??!0}}).convert();c!=null&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},c.type==="path"&&r.push(c.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let i=this.channel.bindings.ws.headers.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let o=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(o==null)continue;let d=new Ien({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"header",required:i.includes(n),schema:o,description:"description"in o?o.description:void 0}}).convert();d!=null&&d.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let i=this.channel.bindings.ws.query.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.query.properties??{})){let o=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(o==null)continue;let d=new Ien({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"query",required:i.includes(n),schema:o,description:"description"in o?o.description:void 0,deprecated:o.deprecated??!1}}).convert();d!=null&&d.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}};var Yya=class extends Va{servers;constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r}),this.servers=i}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[i,n]of Object.entries(this.servers)){let a=this.buildSingleBaseUrlEnvironment(this.context,i,n);t.push(a),r==null&&(r=a.id)}return{defaultEnvironment:r,environments:JD.singleBaseUrl({environments:t})}}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var lIu=class extends Yya{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.url),docs:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}};var Osl="$message.",SU_="#/channels/",MU_="#/servers/",fIu=class extends $ya{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a,operations:o}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}),this.operations=o}convert(){let t=[],r=[],i=[],a=new Jya({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".")??this.channelPath;this.channel.parameters&&this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:this.channelPath});let o=Object.entries(this.operations).reduce((p,[h,_])=>{try{this.getChannelPathFromOperation(_)===this.channelPath&&(p[h]=_)}catch{}return p},{}),c=[];for(let[p,h]of Object.entries(o))for(let _ of h.messages){let y=this.context.convertReferenceToTypeReference({reference:_});if(y.ok){let b=R3.reference({bodyType:y.reference,docs:h.description});c.push({type:p,displayName:p,origin:h.action==="send"?"client":"server",body:b,availability:this.context.getAvailability({node:h,breadcrumbs:this.breadcrumbs}),docs:h.description,methodName:void 0})}}let d=this.resolveChannelServersFromReference(this.channel.servers??[])??Object.keys(this.context.spec.servers??{})[0],s=this.transformToValidPath(this.channel.address??this.channelPath),u=eI(s),f=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(a),displayName:a,baseUrl:d,path:u,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:c,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:s,baseUrl:d,asyncApiVersion:"v3"})}},audiences:f,inlinedTypes:this.inlinedTypes}}convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:n}){for(let a of Object.values(this.channel.parameters??{})){let o=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(o==null)continue;let c=this.convertChannelParameterLocation(o.location);if(c==null)continue;let{type:d,parameterKey:s}=c,f=new Ien({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:s,in:d},parameterNamePrefix:this.channelPath}).convert();if(f!=null)switch(this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes},f.type){case"path":t.push(f.parameter);break;case"query":r.push(f.parameter);break;case"header":i.push(f.parameter);break}}}convertChannelParameterLocation(t){try{let[r,i]=t.split("#/");if(r==null||i==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(Osl)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${Osl} prefix`,path:this.breadcrumbs});return}let n=r.substring(Osl.length);if(n!=="header"&&n!=="path"&&n!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${n}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return n==="payload"?{type:"query",parameterKey:i}:{type:n,parameterKey:i}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(MU_)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let i=r.$ref.substring(MU_.length);if(i==null){this.context.errorCollector.collect({message:`Failed to find server with name ${i}`,path:this.breadcrumbs});return}return i}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(SU_))throw new Error(`Failed to resolve channel path from operation ${t.channel.$ref}`);return t.channel.$ref.substring(SU_.length)}};var dIu=class extends Yya{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.host),docs:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}};var Aao=class extends jHt{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){return this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.isAsyncAPIV3(this.context)?this.convertChannelMessages():this.convertComponentMessages(),this.convertSchemas(),this.convertServers(),this.convertChannels(),this.finalizeIr()}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}convertChannelMessages(){let t=this.context.spec;for(let[r,i]of Object.entries(t.channels??{}))for(let[n,a]of Object.entries(i.messages??{})){if(!this.context.isMessageWithPayload(a)&&!this.context.isReferenceObject(a))continue;let o=["channels",r,"messages",n],c=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:o});if(!this.context.isMessageWithPayload(c))continue;let d=this.context.resolveMaybeReference({schemaOrReference:c.payload,breadcrumbs:o});if(d==null)continue;let s=`${r}_${n}`;this.convertSchema({id:s,breadcrumbs:o,schema:d})}}convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let i=["components","messages",t],n=this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:i});n!=null&&this.convertSchema({id:t,breadcrumbs:i,schema:n})}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}convertSchema({id:t,breadcrumbs:r,schema:i}){let a=new $A.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:i}).convert();a!=null&&this.addSchemaOutputToIr(t,a)}convertServers(){let t;if(this.isAsyncAPIV3(this.context)){let r=this.context.spec.servers;t=new dIu({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new lIu({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let n=new BN.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,a;if(this.isAsyncAPIV3(this.context)){let c=this.context.spec.operations??{};a=new fIu({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t,operations:c}).convert()}else a=new cIu({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t}).convert();a!=null&&(this.addWebsocketChannelToIr({websocketChannel:a.channel,channelPath:t,audiences:a.audiences,websocketGroup:n}),this.addTypesToIr(a.inlinedTypes))}}};var Pao=class extends kq{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a,o=t.$ref.match(/^.*\/schemas\/(.+)$/),c=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),d=t.$ref.match(/^.*\/messages\/(.+)$/);if(o&&o[1])return a=o[1],this.convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a});if(c&&c[2]){let s=c[1],u=c[2];return a=`${s}_${u}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})}else return d&&d[1]?(a=d[1],this.convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})):{ok:!1}}convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.title??i),{ok:!0,reference:hi.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.name??i),{ok:!0,reference:hi.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.messageId??o.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.messageId??o.value.name??i),{ok:!0,reference:hi.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}};var RU_=ce(pIu(),1);var hIu=class extends Nl{document;key="x-fern-base-path";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-base-path",path:this.breadcrumbs});return}return t}}};var _Iu=class extends Nl{document;key="x-fern-global-headers";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-headers",path:this.breadcrumbs});return}return t}}};function DU_({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?Va.OPTIONAL_STRING:Va.STRING,env:r.env,v2Examples:r.optional?void 0:aWI({header:r,context:t}),availability:void 0,docs:void 0}))}function aWI({header:e,context:t}){let r=new NU({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:i}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:i}}}var yIu=class extends $A.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let i=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),a=new $A.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:i}).convert();a!=null&&(t=a.type,r=a.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var bIu=class extends $A.AbstractConverters.AbstractMediaTypeObjectConverter{contentType;mediaType;description;required;schemaId;streamingExtension;queryParameters;constructor({context:t,breadcrumbs:r,contentType:i,mediaType:n,description:a,required:o,group:c,method:d,streamingExtension:s,queryParameters:u}){super({context:t,breadcrumbs:r,group:c,method:d}),this.contentType=i,this.mediaType=n,this.description=a,this.required=o,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=s,this.queryParameters=u??[]}convert(){return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleStreamConditionJsonOrFormContent({contentType:this.contentType})}convertNonStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleJsonOrFormContent({contentType:this.contentType});if(iA.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=iA.parse(this.contentType);return t?t.isJSON()||t.isURLEncoded()||t.isPlainText()||t.isCSV()||t.isHTML()||t.isXML()||t.isDNS()||t.isApplicationText():!1}isBinaryContentType(){let t=iA.parse(this.contentType);return t?t.isBinary():!1}handleJsonOrFormContent({contentType:t}){let r=this.mediaType;if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;return n?.type==="object"?this.hasBodyQueryParameterOverlap(n.properties)?{requestBody:FA.reference({contentType:t,docs:this.description,requestBodyType:i.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i.inlinedTypes??{}}:{requestBody:FA.inlinedRequestBody({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:n.extendedProperties,extends:n.extends,properties:n.properties,extraProperties:n.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes})}:{requestBody:FA.reference({contentType:t,docs:this.description,requestBodyType:i.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i.inlinedTypes??{}}}handleMultipartContent({contentType:t}){let r=this.mediaType;if(r==null||r.schema==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,resolveSchema:!0,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;if(n?.type==="object")return{requestBody:FA.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:n.properties.map(a=>{let o=r.encoding?.[a.name.wireValue];return this.convertRequestBodyProperty({property:a,contentType:t,encoding:o})}),v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes}),examples:i.examples}}handleBinaryContent({contentType:t}){let r=this.mediaType;if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});return{requestBody:FA.bytes({contentType:t,isOptional:this.required===!1,docs:this.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i?.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r,encoding:i}){let{isFile:n,isOptional:a,isArray:o}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return n?o?dR.file(QZ.fileArray({key:t.name,isOptional:a,contentType:r,docs:t.docs})):dR.file(QZ.file({key:t.name,isOptional:a,contentType:r,docs:t.docs})):dR.bodyProperty({...t,contentType:i?.contentType??r,style:uWI({encoding:i}),name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.mediaType;if(r==null||r.schema==null)return;let i=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(i==null)return;let n=i.properties?.[this.streamingExtension.streamConditionProperty];if(n==null||this.context.isReferenceObject(n))return;let a=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!0,contentType:t,mediaTypeObject:r}),o=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(a==null||o==null))return{requestBody:o.requestBody,streamRequestBody:a.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...a.inlinedTypes,...o.inlinedTypes}})}}buildStreamConditionInlinedRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:i,contentType:n,mediaTypeObject:a}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let o={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{type:"boolean",const:i,...t}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},c={...a,schema:o},d=this.parseMediaTypeObject({mediaTypeObject:c,schemaId:this.schemaId,contentType:n});if(d==null)return;let s=d.schema?.typeDeclaration.shape;if(s?.type==="object")return{requestBody:FA.inlinedRequestBody({contentType:n,docs:void 0,name:this.context.casingsGenerator.generateName(i?`${this.schemaId}_streaming`:this.schemaId),extendedProperties:s.extendedProperties,extends:s.extends,properties:s.properties,extraProperties:s.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:c,exampleGenerationStrategy:"request"})}),inlinedTypes:d.inlinedTypes}}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:i}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:i}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:i}):{isFile:this.context.isFile(t),isOptional:r??!1,isArray:i??!1}}hasBodyQueryParameterOverlap(t){if(this.queryParameters.length===0)return!1;let r=new Set(this.queryParameters.map(i=>i.name.wireValue.toLowerCase()));return t.some(i=>r.has(i.name.wireValue.toLowerCase()))}},oWI={"application/json":"json"};function uWI({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return oWI[e.contentType]}}var sWI=/{([^}]+)}/g,cWI=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),Xya=class extends Va{operation;method;path;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r}),this.operation=i,this.method=n,this.path=a}convertHttpMethod(){switch(this.method){case"get":return EE.Get;case"post":return EE.Post;case"put":return EE.Put;case"delete":return EE.Delete;case"patch":return EE.Patch;case"head":return EE.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],i=[],n=[];if(!this.operation.parameters)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n};for(let a of this.operation.parameters){let o=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:t});if(o==null)continue;let d=new yIu({context:this.context,breadcrumbs:t,parameter:o}).convert();if(d!=null)switch(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},d.type){case"path":r.push(d.parameter);break;case"query":i.push(d.parameter);break;case"header":{let s=d.parameter.name.name.originalName,u=d.parameter.name.wireValue,f=!1,p=this.context.authOverrides?.["auth-schemes"];if(p!=null){for(let _ of Object.values(p))if(pWI(_)&&_.header.toLowerCase()===u.toLowerCase()){f=!0;break}}let h=this.context.globalHeaderNames;if(h!=null){for(let _ of h)if(_.toLowerCase()===u.toLowerCase()){f=!0;break}}!cWI.has(s.toLowerCase())&&!f&&n.push(d.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n}}checkMissingPathParameters(t){let i=[...this.path.matchAll(sWI)].map(n=>n[1]).filter(n=>!t.some(a=>a.name.originalName===n));for(let n of i){if(n==null)continue;let a=`${n}_example`;t.push({name:this.context.casingsGenerator.generateName(n),valueType:Va.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[a]:this.generateStringParameterExample({example:n})}},explode:void 0})}}convertRequestBody({breadcrumbs:t,group:r,method:i,streamingExtension:n,queryParameters:a}){if(this.operation.requestBody==null)return;let o=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(o==null)return null;let c=[];for(let[d,s]of Object.entries(o.content)){let f=new bIu({context:this.context,breadcrumbs:t,contentType:d,mediaType:s,description:o.description,required:o.required,group:r??[],method:i,streamingExtension:n,queryParameters:a}).convert();f!=null&&(this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes},c.push({requestBody:f.requestBody,streamRequestBody:f.streamRequestBody,examples:f.examples}))}return c}computeGroupNameAndLocationFromExtensions(){let r=new BN.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,n=new BN.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:n,method:r}}evaluateMethodNameFromOperation(){let t=this.operation.operationId;return t??(this.operation.summary!=null?An(this.operation.summary):An(`${this.method}_${this.path.split("/").join("_")}`))}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:r};let i=IU_(t),n=IU_(r);return EC(i,n)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,methodName:r,methodNameTokens:n})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:i,methodNameTokens:n}){if(r.some((c,d)=>c!==n[d]))return{group:[t],method:i};let o=n.slice(r.length);return{group:[t],method:An(o.join("_"))}}generateStringParameterExample({example:t}){let r=new $A.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:i}=r.convert();return i}};function IU_(e){let t=lWI(e)?fWI(e):dWI(e);return t=t.map(r=>r.toLowerCase()),t=$Me(t),t}function lWI(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function fWI(e){return e.split(/(?=[A-Z])/)}function dWI(e){return e.split(/[^a-zA-Z0-9]+/)}function pWI(e){return e?.header!=null}var Zya=class extends Xya{constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=[...this.breadcrumbs,"Payload"],{headers:a,queryParameters:o}=this.convertParameters({breadcrumbs:n}),c=this.convertRequestBody({breadcrumbs:n,group:r,method:i,streamingExtension:void 0,queryParameters:o});if(c==null)return;let d=c[0]?.requestBody;if(d==null)return;let s,u;if(d.type==="inlinedRequestBody")s=lU.inlinedPayload({name:d.name,extends:d.extends,properties:d.properties});else if(d.type==="reference")s=lU.reference({payloadType:d.requestBodyType,docs:d.docs});else if(d.type==="fileUpload")u={name:d.name,properties:d.properties,docs:d.docs,v2Examples:d.v2Examples,contentType:d.contentType},s=lU.inlinedPayload({name:d.name,extends:[],properties:[]});else return;let f=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,webhook:{id:`${r?.join(".")??""}.${i}`,name:this.context.casingsGenerator.generateName(i),displayName:this.operation.summary,method:t,headers:a,payload:s,fileUploadPayload:u,responses:f.length>0?f:void 0,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(d.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(d.v2Examples?.userSpecifiedExamples??{})}},inlinedTypes:this.inlinedTypes}}convertWebhookResponses(){let t=[];if(this.operation.responses==null)return t;for(let[r,i]of Object.entries(this.operation.responses)){let n=/^\d[Xx]{2}$/.test(r),a;if(n)a=parseInt(r.charAt(0))*100;else if(a=parseInt(r),isNaN(a))continue;let c=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[...this.breadcrumbs,"responses",r]})?.description;t.push({statusCode:a,isWildcardStatusCode:n?!0:void 0,body:void 0,docs:c})}return t}getWebhookV2ExamplesFromRequestBodyV2Examples(t){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,{name:r,payload:i}]))}};var Psl=ce(pIu(),1);var BU_=["get","post","put","delete","patch","head"];var vIu=class extends Nl{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}};var hWI=Bt.object({cursor:Bt.string(),next_cursor:Bt.string(),results:Bt.string()}),_WI=Bt.object({offset:Bt.string(),results:Bt.string(),step:Bt.string().optional(),"has-next-page":Bt.string().optional()}),msl=Bt.union([Bt.boolean(),hWI,_WI]);var Asl="$request.",gIu="$response.",OIu=class extends Nl{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:i,context:n}){super({breadcrumbs:t,context:n}),this.operation=r,this.document=i}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=msl.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let i=this.getExtensionValue(this.document);if(i==null)return;if(typeof i=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let n=msl.safeParse(i);if(!n.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${n.error.message}`,path:this.breadcrumbs});return}if(typeof n.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:n.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:kq.maybeTrimPrefix(r.cursor,Asl),nextCursor:kq.maybeTrimPrefix(r.next_cursor,gIu),results:kq.maybeTrimPrefix(r.results,gIu)};let i=t;return{type:"offset",offset:kq.maybeTrimPrefix(i.offset,Asl),results:kq.maybeTrimPrefix(i.results,gIu),step:i.step!=null?kq.maybeTrimPrefix(i.step,Asl):void 0,hasNextPage:i["has-next-page"]!=null?kq.maybeTrimPrefix(i["has-next-page"],gIu):void 0}}};var yWI="$request.",bWI=Bt.object({"stream-condition":Bt.string().optional(),format:Bt.enum(["sse","json"]).optional(),"stream-description":Bt.string().optional(),"response-stream":Bt.any(),response:Bt.any()}),vWI=Bt.union([Bt.boolean(),bWI]),mIu=class extends Nl{operation;key="x-fern-streaming";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=vWI.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json"}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",streamDescription:r.data["stream-description"],streamConditionProperty:kq.maybeTrimPrefix(r.data["stream-condition"],yWI),responseStream:r.data["response-stream"],response:r.data.response}}};var AIu=class extends Nl{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}};var jIu=require("fs"),CU_=require("path");function gWI(e){return Wl(e)&&typeof e.$ref=="string"}function OWI(e,t){if(e!=null){if(typeof e=="string")return e;if(gWI(e)){let r=(0,CU_.resolve)(t??process.cwd(),e.$ref);if((0,jIu.existsSync)(r))try{return(0,jIu.readFileSync)(r,"utf-8")}catch{return}}}}var PIu=class extends Nl{operation;baseDir;key="x-codeSamples";constructor({context:t,breadcrumbs:r,operation:i,baseDir:n}){super({breadcrumbs:r,context:t}),this.operation=i,this.baseDir=n}convert(){let t=Wl(this.operation)?this.operation:{},r=t["x-codeSamples"],i=t["x-code-samples"],n=Array.isArray(r)?r:[],a=Array.isArray(i)?i:[],o=[...n,...a];if(o.length===0)return;let c=[];for(let d of o){if(!Wl(d))continue;let s=d,u=s.lang,f=s.label,p=s.source;if(typeof u!="string")continue;let h=OWI(p,this.baseDir);h!=null&&c.push({name:typeof f=="string"?f:u,language:u,code:h,install:void 0,docs:void 0})}if(c.length!==0)return[{"code-samples":c}]}};var EIu=require("fs"),qU_=require("path");function mWI(e){return Wl(e)&&typeof e.$ref=="string"}function AWI(e,t){if(e!=null){if(typeof e=="string")return e;if(mWI(e)){let r=(0,qU_.resolve)(t??process.cwd(),e.$ref);if((0,EIu.existsSync)(r))try{return(0,EIu.readFileSync)(r,"utf-8")}catch{return}}}}function PWI(e,t){if(!Array.isArray(e))return[];let r=[];for(let i of e){if(!Wl(i))continue;let a=AWI(i.code,t);a!=null&&r.push({...i,code:a})}return r}var wIu=class extends Nl{operation;baseDir;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:i,baseDir:n}){super({breadcrumbs:r,context:t}),this.operation=i,this.baseDir=n}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).map(a=>{if(!Wl(a))return a;let c=a["code-samples"];if(c!=null){let d=PWI(c,this.baseDir);return{...a,"code-samples":d}}return a}).filter(a=>{let o=TC.serialization.ExampleEndpointCallSchema.parse(a);return o.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),o.ok})}};var jao=class extends Nl{document;key="x-fern-explorer";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}};var wao=class extends $A.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:i,group:n,method:a,statusCode:o,streamingExtension:c}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseBody=i,this.statusCode=o,this.streamingExtension=c}convert(){return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,i=[...this.group,this.method,"Response",this.statusCode].join("_"),n=`${i}_streaming`,a=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:n}),o=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:i});return this.convertStreamConditionResponse({convertedStreamingSchema:a,convertedNonStreamingSchema:o})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{});for(let i of r){let n=this.responseBody.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:t,contentType:this.streamingExtension.format});if(a!=null)return this.convertStreamingResponse({mediaTypeObject:n,convertedSchema:a})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(a=>a.includes("json"));for(let a of r){let o=this.responseBody.content?.[a];if(o==null)continue;let c=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:a});if(c!=null&&this.shouldReturnJsonResponse(a))return this.returnJsonResponse({mediaTypeObject:o,convertedSchema:c})}let i=Object.keys(this.responseBody.content??{}).filter(a=>!a.includes("json"));for(let a of i){let o=this.responseBody.content?.[a];if(o==null)continue;let c=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:a});if(c!=null){if(this.isBinarySchema(c))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:o}):this.returnFileDownloadResponse({mediaTypeObject:o});if(this.shouldReturnTextResponse(a))return this.returnTextResponse({mediaTypeObject:o})}}let n=parseInt(this.statusCode);if(!isNaN(n)&&n>=200&&n<300){let a={schema:{type:"object",description:"Empty response body"}},o=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:t,contentType:"application/json",resolveSchema:!0});if(o!=null)return this.returnJsonResponse({mediaTypeObject:a,convertedSchema:o})}}convertStreamConditionResponse({convertedStreamingSchema:t,convertedNonStreamingSchema:r}){if(t==null||r==null)return;let i=this.responseBody.description;return this.streamingExtension?.type==="streamCondition"&&this.streamingExtension.streamDescription!=null&&(i=this.streamingExtension.streamDescription),{responseBody:np.json(Lq.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:np.streaming(RC.json({docs:i,payload:t.type,terminator:void 0,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes},headers:this.convertResponseHeaders()}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:np.streaming(RC.json({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()};case"sse":return{responseBody:np.streaming(RC.sse({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:np.json(Lq.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:np.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:np.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}returnTextResponse({mediaTypeObject:t}){return{responseBody:np.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return iA.parse(t)?.isText()??!1}convertResponseHeaders(){let t=[],r=this.responseBody.headers;if(r==null)return t;for(let[i,n]of Object.entries(r)){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"headers",i]});if(a==null)continue;let o=a.schema,c=Va.OPTIONAL_STRING;if(o!=null){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,"headers",i,"schema"]});s!=null&&(s.type==="number"||s.type==="integer"?c=hi.primitive({v1:s.type==="integer"?"INTEGER":"DOUBLE",v2:s.type==="integer"?Cn.integer({default:void 0,validation:void 0}):Cn.double({default:void 0,validation:void 0})}):s.type==="boolean"&&(c=hi.primitive({v1:"BOOLEAN",v2:Cn.boolean({default:void 0})})))}let d=this.convertHeaderExamples({header:a,headerName:i,schema:o});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:i,wireValue:i}),docs:a.description,valueType:c,env:void 0,v2Examples:d,availability:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t.example,o=t.examples;for(let[c,d]of Object.entries(o??{})){let s=this.context.resolveExampleWithValue(d);s!=null&&(n.userSpecifiedExamples[c]=this.generateHeaderExample({schema:i,example:s}))}if(a!=null){let c=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[c]=this.generateHeaderExample({schema:i,example:a})}if(Object.keys(n.userSpecifiedExamples).length===0&&i!=null){let c=`${r}_example`;n.autogeneratedExamples[c]=this.generateHeaderExample({schema:i,example:void 0,ignoreErrors:!0})}return n}generateHeaderExample({schema:t,example:r,ignoreErrors:i}){if(t==null)return r;let n=new NU({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:a,errors:o}=n.convert();return i||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}};var SIu=class extends $A.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;constructor({context:t,breadcrumbs:r,responseError:i,group:n,method:a,methodName:o,statusCode:c,isWildcardStatusCode:d}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseError=i,this.statusCode=c,this.methodName=o,this.isWildcardStatusCode=d}convert(){if(!this.responseError.content){let i=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(i==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let n=this.getErrorIdFromErrorName(i);return{error:{error:{name:this.context.casingsGenerator.generateName(n),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:n},docs:this.responseError.description},errorType:hi.unknown(),displayName:i,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:{},examples:{},headers:this.convertResponseHeaders()}}let t=Object.keys(this.responseError.content).filter(i=>i.includes("json")),r=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let i of[...t]){let n=this.responseError.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:TU_(`${this.methodName}Request${r}`),contentType:i});if(a==null)continue;let o=this.getErrorIdFromErrorName(r);if(a.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:o,fernFilepath:a.schema.typeDeclaration.name.fernFilepath,convertedSchema:a,mediaTypeObject:n});if(a.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:o,fernFilepath:a.type.fernFilepath,convertedSchema:a,mediaTypeObject:n})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:i,convertedSchema:n,mediaTypeObject:a}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:i,errorId:r},docs:this.responseError.description},errorType:n.type,displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:n.inlinedTypes,examples:this.convertErrorExamples({mediaTypeObject:a}),headers:this.convertResponseHeaders()}}convertErrorExamples({mediaTypeObject:t}){let r=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_error_example`});if(r.length===0)return;let i=new Set,n={};for(let[a,o]of r){let c=this.context.resolveExampleWithValue(o),d=this.context.resolveExampleRecursively({example:o,breadcrumbs:this.breadcrumbs}),s=this.getIdForErrorExample({key:a,example:d,usedExampleNames:i});i.add(s),c!=null&&(n[s]=c)}return Object.keys(n).length>0?n:void 0}getIdForErrorExample({key:t,example:r,usedExampleNames:i}){if(this.context.isExampleWithSummary(r)){let n=r.summary;if(!i.has(n))return n;let a=`${n} (${t})`;return i.has(a)?t:a}return t}getErrorNameForStatusCode(t,r){if(r){if(t===400)return"ClientRequestError";if(t===500)return"ServerError"}return oIu[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?TU_(`${this.methodName}Request${t}`):t}convertResponseHeaders(){let t=[],r=this.responseError.headers;if(r==null)return t;for(let[i,n]of Object.entries(r)){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"headers",i]});if(a==null)continue;let o=a.schema,c=Va.OPTIONAL_STRING;if(o!=null){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,"headers",i,"schema"]});s!=null&&(s.type==="number"||s.type==="integer"?c=hi.primitive({v1:s.type==="integer"?"INTEGER":"DOUBLE",v2:s.type==="integer"?Cn.integer({default:void 0,validation:void 0}):Cn.double({default:void 0,validation:void 0})}):s.type==="boolean"&&(c=hi.primitive({v1:"BOOLEAN",v2:Cn.boolean({default:void 0})})))}let d=this.convertHeaderExamples({header:a,headerName:i,schema:o});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:i,wireValue:i}),docs:a.description,valueType:c,env:void 0,v2Examples:d,availability:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t.example,o=t.examples;for(let[c,d]of Object.entries(o??{})){let s=this.context.resolveExampleWithValue(d);s!=null&&(n.userSpecifiedExamples[c]=this.generateHeaderExample({schema:i,example:s}))}if(a!=null){let c=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[c]=this.generateHeaderExample({schema:i,example:a})}if(Object.keys(n.userSpecifiedExamples).length===0&&i!=null){let c=`${r}_example`;n.autogeneratedExamples[c]=this.generateHeaderExample({schema:i,example:void 0,ignoreErrors:!0})}return n}generateHeaderExample({schema:t,example:r,ignoreErrors:i}){if(t==null)return r;let n=new NU({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:a,errors:o}=n.convert();return i||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}};function TU_(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var MIu=class e extends Xya{idempotent;idToAuthScheme;topLevelServers;pathLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a,idempotent:o,idToAuthScheme:c,topLevelServers:d,pathLevelServers:s,streamingExtension:u}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a}),this.idempotent=o,this.idToAuthScheme=c,this.topLevelServers=d,this.pathLevelServers=s,this.streamingExtension=u}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=this.getGroupDisplayName(r),{headers:a,pathParameters:o,queryParameters:c}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),d=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:i,streamingExtension:this.streamingExtension,queryParameters:c}),s=d?.[0]?.requestBody,u=d?.[0]?.streamRequestBody,f={requestBodies:d?.map(W=>W.requestBody)},p=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:i,streamingExtension:this.streamingExtension}),h=p?.response,_=p?.streamResponse,y=p!=null?p.errors:[],b={},v=y.map(W=>W.error),O=eI(this.path),m=this.getEndpointBaseUrl(),g=this.getEndpointBaseUrls(),A=this.convertExamples({httpPath:O,httpMethod:t,baseUrl:m}),j=new Set(this.operation.security?.flatMap(W=>Object.keys(W))??[]),S=this.authSchemeToHeaders(Array.from(j));S.length>0&&a.push(...S);for(let W of y){let Oe=W.error,Ae=W.errorType,L=Oe.error.errorId,Q=W.examples;b[L]={name:Oe.error,displayName:W.displayName,discriminantValue:{name:Oe.error.name,wireValue:L},type:Ae,statusCode:W.statusCode,isWildcardStatusCode:W.isWildcardStatusCode,docs:Oe.docs,examples:[],v2Examples:{userSpecifiedExamples:Q??{},autogeneratedExamples:{}},headers:W.headers}}let w=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],I=new jao({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),T=new jao({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??I,K={displayName:this.operation.summary,method:t,baseUrl:m,v2BaseUrls:g,path:O,pathParameters:o,queryParameters:c,headers:a.filter((W,Oe,Ae)=>Oe===Ae.findIndex(L=>L.name.wireValue===W.name.wireValue)),responseHeaders:p?.responseHeaders,sdkRequest:void 0,errors:v,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:O,allPathParameters:o,pagination:void 0,transport:void 0,source:j5.openapi(),audiences:w,retries:void 0,apiPlayground:T},G=this.context.namespace!=null?[this.context.namespace]:[],z=r?.map(W=>An(W));return G.push(...z??[]),{audiences:w,group:r,groupDisplayName:n,errors:b,endpoint:{...K,id:`endpoint_${G.join("/")}.${i}`,name:this.context.casingsGenerator.generateName(i),requestBody:s,v2RequestBodies:f,response:h,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:A.examples},v2Responses:{responses:p?.v2Responses}},streamEndpoint:_!=null&&_.body!=null?{...K,id:`endpoint_${G.join("/")}.${i}_stream`,name:this.context.casingsGenerator.generateName(`${i}_stream`),requestBody:u,v2RequestBodies:void 0,response:_,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:A.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:_.body,docs:_.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[])}}convertResponseBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.responses==null)return;let a,o=!1;for(let[c,d]of Object.entries(this.operation.responses)){let s=/^[45]XX$/i.test(c),u,f=!1;if(s)u=parseInt(c.charAt(0))*100,f=!0;else{if(u=parseInt(c),isNaN(u)||u<200||u>=300&&u<400)continue;f=u>=400&&u<600}if(a==null&&(a={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]}),u>=200&&u<300){let p=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,c]});if(p==null)continue;let _=new wao({context:this.context,breadcrumbs:[...t,c],responseBody:p,group:r??[],method:i,statusCode:c,streamingExtension:n}).convert();_!=null&&(this.inlinedTypes={...this.inlinedTypes,..._.inlinedTypes},o||(o=!0,a.response={statusCode:u,isWildcardStatusCode:s?!0:void 0,body:_.responseBody,docs:p.description},a.streamResponse={statusCode:u,isWildcardStatusCode:s?!0:void 0,body:_.streamResponseBody,docs:p.description},_.headers!=null&&(a.responseHeaders=_.headers)),a.v2Responses=[...a.v2Responses??[],{statusCode:u,isWildcardStatusCode:s?!0:void 0,body:_.responseBody,docs:p.description}])}if(f){let p=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,c]});if(p==null)continue;let _=new SIu({context:this.context,breadcrumbs:[...t,c],responseError:p,group:r??[],method:i,methodName:this.evaluateMethodNameFromOperation(),statusCode:u,isWildcardStatusCode:s?!0:void 0}).convert();_!=null&&(this.inlinedTypes={...this.inlinedTypes,..._.inlinedTypes},a.errors.push(_))}}if(this.streamingExtension!=null){a==null&&(a={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]});let d=new wao({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:i,statusCode:"stream",streamingExtension:n}).convert();d!=null&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},a.response={statusCode:200,isWildcardStatusCode:void 0,body:d.responseBody,docs:void 0},a.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:d.streamResponseBody,docs:void 0},a.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:d.responseBody,docs:void 0}])}return a}computeEndpointAuth(){return this.operation.security!=null&&this.operation.security.length===0?!1:this.operation.security!=null&&this.operation.security.length>0?!0:this.context.spec.security!=null&&this.context.spec.security.length>0||this.shouldApplyDefaultAuthOverrides()}computeEndpointSecurity(){return this.operation.security!=null&&this.operation.security.length===0?[]:this.context.authOverrides?.auth!=null?this.getDefaultSecurityFromAuthOverrides():this.operation.security??this.context.spec.security}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth)return!1;let t=this.context.spec.security!=null&&this.context.spec.security.length>0,r=this.operation.security!=null&&this.operation.security.length>0;return!(t||r)}getDefaultSecurityFromAuthOverrides(){if(!this.context.authOverrides?.auth)return;let t=this.context.authOverrides.auth;if(typeof t=="string"){let r={};return r[t]=[],[r]}if(typeof t=="object"&&"any"in t){let r=t.any;if(Array.isArray(r))return r.map(i=>{let n=typeof i=="string"?i:i.scheme,a={};return a[n]=[],a})}}authSchemeToHeaders(t){let r=[];for(let i of t){let n=this.idToAuthScheme?.[i];if(n==null)continue;let a={valueType:Va.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0};switch(n.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"header":r.push({name:n.name,...a});break}}return r}convertExamples({httpPath:t,httpMethod:r,baseUrl:i}){let a=new wIu({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],c=new PIu({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],s=a.some(u=>Array.isArray(u["code-samples"])&&u["code-samples"].length>0)?a:[...a,...c];return s.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:s}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:s}),streamExamples:{}}}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){let a=n.filter(s=>!(s.response!=null&&"stream"in s.response)),o=n.filter(s=>s.response!=null&&"stream"in s.response),c=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:a}),d=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:o});return{examples:c,streamExamples:d}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){return Object.fromEntries(n.map((a,o)=>[this.getExampleName({example:a,exampleIndex:o}),{displayName:void 0,request:a.request!=null||a["path-parameters"]!=null||a["query-parameters"]!=null||a.headers!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,a["path-parameters"]??{})},baseUrl:void 0,environment:i,auth:void 0,pathParameters:a["path-parameters"]??{},queryParameters:a["query-parameters"]??{},headers:a.headers??{},requestBody:a.request??void 0}:void 0,response:a.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:a})}:void 0,codeSamples:a["code-samples"]?.map(c=>{let d=("language"in c?c.language:c.sdk)??void 0;return{name:c.name,docs:void 0,language:d,code:c.code}})}]))}getExampleName({example:t,exampleIndex:r}){return t.name??t["code-samples"]?.[0]?.name??`Example_${r}`}getExampleResponseBody({example:t}){if(t.response!=null){if("stream"in t.response)return Ir.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return Ir.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new BN.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert();if(r!=null)return this.context.logger.debug(`[getEndpointBaseUrl] Endpoint ${this.method.toUpperCase()} ${this.path} specifies a server with "${nn.SERVER_NAME_V2}" extension. Returning server type: ${r}`),r;let i=this.operation.servers?.[0]??this.pathLevelServers?.[0];if(i==null)return;let a=this.topLevelServers?.find(o=>o.url===i.url)??i;return vAe.getServerName({server:a,context:this.context})}getEndpointBaseUrls(){let t=this.operation.servers??this.pathLevelServers;return t?.map(i=>{let a=this.topLevelServers?.find(o=>o.url===i.url)??i;return vAe.getServerName({server:a,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(i=>`${r[i.pathParameter]?.toString()??i.pathParameter}${i.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(i=>i.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0];r!=null&&(r=this.context.getDisplayNameForTag(r));let i=t?.[t.length-1];if(i!=null&&r!=null)return r.toLowerCase().replaceAll(" ","")===i?r:void 0}};var DIu=class extends Va{pathItem;path;idToAuthScheme;topLevelServers;constructor({context:t,breadcrumbs:r,pathItem:i,path:n,idToAuthScheme:a,topLevelServers:o}){super({context:t,breadcrumbs:r}),this.pathItem=i,this.path=n,this.idToAuthScheme=a,this.topLevelServers=o}convert(){let t=[],r=[],i={};for(let n of BU_){let a=this.pathItem[n];if(a==null)continue;let o=[...this.breadcrumbs,n],c=this.tryParseAsWebhook({operationBreadcrumbs:o,operation:a,method:n,context:this.context});if(c!=null){r.push(c),Object.assign(i,c.inlinedTypes);continue}let s=new mIu({breadcrumbs:o,operation:a,context:this.context}).convert(),u=this.tryParseAsHttpEndpoint({operationBreadcrumbs:o,operation:a,method:n,streamingExtension:s});u!=null&&(t.push(u),Object.assign(i,u.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:i}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:i,context:n}){return new AIu({breadcrumbs:i,operation:t,context:n}).convert()?new Zya({context:this.context,breadcrumbs:i,operation:t,method:Psl.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:i,streamingExtension:n}){new OIu({breadcrumbs:i,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let d=new vIu({breadcrumbs:i,operation:t,context:this.context}).convert();return new MIu({context:this.context,breadcrumbs:i,operation:t,method:Psl.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:n}).convert()}};var IIu=class extends Va{securityScheme;schemeId;constructor({context:t,breadcrumbs:r,securityScheme:i,schemeId:n}){super({context:t,breadcrumbs:r}),this.securityScheme=i,this.schemeId=n}getExtension(t){return this.securityScheme[t]}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme?.toLowerCase()==="bearer"){let t=this.getExtension("x-fern-bearer"),r=t?.name??"token",i=t?.env;return AP.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName(r),tokenEnvVar:i,docs:this.securityScheme.description})}if(this.securityScheme.scheme?.toLowerCase()==="basic"){let t=this.getExtension("x-fern-basic"),r=t?.username?.name??"username",i=t?.password?.name??"password",n=t?.username?.env,a=t?.password?.env;return AP.basic({key:this.schemeId,username:this.context.casingsGenerator.generateName(r),password:this.context.casingsGenerator.generateName(i),usernameEnvVar:n,passwordEnvVar:a,usernameOmit:!1,passwordOmit:!1,docs:this.securityScheme.description})}break}case"apiKey":{if(this.securityScheme.in==="header"){let t=this.getExtension("x-fern-header"),r=t?.name??"apiKey",i=t?.env,n=t?.prefix;return AP.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(r),wireValue:this.securityScheme.name},valueType:Va.OPTIONAL_STRING,prefix:n,headerEnvVar:i,docs:this.securityScheme.description})}break}case"oauth2":return AP.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var Eao=class extends jHt{constructor({breadcrumbs:t,context:r,audiences:i}){super({breadcrumbs:t,context:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertBasePath(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:t,errors:r}=this.convertPaths();this.addErrorsToIr(r);let{defaultUrl:i}=this.convertServers({endpointLevelServers:t});this.updateEndpointsWithDefaultUrl(i);let n=this.context.spec.info?.title?.trim();return n&&n!=='""'&&(this.ir.apiDisplayName=n),this.finalizeIr()}convertGlobalHeaders(){this.context.globalHeaderOverrides;let r=new _Iu({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let i=DU_({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(i),this.context.setGlobalHeaders(i)}}convertBasePath(){let r=new hIu({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();r!=null&&(this.ir.basePath=eI(r))}convertSecuritySchemes(){if(this.context.authOverrides){let r=Xnl({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertOpenApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertOpenApiSecuritySchemes(){let t=[];for(let[r,i]of Object.entries(this.context.spec.components?.securitySchemes??{})){let n=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:["components","securitySchemes",r]});if(n==null)continue;let o=new IIu({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:n,schemeId:r}).convert();o!=null&&t.push(o)}return t}convertServers({endpointLevelServers:t}){if(this.context.environmentOverrides){let n=ano({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return n!=null&&this.addEnvironmentsToIr({environmentConfig:n.environmentsConfig,audiences:n.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let i=new vAe({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new $A.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&this.addSchemaOutputToIr(t,n)}}convertWebhooks(){for(let[,t]of Object.entries(this.context.spec.webhooks??{})){if(t==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});continue}if(!("post"in t)){this.context.errorCollector.collect({message:"Skipping webhook as it is not a POST method",path:this.breadcrumbs});continue}if(t.post?.operationId==null){this.context.errorCollector.collect({message:"Skipping webhook as no operationId is present",path:this.breadcrumbs});continue}let r=t.post.operationId,n=new Zya({context:this.context,breadcrumbs:["webhooks",r],operation:t.post,method:RU_.OpenAPIV3.HttpMethods.POST,path:r}).convert();n!=null&&(this.addWebhookToIr({webhook:n.webhook,operationId:r,audiences:n.audiences,group:n.group}),this.addTypesToIr(n.inlinedTypes))}}convertPaths(){let t=[],r={};for(let[i,n]of Object.entries(this.context.spec.paths??{})){if(n==null)continue;let o=new DIu({context:this.context,breadcrumbs:["paths",i],topLevelServers:this.context.spec.servers,pathItem:n,path:i}).convert();if(o!=null){for(let c of o.endpoints){if(c.streamEndpoint!=null&&this.addEndpointToIr({endpoint:c.streamEndpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName}),this.addEndpointToIr({endpoint:c.endpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName}),c.servers)for(let d of c.servers)this.shouldAddServerToCollectedServers({server:d,currentServers:t})&&t.push(d);if(c.errors)for(let[d,s]of Object.entries(c.errors))r[d]=s}for(let c of o.webhooks){let d=this.context.getGroup({groupParts:c.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:c.webhook,operationId:d.join("."),group:d,audiences:c.audiences})}this.addTypesToIr(o.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;this.context.spec.components||(this.context.spec.components={}),this.context.spec.components.securitySchemes={};let t={};for(let r of Object.keys(this.context.authOverrides["auth-schemes"]))this.context.spec.components.securitySchemes[r]={type:"http",scheme:"bearer"},t[r]=[];this.context.spec.security=[t],this.removeEndpointSpecificAuth()}removeEndpointSpecificAuth(){if(this.context.spec.paths)for(let t of Object.values(this.context.spec.paths)){if(!t)continue;let r=["get","post","put","patch","delete","options","head","trace"];for(let i of r){let n=t[i];n?.security&&delete n.security}}}};var BIu=class extends Nl{tag;key="x-displayName";constructor({breadcrumbs:t,tag:r,context:i}){super({breadcrumbs:t,context:i}),this.tag=r}convert(){if(typeof this.tag!="object"||this.tag==null)return;let t=this.tag[this.key];if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"x-displayName extension must be a string",path:this.breadcrumbs});return}if(t.trim().length!==0)return{displayName:t}}}};var g8i=class extends kq{globalHeaderNames;tagToDisplayName={};isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;n==="reference_identifier"?c=i??o.value.title:n==="discriminator_key"?c=o.value.title??i:n==="schema_identifier"&&(c=o.value.title);let d;if(a.includes("/")){let u=new $A.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:o.value,id:a}).convert();u!=null&&(d={[a]:u.convertedSchema})}return{ok:!0,reference:hi.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,default:void 0,inline:!1,displayName:c}),inlinedTypes:d}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>r.name.wireValue)}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let n=new BIu({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName??r.name;this.tagToDisplayName[r.name]=n}return this.tagToDisplayName[t]??t}};var jWI=Bt.object({description:Bt.string().optional(),required:Bt.boolean().optional(),deprecated:Bt.boolean().optional(),allowEmptyValue:Bt.boolean().optional(),style:Bt.string().optional(),explode:Bt.boolean().optional(),allowReserved:Bt.boolean().optional(),schema:Bt.any().optional(),example:Bt.any().optional(),examples:Bt.record(Bt.string(),Bt.any()).optional(),content:Bt.record(Bt.string(),Bt.any()).optional()}),wWI=jWI.extend({name:Bt.string(),in:Bt.string()}),EWI=Bt.array(wWI),CIu=class extends Nl{operation;key="x-fern-parameters";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null)try{return EWI.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${r instanceof Error?r.message:String(r)}`,path:this.breadcrumbs});return}}};var qIu=class extends Va{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:i,pathParameters:n=[],queryParameters:a=[],headers:o=[],topLevelServers:c=[]}){super({context:t,breadcrumbs:r}),this.method=i,this.pathParameters=n,this.queryParameters=a,this.headers=o,this.topLevelServers=c}convert(){let t={},r="";for(let s of this.pathParameters)r+=`/{${s.name.originalName}}`;let i=eI(r),n=[];for(let[s,u]of this.method.params.entries()){let f;if(this.context.isReferenceObject(u)){let y=this.context.resolveReference({reference:u});if(y.resolved)f=y.value;else continue}else f=u;let p=[this.method.name,"Param",f.name].join("_"),_=new $A.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",f.name],schemaIdOverride:p,context:this.context,schemaOrReference:f.schema,wrapAsOptional:!f.required}).convert();_!=null&&(n.push({docs:f.description,availability:this.context.getAvailability({node:u,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:f.name,wireValue:f.name}),valueType:_.type,v2Examples:_.schema?.typeDeclaration.v2Examples,propertyAccess:void 0}),t={..._.inlinedTypes,...t,..._.schema!=null?{[p]:_.schema}:{}})}let a;if(this.method.result!=null){let s=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(s!=null){let u=new $A.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:s.schema}),f=[this.method.name,"Result"].join("_"),p=u.convert();p!=null&&(a={docs:s.description,v2Examples:p.schema?.typeDeclaration.v2Examples,responseBodyType:p.type},t={...p.inlinedTypes,...t,...p.schema!=null?{[f]:p.schema}:{}})}}let o=this.getEndpointBaseUrls(),c=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:o,basePath:void 0,auth:!1,security:void 0,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:i,fullPath:i,requestBody:n.length>0?FA.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:n,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,v2RequestBodies:void 0,sdkRequest:void 0,response:a!=null?{body:np.json(Lq.response(a)),statusCode:void 0,isWildcardStatusCode:void 0,docs:a.docs}:void 0,v2Responses:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples()},transport:void 0,availability:void 0,source:j5.openrpc(),audiences:c,retries:void 0,apiPlayground:void 0,responseHeaders:[]},audiences:c,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(i=>i.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(i=>{if(this.topLevelServers.find(c=>c.name===i.name&&c.url!==i.url)!=null)return i.url;let o=this.topLevelServers.find(c=>c.url===i.url)??i;return vAe.getServerName({server:o,context:this.context})})}convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let i of this.method.examples??[]){let n;if(this.context.isReferenceObject(i)){let d=this.context.resolveReference({reference:i});if(d.resolved)n=d.value;else continue}else n=i;let a;if(n.result)if(this.context.isReferenceObject(n.result)){let d=this.context.resolveReference({reference:n.result});d.resolved&&(a=d.value)}else a=n.result;let o=n.name??`Example ${r+1}`,c=[];if(n.params&&Array.isArray(n.params)){c=[];for(let d of n.params)if(this.context.isReferenceObject(d)){let s=this.context.resolveReference({reference:d});if(s.resolved)c.push(s.value);else continue}else c.push(d)}t[o]={displayName:void 0,request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:c.map(d=>d.value)??void 0},response:{docs:void 0,statusCode:void 0,body:a?.value?Ir.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:n.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++r}return t}};var TIu=class extends $A.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let n=new $A.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();n!=null&&(t=n.type,r=n.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var Sao=class extends jHt{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.convertSchemas();let{endpointLevelServers:t}=this.convertMethods(),{defaultUrl:r}=this.convertServers({endpointLevelServers:t});return this.updateEndpointsWithDefaultUrl(r),this.finalizeIr()}convertServers({endpointLevelServers:t}){let i=new vAe({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new $A.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&this.addSchemaOutputToIr(t,n)}}convertMethods(){let t=[],i=new CIu({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),n=[],a=[],o=[];if(i&&i.length>0)for(let[d,s]of i.entries()){let f=new TIu({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${d}]`],parameter:s}).convert();if(f!=null)switch(f.type){case"path":{n.push(f.parameter);break}case"query":{a.push(f.parameter);break}case"header":{o.push(f.parameter);break}}}let c=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let d of this.context.spec.methods??[]){let s=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:["methods"]});if(s==null)continue;let f=new qIu({context:this.context,breadcrumbs:["methods"],method:s,pathParameters:n,queryParameters:a,headers:o,topLevelServers:this.context.spec.servers}).convert();if(f!=null&&(this.addEndpointToIr({endpoint:f.endpoint,audiences:f.audiences,endpointGroup:c,serviceName:"service_root"}),this.addTypesToIr(f.inlinedTypes),f.servers))for(let p of f.servers)this.shouldAddServerToCollectedServers({server:p,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(p))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(i=>i.name===t.name&&i.url!==t.url)?{...t,name:t.url}:t}};var Mao=class extends kq{isReferenceObject(t){return t!=null&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.title??i),{ok:!0,reference:hi.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}};var Y3_=require("fs/promises");var zU_={[Ki.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,xf(e)])),[Ki.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[Ki.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[Ki.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all","kwargs"]),[Ki.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","vendor","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[Ki.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime","object_id","hash","eql?","equal?","method","send","respond_to?","respond_to_missing?","instance_of?","kind_of?","is_a?","extend","singleton_class","instance_variables","instance_variable_get","instance_variable_set","instance_variable_defined?","remove_instance_variable","public_methods","private_methods","protected_methods","singleton_methods"]),[Ki.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[Ki.GenerationLanguage.RUST]:new Set(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","union","unsafe","use","where","while","abstract","become","box","do","final","macro","override","priv","try","typeof","unsized","virtual","yield","bool","char","f32","f64","i8","i16","i32","i64","i128","isize","str","u8","u16","u32","u64","u128","usize","String","Vec","Option","Result","Box","Rc","Arc","Cell","RefCell","HashMap","HashSet","BTreeMap","BTreeSet"]),[Ki.GenerationLanguage.SWIFT]:new Set([])};var SWI=["go","ruby"];function NIu({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let o=zWI(n),c=p=>({unsafeName:p,safeName:MWI({name:p,keywords:DWI({generationLanguage:e,keywords:t})})}),d=An(o),s=xf(d),u=l2t(o),f=gmn(d);return r&&(!CWI(f)&&(e==null||SWI.includes(e))&&(d=f.map((p,h)=>{if(h>0){let _=RIu(p);if(_!=null)return _;if(zIu(p))return p.toUpperCase()}return p}).join(""),s=xf(f.map((p,h)=>{let _=RIu(p);return _??(zIu(p)?p.toUpperCase():h===0?xf(p):p)}).join(""))),u=o.split(" ").map(p=>p.split(/(\d+)/).map(l2t).join("")).join("_")),{originalName:n,camelCase:c(a?.casingOverrides?.camel??d),snakeCase:c(a?.casingOverrides?.snake??u),screamingSnakeCase:c(a?.casingOverrides?.["screaming-snake"]??u.toUpperCase()),pascalCase:c(a?.casingOverrides?.pascal??s)}},generateNameAndWireValue:({name:n,wireValue:a,opts:o})=>({name:i.generateName(n,o),wireValue:a})};return i}function MWI({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":BWI(e)?"_"+e:e}function DWI({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return zU_[e]}var IWI=/^[0-9]/;function BWI(e){return IWI.test(e)}function CWI(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=RIu(i)!=null||zIu(i),a=RIu(t)!=null||zIu(t);return n&&a})}function RIu(e){return TWI.get(e.toUpperCase())}function zIu(e){return qWI.has(e.toUpperCase())}var qWI=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),TWI=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]),RWI=[[/\[\]/g,"Array"]];function zWI(e){return RWI.reduce((t,[r,i])=>t.replace(r,i),e)}var NU_=require("fs/promises");async function jsl({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,NU_.readFile)(t)).toString(),n;try{n=JSON.parse(i)}catch{n=Mi.load(i)}return r!=null?await Wya({absoluteFilePathToOverrides:r,context:e,data:n}):n}var f4_=ce(l4_(),1);function ner(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...o}={}){let c=n.reduce((s,u)=>({...s,[u]:"<redacted>"}),a),d=[t,...r].join(" ");for(let[s,u]of Object.entries(c))d=d.replaceAll(s,u);return e?.debug(`+ ${d}`),(0,f4_.default)(t,r,o)}async function Q_(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...o}={}){let c=ner(e,t,r,{doNotPipeOutput:i,secrets:n,substitutions:a,...o});i||(c.stdout?.pipe(process.stdout),c.stderr?.pipe(process.stderr));let d=await c;return d.stdout==null&&(d.stdout=""),d.stderr==null&&(d.stderr=""),d}function Cen(e,{logger:t,...r}={}){return(i,n)=>Q_(t,e,i,{...r,...n})}var k7=require("fs/promises"),m4_=ce(require("path"),1),Wsl=ce(GQ(),1);var Twn=require("fs/promises"),d4_=ce(GQ(),1);function Tao(e){return e.includes("server hosted at that remote is unavailable")||e.includes("fetch failed")||e.includes("failed to connect")||e.includes("network")||e.includes("ENOTFOUND")||e.includes("ETIMEDOUT")||e.includes("TIMEDOUT")||e.includes("timed out")||e.includes("ECONNREFUSED")||e.includes("ECONNRESET")||e.includes("socket hang up")}var qao,Lsl;async function Vsl(e,t,r=5e3){return qao!==void 0?qao:(Lsl==null&&(Lsl=DxI(e,t,r)),Lsl)}async function DxI(e,t,r){t.debug(`Detecting air-gapped mode by checking connectivity to ${e}`);try{return await fetch(e,{method:"GET",signal:AbortSignal.timeout(r)}),qao=!1,t.debug("Network check succeeded - not in air-gapped mode"),!1}catch(i){let n=i instanceof Error?i.message:String(i);return Tao(n)?(qao=!0,t.debug(`Network check failed - entering air-gapped mode: ${n}`),!0):(qao=!1,!1)}}async function HIu(e,t){let r=ut(e,me.of("buf.lock")),i=!1;try{await(0,Twn.access)(r),i=!0,t.debug(`Found buf.lock at: ${r}`)}catch{t.debug(`No buf.lock found at: ${r}`)}if(!i)return!1;let n=vr.of((await d4_.default.dir()).path);try{let a=ut(e,me.of("buf.yaml"));try{await(0,Twn.cp)(a,ut(n,me.of("buf.yaml"))),await(0,Twn.cp)(r,ut(n,me.of("buf.lock")))}catch{return!1}try{return await ner(t,"buf",["dep","update"],{cwd:n,stdio:"pipe",timeout:3e4}),t.debug("Network check succeeded - not in air-gapped mode"),!1}catch(o){let c=o instanceof Error?o.message:String(o);return Tao(c)?(t.debug(`Network check failed - entering air-gapped mode: ${c.substring(0,100)}`),!0):!1}}finally{try{await(0,Twn.rm)(n,{recursive:!0,force:!0})}catch{}}}var p4_="buf.gen.yaml",IxI="output",h4_=`${IxI}/ir.json`,_4_="protoc-gen-fern",y4_=`version: v1
|
|
1600
|
+
`).reduce(zLI,Object.create(null)),zLI=(e,t)=>{let r=parseInt(t,10);if(r!==Buffer.byteLength(t)+1)return e;t=t.slice((r+" ").length);let i=t.split("="),n=i.shift();if(!n)return e;let a=n.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),o=i.join("=");return e[a]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(a)?new Date(Number(o)*1e3):/^[0-9]+$/.test(o)?+o:o,e};var NLI=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,F_=NLI!=="win32"?e=>e:e=>e&&e.replace(/\\/g,"/");var Dya=class extends bN{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,r,i){switch(super({}),this.pause(),this.extended=r,this.globalExtended=i,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=F_(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?F_(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,r&&this.#e(r),i&&this.#e(i,!0)}write(t){let r=t.length;if(r>this.blockRemain)throw new Error("writing more to entry than is appropriate");let i=this.remain,n=this.blockRemain;return this.remain=Math.max(0,i-r),this.blockRemain=Math.max(0,n-r),this.ignore?!0:i>=r?super.write(t):super.write(t.subarray(0,i))}#e(t,r=!1){t.path&&(t.path=F_(t.path)),t.linkpath&&(t.linkpath=F_(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,n])=>!(n==null||i==="path"&&r))))}};var _wn=(e,t,r,i={})=>{e.file&&(i.file=e.file),e.cwd&&(i.cwd=e.cwd),i.code=r instanceof Error&&r.code||t,i.tarCode=t,!e.strict&&i.recoverable!==!1?(r instanceof Error&&(i=Object.assign(r,i),r=r.message),e.emit("warn",t,r,i)):r instanceof Error?e.emit("error",Object.assign(r,i)):e.emit("error",Object.assign(new Error(`${t}: ${r}`),i))};var FLI=1024*1024,Xol=Buffer.from([31,139]),Zol=Buffer.from([40,181,47,253]),QLI=Math.max(Xol.length,Zol.length),vIe=Symbol("state"),ywn=Symbol("writeEntry"),d8i=Symbol("readEntry"),Kol=Symbol("nextEntry"),KN_=Symbol("processEntry"),Zkt=Symbol("extendedHeader"),Tno=Symbol("globalExtendedHeader"),_en=Symbol("meta"),$N_=Symbol("emitMeta"),MS=Symbol("buffer"),p8i=Symbol("queue"),yen=Symbol("ended"),$ol=Symbol("emittedEnd"),bwn=Symbol("emit"),AR=Symbol("unzip"),iDu=Symbol("consumeChunk"),nDu=Symbol("consumeChunkSub"),Jol=Symbol("consumeBody"),JN_=Symbol("consumeMeta"),YN_=Symbol("consumeHeader"),Rno=Symbol("consuming"),Yol=Symbol("bufferConcat"),aDu=Symbol("maybeEnd"),Iya=Symbol("writing"),ben=Symbol("aborted"),oDu=Symbol("onDone"),vwn=Symbol("sawValidEntry"),uDu=Symbol("sawNullBlock"),sDu=Symbol("sawEOF"),XN_=Symbol("closeStream"),ULI=()=>!0,h8i=class extends ZN_.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[p8i]=[];[MS];[d8i];[ywn];[vIe]="begin";[_en]="";[Zkt];[Tno];[yen]=!1;[AR];[ben]=!1;[vwn];[uDu]=!1;[sDu]=!1;[Iya]=!1;[Rno]=!1;[$ol]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(oDu,()=>{(this[vIe]==="begin"||this[vwn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(oDu,t.ondone):this.on(oDu,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||FLI,this.filter=typeof t.filter=="function"?t.filter:ULI;let r=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:r?void 0:!1;let i=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:i?!0:void 0,this.on("end",()=>this[XN_]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,r,i={}){_wn(this,t,r,i)}[YN_](t,r){this[vwn]===void 0&&(this[vwn]=!1);let i;try{i=new _Ae(t,r,this[Zkt],this[Tno])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(i.nullBlock)this[uDu]?(this[sDu]=!0,this[vIe]==="begin"&&(this[vIe]="header"),this[bwn]("eof")):(this[uDu]=!0,this[bwn]("nullBlock"));else if(this[uDu]=!1,!i.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:i});else if(!i.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:i});else{let n=i.type;if(/^(Symbolic)?Link$/.test(n)&&!i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:i});else if(!/^(Symbolic)?Link$/.test(n)&&!/^(Global)?ExtendedHeader$/.test(n)&&i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:i});else{let a=this[ywn]=new Dya(i,this[Zkt],this[Tno]);if(!this[vwn])if(a.remain){let o=()=>{a.invalid||(this[vwn]=!0)};a.on("end",o)}else this[vwn]=!0;a.meta?a.size>this.maxMetaEntrySize?(a.ignore=!0,this[bwn]("ignoredEntry",a),this[vIe]="ignore",a.resume()):a.size>0&&(this[_en]="",a.on("data",o=>this[_en]+=o),this[vIe]="meta"):(this[Zkt]=void 0,a.ignore=a.ignore||!this.filter(a.path,a),a.ignore?(this[bwn]("ignoredEntry",a),this[vIe]=a.remain?"ignore":"header",a.resume()):(a.remain?this[vIe]="body":(this[vIe]="header",a.end()),this[d8i]?this[p8i].push(a):(this[p8i].push(a),this[Kol]())))}}}[XN_](){queueMicrotask(()=>this.emit("close"))}[KN_](t){let r=!0;if(!t)this[d8i]=void 0,r=!1;else if(Array.isArray(t)){let[i,...n]=t;this.emit(i,...n)}else this[d8i]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Kol]()),r=!1);return r}[Kol](){do;while(this[KN_](this[p8i].shift()));if(!this[p8i].length){let t=this[d8i];!t||t.flowing||t.size===t.remain?this[Iya]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Jol](t,r){let i=this[ywn];if(!i)throw new Error("attempt to consume body without entry??");let n=i.blockRemain??0,a=n>=t.length&&r===0?t:t.subarray(r,r+n);return i.write(a),i.blockRemain||(this[vIe]="header",this[ywn]=void 0,i.end()),a.length}[JN_](t,r){let i=this[ywn],n=this[Jol](t,r);return!this[ywn]&&i&&this[$N_](i),n}[bwn](t,r,i){!this[p8i].length&&!this[d8i]?this.emit(t,r,i):this[p8i].push([t,r,i])}[$N_](t){switch(this[bwn]("meta",this[_en]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Zkt]=hen.parse(this[_en],this[Zkt],!1);break;case"GlobalExtendedHeader":this[Tno]=hen.parse(this[_en],this[Tno],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let r=this[Zkt]??Object.create(null);this[Zkt]=r,r.path=this[_en].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let r=this[Zkt]||Object.create(null);this[Zkt]=r,r.linkpath=this[_en].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[ben]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,r,i){if(typeof r=="function"&&(i=r,r=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof r=="string"?r:"utf8")),this[ben])return i?.(),!1;if((this[AR]===void 0||this.brotli===void 0&&this[AR]===!1)&&t){if(this[MS]&&(t=Buffer.concat([this[MS],t]),this[MS]=void 0),t.length<QLI)return this[MS]=t,i?.(),!0;for(let d=0;this[AR]===void 0&&d<Xol.length;d++)t[d]!==Xol[d]&&(this[AR]=!1);let o=!1;if(this[AR]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Zol.length;d++)if(t[d]!==Zol[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[AR]===!1&&c)if(t.length<512)if(this[yen])this.brotli=!0;else return this[MS]=t,i?.(),!0;else try{new _Ae(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[AR]===void 0||this[AR]===!1&&(this.brotli||o)){let d=this[yen];this[yen]=!1,this[AR]=this[AR]===void 0?new $Mu({}):o?new eDu({}):new XMu({}),this[AR].on("data",u=>this[iDu](u)),this[AR].on("error",u=>this.abort(u)),this[AR].on("end",()=>{this[yen]=!0,this[iDu]()}),this[Iya]=!0;let s=!!this[AR][d?"end":"write"](t);return this[Iya]=!1,i?.(),s}}this[Iya]=!0,this[AR]?this[AR].write(t):this[iDu](t),this[Iya]=!1;let a=this[p8i].length?!1:this[d8i]?this[d8i].flowing:!0;return!a&&!this[p8i].length&&this[d8i]?.once("drain",()=>this.emit("drain")),i?.(),a}[Yol](t){t&&!this[ben]&&(this[MS]=this[MS]?Buffer.concat([this[MS],t]):t)}[aDu](){if(this[yen]&&!this[$ol]&&!this[ben]&&!this[Rno]){this[$ol]=!0;let t=this[ywn];if(t&&t.blockRemain){let r=this[MS]?this[MS].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${r} available)`,{entry:t}),this[MS]&&t.write(this[MS]),t.end()}this[bwn](oDu)}}[iDu](t){if(this[Rno]&&t)this[Yol](t);else if(!t&&!this[MS])this[aDu]();else if(t){if(this[Rno]=!0,this[MS]){this[Yol](t);let r=this[MS];this[MS]=void 0,this[nDu](r)}else this[nDu](t);for(;this[MS]&&this[MS]?.length>=512&&!this[ben]&&!this[sDu];){let r=this[MS];this[MS]=void 0,this[nDu](r)}this[Rno]=!1}(!this[MS]||this[yen])&&this[aDu]()}[nDu](t){let r=0,i=t.length;for(;r+512<=i&&!this[ben]&&!this[sDu];)switch(this[vIe]){case"begin":case"header":this[YN_](t,r),r+=512;break;case"ignore":case"body":r+=this[Jol](t,r);break;case"meta":r+=this[JN_](t,r);break;default:throw new Error("invalid state: "+this[vIe])}r<i&&(this[MS]?this[MS]=Buffer.concat([t.subarray(r),this[MS]]):this[MS]=t.subarray(r))}end(t,r,i){return typeof t=="function"&&(i=t,r=void 0,t=void 0),typeof r=="function"&&(i=r,r=void 0),typeof t=="string"&&(t=Buffer.from(t,r)),i&&this.once("finish",i),this[ben]||(this[AR]?(t&&this[AR].write(t),this[AR].end()):(this[yen]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[aDu]())),this}};var ven=e=>{let t=e.length-1,r=-1;for(;t>-1&&e.charAt(t)==="/";)r=t,t--;return r===-1?e:e.slice(0,r)};var LLI=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},kol=(e,t)=>{let r=new Map(t.map(a=>[ven(a),!0])),i=e.filter,n=(a,o="")=>{let c=o||(0,cDu.parse)(a).root||".",d;if(a===c)d=!1;else{let s=r.get(a);s!==void 0?d=s:d=n((0,cDu.dirname)(a),c)}return r.set(a,d),d};e.filter=i?(a,o)=>i(a,o)&&n(ven(a)):a=>n(ven(a))},VLI=e=>{let t=new h8i(e),r=e.file,i;try{i=gwn.default.openSync(r,"r");let n=gwn.default.fstatSync(i),a=e.maxReadSize||16*1024*1024;if(n.size<a){let o=Buffer.allocUnsafe(n.size),c=gwn.default.readSync(i,o,0,n.size,0);t.end(c===o.byteLength?o:o.subarray(0,c))}else{let o=0,c=Buffer.allocUnsafe(a);for(;o<n.size;){let d=gwn.default.readSync(i,c,0,a,o);if(d===0)break;o+=d,t.write(c.subarray(0,d))}t.end()}}finally{if(typeof i=="number")try{gwn.default.closeSync(i)}catch{}}},WLI=(e,t)=>{let r=new h8i(e),i=e.maxReadSize||16*1024*1024,n=e.file;return new Promise((o,c)=>{r.on("error",c),r.on("end",o),gwn.default.stat(n,(d,s)=>{if(d)c(d);else{let u=new lwn(n,{readSize:i,size:s.size});u.on("error",c),u.pipe(r)}})})},Own=Xkt(VLI,WLI,e=>new h8i(e),e=>new h8i(e),(e,t)=>{t?.length&&kol(e,t),e.noResume||LLI(e)});var Vno=ce(require("fs"),1);var gHt=ce(require("fs"),1);var nul=ce(require("path"),1);var eul=(e,t,r)=>(e&=4095,r&&(e=(e|384)&-19),t&&(e&256&&(e|=64),e&32&&(e|=8),e&4&&(e|=1)),e);var eF_=require("path"),{isAbsolute:xLI,parse:kN_}=eF_.win32,zno=e=>{let t="",r=kN_(e);for(;xLI(e)||r.root;){let i=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(i.length),t+=i,r=kN_(e)}return[t,e]};var lDu=["|","<",">","?",":"],tul=lDu.map(e=>String.fromCharCode(61440+e.charCodeAt(0))),HLI=new Map(lDu.map((e,t)=>[e,tul[t]])),GLI=new Map(tul.map((e,t)=>[e,lDu[t]])),rul=e=>lDu.reduce((t,r)=>t.split(r).join(HLI.get(r)),e),tF_=e=>tul.reduce((t,r)=>t.split(r).join(GLI.get(r)),e);var uF_=(e,t)=>t?(e=F_(e).replace(/^\.(\/|$)/,""),ven(t)+"/"+e):F_(e),KLI=16*1024*1024,iF_=Symbol("process"),nF_=Symbol("file"),aF_=Symbol("directory"),aul=Symbol("symlink"),oF_=Symbol("hardlink"),Nno=Symbol("header"),fDu=Symbol("read"),oul=Symbol("lstat"),dDu=Symbol("onlstat"),uul=Symbol("onread"),sul=Symbol("onreadlink"),cul=Symbol("openfile"),lul=Symbol("onopenfile"),gen=Symbol("close"),pDu=Symbol("mode"),ful=Symbol("awaitDrain"),iul=Symbol("ondrain"),kkt=Symbol("prefix"),Fno=class extends bN{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,r={}){let i=Cno(r);super(),this.path=F_(t),this.portable=!!i.portable,this.maxReadSize=i.maxReadSize||KLI,this.linkCache=i.linkCache||new Map,this.statCache=i.statCache||new Map,this.preservePaths=!!i.preservePaths,this.cwd=F_(i.cwd||process.cwd()),this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.mtime=i.mtime,this.prefix=i.prefix?F_(i.prefix):void 0,this.onWriteEntry=i.onWriteEntry,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let n=!1;if(!this.preservePaths){let[o,c]=zno(this.path);o&&typeof c=="string"&&(this.path=c,n=o)}this.win32=!!i.win32||process.platform==="win32",this.win32&&(this.path=tF_(this.path.replace(/\\/g,"/")),t=t.replace(/\\/g,"/")),this.absolute=F_(i.absolute||nul.default.resolve(this.cwd,t)),this.path===""&&(this.path="./"),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path});let a=this.statCache.get(this.absolute);a?this[dDu](a):this[oul]()}warn(t,r,i={}){return _wn(this,t,r,i)}emit(t,...r){return t==="error"&&(this.#e=!0),super.emit(t,...r)}[oul](){gHt.default.lstat(this.absolute,(t,r)=>{if(t)return this.emit("error",t);this[dDu](r)})}[dDu](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=$LI(t),this.emit("stat",t),this[iF_]()}[iF_](){switch(this.type){case"File":return this[nF_]();case"Directory":return this[aF_]();case"SymbolicLink":return this[aul]();default:return this.end()}}[pDu](t){return eul(t,this.type==="Directory",this.portable)}[kkt](t){return uF_(t,this.prefix)}[Nno](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new _Ae({path:this[kkt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[kkt](this.linkpath):this.linkpath,mode:this[pDu](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new hen({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[kkt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[kkt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[aF_](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Nno](),this.end()}[aul](){gHt.default.readlink(this.absolute,(t,r)=>{if(t)return this.emit("error",t);this[sul](r)})}[sul](t){this.linkpath=F_(t),this[Nno](),this.end()}[oF_](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=F_(nul.default.relative(this.cwd,t)),this.stat.size=0,this[Nno](),this.end()}[nF_](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,r=this.linkCache.get(t);if(r?.indexOf(this.cwd)===0)return this[oF_](r);this.linkCache.set(t,this.absolute)}if(this[Nno](),this.stat.size===0)return this.end();this[cul]()}[cul](){gHt.default.open(this.absolute,"r",(t,r)=>{if(t)return this.emit("error",t);this[lul](r)})}[lul](t){if(this.fd=t,this.#e)return this[gen]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let r=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(r),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[fDu]()}[fDu](){let{fd:t,buf:r,offset:i,length:n,pos:a}=this;if(t===void 0||r===void 0)throw new Error("cannot read file without first opening");gHt.default.read(t,r,i,n,a,(o,c)=>{if(o)return this[gen](()=>this.emit("error",o));this[uul](c)})}[gen](t=()=>{}){this.fd!==void 0&&gHt.default.close(this.fd,t)}[uul](t){if(t<=0&&this.remain>0){let n=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[gen](()=>this.emit("error",n))}if(t>this.remain){let n=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[gen](()=>this.emit("error",n))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let n=t;n<this.length&&t<this.blockRemain;n++)this.buf[n+this.offset]=0,t++,this.remain++;let r=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(r)?this[iul]():this[ful](()=>this[iul]())}[ful](t){this.once("drain",t)}write(t,r,i){if(typeof r=="function"&&(i=r,r=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof r=="string"?r:"utf8")),this.blockRemain<t.length){let n=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",n)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,i)}[iul](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[gen](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[fDu]()}},hDu=class extends Fno{sync=!0;[oul](){this[dDu](gHt.default.lstatSync(this.absolute))}[aul](){this[sul](gHt.default.readlinkSync(this.absolute))}[cul](){this[lul](gHt.default.openSync(this.absolute,"r"))}[fDu](){let t=!0;try{let{fd:r,buf:i,offset:n,length:a,pos:o}=this;if(r===void 0||i===void 0)throw new Error("fd and buf must be set in READ method");let c=gHt.default.readSync(r,i,n,a,o);this[uul](c),t=!1}finally{if(t)try{this[gen](()=>{})}catch{}}}[ful](t){t()}[gen](t=()=>{}){this.fd!==void 0&&gHt.default.closeSync(this.fd),t()}},_Du=class extends bN{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,r,i={}){return _wn(this,t,r,i)}constructor(t,r={}){let i=Cno(r);super(),this.preservePaths=!!i.preservePaths,this.portable=!!i.portable,this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.onWriteEntry=i.onWriteEntry,this.readEntry=t;let{type:n}=t;if(n==="Unsupported")throw new Error("writing entry that should be ignored");this.type=n,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=i.prefix,this.path=F_(t.path),this.mode=t.mode!==void 0?this[pDu](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:i.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?F_(t.linkpath):void 0,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let a=!1;if(!this.preservePaths){let[c,d]=zno(this.path);c&&typeof d=="string"&&(this.path=d,a=c)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new _Ae({path:this[kkt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[kkt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),a&&this.warn("TAR_ENTRY_INFO",`stripping ${a} from absolute path`,{entry:this,path:a+this.path}),this.header.encode()&&!this.noPax&&super.write(new hen({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[kkt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[kkt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),t.pipe(this)}[kkt](t){return uF_(t,this.prefix)}[pDu](t){return eul(t,this.type==="Directory",this.portable)}write(t,r,i){typeof r=="function"&&(i=r,r=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof r=="string"?r:"utf8"));let n=t.length;if(n>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=n,super.write(t,i)}end(t,r,i){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(i=t,r=void 0,t=void 0),typeof r=="function"&&(i=r,r=void 0),typeof t=="string"&&(t=Buffer.from(t,r??"utf8")),i&&this.once("finish",i),t?super.end(t,i):super.end(i),this}},$LI=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported";var yDu=class e{tail;head;length=0;static create(t=[]){return new e(t)}constructor(t=[]){for(let r of t)this.push(r)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw new Error("removing node which does not belong to this list");let r=t.next,i=t.prev;return r&&(r.prev=i),i&&(i.next=r),t===this.head&&(this.head=r),t===this.tail&&(this.tail=i),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,r}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let r=this.head;t.list=this,t.next=r,r&&(r.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let r=this.tail;t.list=this,t.prev=r,r&&(r.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let r=0,i=t.length;r<i;r++)YLI(this,t[r]);return this.length}unshift(...t){for(var r=0,i=t.length;r<i;r++)XLI(this,t[r]);return this.length}pop(){if(!this.tail)return;let t=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,t}shift(){if(!this.head)return;let t=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,t}forEach(t,r){r=r||this;for(let i=this.head,n=0;i;n++)t.call(r,i.value,n,this),i=i.next}forEachReverse(t,r){r=r||this;for(let i=this.tail,n=this.length-1;i;n--)t.call(r,i.value,n,this),i=i.prev}get(t){let r=0,i=this.head;for(;i&&r<t;r++)i=i.next;if(r===t&&i)return i.value}getReverse(t){let r=0,i=this.tail;for(;i&&r<t;r++)i=i.prev;if(r===t&&i)return i.value}map(t,r){r=r||this;let i=new e;for(let n=this.head;n;)i.push(t.call(r,n.value,this)),n=n.next;return i}mapReverse(t,r){r=r||this;var i=new e;for(let n=this.tail;n;)i.push(t.call(r,n.value,this)),n=n.prev;return i}reduce(t,r){let i,n=this.head;if(arguments.length>1)i=r;else if(this.head)n=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var a=0;n;a++)i=t(i,n.value,a),n=n.next;return i}reduceReverse(t,r){let i,n=this.tail;if(arguments.length>1)i=r;else if(this.tail)n=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let a=this.length-1;n;a--)i=t(i,n.value,a),n=n.prev;return i}toArray(){let t=new Array(this.length);for(let r=0,i=this.head;i;r++)t[r]=i.value,i=i.next;return t}toArrayReverse(){let t=new Array(this.length);for(let r=0,i=this.tail;i;r++)t[r]=i.value,i=i.prev;return t}slice(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let i=new e;if(r<t||r<0)return i;t<0&&(t=0),r>this.length&&(r=this.length);let n=this.head,a=0;for(a=0;n&&a<t;a++)n=n.next;for(;n&&a<r;a++,n=n.next)i.push(n.value);return i}sliceReverse(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let i=new e;if(r<t||r<0)return i;t<0&&(t=0),r>this.length&&(r=this.length);let n=this.length,a=this.tail;for(;a&&n>r;n--)a=a.prev;for(;a&&n>t;n--,a=a.prev)i.push(a.value);return i}splice(t,r=0,...i){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let n=this.head;for(let o=0;n&&o<t;o++)n=n.next;let a=[];for(let o=0;n&&o<r;o++)a.push(n.value),n=this.removeNode(n);n?n!==this.tail&&(n=n.prev):n=this.tail;for(let o of i)n=JLI(this,n,o);return a}reverse(){let t=this.head,r=this.tail;for(let i=t;i;i=i.prev){let n=i.prev;i.prev=i.next,i.next=n}return this.head=r,this.tail=t,this}};function JLI(e,t,r){let i=t,n=t?t.next:e.head,a=new Qno(r,i,n,e);return a.next===void 0&&(e.tail=a),a.prev===void 0&&(e.head=a),e.length++,a}function YLI(e,t){e.tail=new Qno(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function XLI(e,t){e.head=new Qno(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}var Qno=class{list;next;prev;value;constructor(t,r,i,n){this.list=n,this.value=t,r?(r.next=this,this.prev=r):this.prev=void 0,i?(i.prev=this,this.next=i):this.next=void 0}};var vul=ce(require("path"),1);var ADu=class{path;absolute;entry;stat;readdir;pending=!1;ignore=!1;piped=!1;constructor(t,r){this.path=t||"./",this.absolute=r}},sF_=Buffer.alloc(1024),bDu=Symbol("onStat"),Uno=Symbol("ended"),OHt=Symbol("queue"),mwn=Symbol("current"),Awn=Symbol("process"),Lno=Symbol("processing"),dul=Symbol("processJob"),mHt=Symbol("jobs"),pul=Symbol("jobDone"),vDu=Symbol("addFSEntry"),cF_=Symbol("addTarEntry"),yul=Symbol("stat"),bul=Symbol("readdir"),gDu=Symbol("onreaddir"),ODu=Symbol("pipe"),lF_=Symbol("entry"),hul=Symbol("entryOpt"),mDu=Symbol("writeEntryClass"),fF_=Symbol("write"),_ul=Symbol("ondrain"),Oen=class extends bN{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[mDu];onWriteEntry;[OHt];[mHt]=0;[Lno]=!1;[Uno]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=F_(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[mDu]=Fno,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new KMu(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new YMu(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new kMu(t.zstd)),!this.zip)throw new Error("impossible");let r=this.zip;r.on("data",i=>super.write(i)),r.on("end",()=>super.end()),r.on("drain",()=>this[_ul]()),this.on("resume",()=>r.resume())}else this.on("drain",this[_ul]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[OHt]=new yDu,this[mHt]=0,this.jobs=Number(t.jobs)||4,this[Lno]=!1,this[Uno]=!1}[fF_](t){return super.write(t)}add(t){return this.write(t),this}end(t,r,i){return typeof t=="function"&&(i=t,t=void 0),typeof r=="function"&&(i=r,r=void 0),t&&this.add(t),this[Uno]=!0,this[Awn](),i&&i(),this}write(t){if(this[Uno])throw new Error("write after end");return t instanceof Dya?this[cF_](t):this[vDu](t),this.flowing}[cF_](t){let r=F_(vul.default.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let i=new ADu(t.path,r);i.entry=new _Du(t,this[hul](i)),i.entry.on("end",()=>this[pul](i)),this[mHt]+=1,this[OHt].push(i)}this[Awn]()}[vDu](t){let r=F_(vul.default.resolve(this.cwd,t));this[OHt].push(new ADu(t,r)),this[Awn]()}[yul](t){t.pending=!0,this[mHt]+=1;let r=this.follow?"stat":"lstat";Vno.default[r](t.absolute,(i,n)=>{t.pending=!1,this[mHt]-=1,i?this.emit("error",i):this[bDu](t,n)})}[bDu](t,r){this.statCache.set(t.absolute,r),t.stat=r,this.filter(t.path,r)?r.isFile()&&r.nlink>1&&t===this[mwn]&&!this.linkCache.get(`${r.dev}:${r.ino}`)&&!this.sync&&this[dul](t):t.ignore=!0,this[Awn]()}[bul](t){t.pending=!0,this[mHt]+=1,Vno.default.readdir(t.absolute,(r,i)=>{if(t.pending=!1,this[mHt]-=1,r)return this.emit("error",r);this[gDu](t,i)})}[gDu](t,r){this.readdirCache.set(t.absolute,r),t.readdir=r,this[Awn]()}[Awn](){if(!this[Lno]){this[Lno]=!0;for(let t=this[OHt].head;t&&this[mHt]<this.jobs;t=t.next)if(this[dul](t.value),t.value.ignore){let r=t.next;this[OHt].removeNode(t),t.next=r}this[Lno]=!1,this[Uno]&&!this[OHt].length&&this[mHt]===0&&(this.zip?this.zip.end(sF_):(super.write(sF_),super.end()))}}get[mwn](){return this[OHt]&&this[OHt].head&&this[OHt].head.value}[pul](t){this[OHt].shift(),this[mHt]-=1,this[Awn]()}[dul](t){if(!t.pending){if(t.entry){t===this[mwn]&&!t.piped&&this[ODu](t);return}if(!t.stat){let r=this.statCache.get(t.absolute);r?this[bDu](t,r):this[yul](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let r=this.readdirCache.get(t.absolute);if(r?this[gDu](t,r):this[bul](t),!t.readdir)return}if(t.entry=this[lF_](t),!t.entry){t.ignore=!0;return}t===this[mwn]&&!t.piped&&this[ODu](t)}}}[hul](t){return{onwarn:(r,i,n)=>this.warn(r,i,n),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[lF_](t){this[mHt]+=1;try{return new this[mDu](t.path,this[hul](t)).on("end",()=>this[pul](t)).on("error",i=>this.emit("error",i))}catch(r){this.emit("error",r)}}[_ul](){this[mwn]&&this[mwn].entry&&this[mwn].entry.resume()}[ODu](t){t.piped=!0,t.readdir&&t.readdir.forEach(n=>{let a=t.path,o=a==="./"?"":a.replace(/\/*$/,"/");this[vDu](o+n)});let r=t.entry,i=this.zip;if(!r)throw new Error("cannot pipe without source");i?r.on("data",n=>{i.write(n)||r.pause()}):r.on("data",n=>{super.write(n)||r.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,r,i={}){_wn(this,t,r,i)}},Pwn=class extends Oen{sync=!0;constructor(t){super(t),this[mDu]=hDu}pause(){}resume(){}[yul](t){let r=this.follow?"statSync":"lstatSync";this[bDu](t,Vno.default[r](t.absolute))}[bul](t){this[gDu](t,Vno.default.readdirSync(t.absolute))}[ODu](t){let r=t.entry,i=this.zip;if(t.readdir&&t.readdir.forEach(n=>{let a=t.path,o=a==="./"?"":a.replace(/\/*$/,"/");this[vDu](o+n)}),!r)throw new Error("Cannot pipe without source");i?r.on("data",n=>{i.write(n)}):r.on("data",n=>{super[fF_](n)})}};var ZLI=(e,t)=>{let r=new Pwn(e),i=new Sya(e.file,{mode:e.mode||438});r.pipe(i),dF_(r,t)},kLI=(e,t)=>{let r=new Oen(e),i=new f8i(e.file,{mode:e.mode||438});r.pipe(i);let n=new Promise((a,o)=>{i.on("error",o),i.on("close",a),r.on("error",o)});return pF_(r,t),n},dF_=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?Own({file:gul.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>e.add(i)}):e.add(r)}),e.end()},pF_=async(e,t)=>{for(let r=0;r<t.length;r++){let i=String(t[r]);i.charAt(0)==="@"?await Own({file:gul.default.resolve(String(e.cwd),i.slice(1)),noResume:!0,onReadEntry:n=>{e.add(n)}}):e.add(i)}e.end()},e4I=(e,t)=>{let r=new Pwn(e);return dF_(r,t),r},t4I=(e,t)=>{let r=new Oen(e);return pF_(r,t),r},Oul=Xkt(ZLI,kLI,e4I,t4I,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")});var Ful=ce(require("fs"),1);var DF_=ce(require("assert"),1),Nul=require("crypto"),KA=ce(require("fs"),1),yAe=ce(require("path"),1);var mul=ce(require("fs"),1),r4I=process.env.__FAKE_PLATFORM__||process.platform,i4I=r4I==="win32",{O_CREAT:n4I,O_TRUNC:a4I,O_WRONLY:o4I}=mul.default.constants,hF_=Number(process.env.__FAKE_FS_O_FILENAME__)||mul.default.constants.UV_FS_O_FILEMAP||0,u4I=i4I&&!!hF_,s4I=512*1024,c4I=hF_|a4I|n4I|o4I,Aul=u4I?e=>e<s4I?c4I:"w":()=>"w";var Wno=ce(require("fs"),1),Bya=ce(require("path"),1),Pul=(e,t,r)=>{try{return Wno.default.lchownSync(e,t,r)}catch(i){if(i?.code!=="ENOENT")throw i}},PDu=(e,t,r,i)=>{Wno.default.lchown(e,t,r,n=>{i(n&&n?.code!=="ENOENT"?n:null)})},l4I=(e,t,r,i,n)=>{if(t.isDirectory())jul(Bya.default.resolve(e,t.name),r,i,a=>{if(a)return n(a);let o=Bya.default.resolve(e,t.name);PDu(o,r,i,n)});else{let a=Bya.default.resolve(e,t.name);PDu(a,r,i,n)}},jul=(e,t,r,i)=>{Wno.default.readdir(e,{withFileTypes:!0},(n,a)=>{if(n){if(n.code==="ENOENT")return i();if(n.code!=="ENOTDIR"&&n.code!=="ENOTSUP")return i(n)}if(n||!a.length)return PDu(e,t,r,i);let o=a.length,c=null,d=s=>{if(!c){if(s)return i(c=s);if(--o===0)return PDu(e,t,r,i)}};for(let s of a)l4I(e,s,t,r,d)})},f4I=(e,t,r,i)=>{t.isDirectory()&&wul(Bya.default.resolve(e,t.name),r,i),Pul(Bya.default.resolve(e,t.name),r,i)},wul=(e,t,r)=>{let i;try{i=Wno.default.readdirSync(e,{withFileTypes:!0})}catch(n){let a=n;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return Pul(e,t,r);throw a}for(let n of i)f4I(e,n,t,r);return Pul(e,t,r)};var h2=ce(require("fs"),1),_F_=ce(require("fs/promises"),1),Gno=ce(require("path"),1);var xno=class extends Error{path;code;syscall="chdir";constructor(t,r){super(`${r}: Cannot cd into '${t}'`),this.path=t,this.code=r}get name(){return"CwdError"}};var Hno=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,r){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=r}get name(){return"SymlinkError"}};var d4I=(e,t)=>{h2.default.stat(e,(r,i)=>{(r||!i.isDirectory())&&(r=new xno(e,r?.code||"ENOTDIR")),t(r)})},yF_=(e,t,r)=>{e=F_(e);let i=t.umask??18,n=t.mode|448,a=(n&i)!==0,o=t.uid,c=t.gid,d=typeof o=="number"&&typeof c=="number"&&(o!==t.processUid||c!==t.processGid),s=t.preserve,u=t.unlink,f=F_(t.cwd),p=(y,b)=>{y?r(y):b&&d?jul(b,o,c,v=>p(v)):a?h2.default.chmod(e,n,r):r()};if(e===f)return d4I(e,p);if(s)return _F_.default.mkdir(e,{mode:n,recursive:!0}).then(y=>p(null,y??void 0),p);let _=F_(Gno.default.relative(f,e)).split("/");Eul(f,_,n,u,f,void 0,p)},Eul=(e,t,r,i,n,a,o)=>{if(!t.length)return o(null,a);let c=t.shift(),d=F_(Gno.default.resolve(e+"/"+c));h2.default.mkdir(d,r,bF_(d,t,r,i,n,a,o))},bF_=(e,t,r,i,n,a,o)=>c=>{c?h2.default.lstat(e,(d,s)=>{if(d)d.path=d.path&&F_(d.path),o(d);else if(s.isDirectory())Eul(e,t,r,i,n,a,o);else if(i)h2.default.unlink(e,u=>{if(u)return o(u);h2.default.mkdir(e,r,bF_(e,t,r,i,n,a,o))});else{if(s.isSymbolicLink())return o(new Hno(e,e+"/"+t.join("/")));o(c)}}):(a=a||e,Eul(e,t,r,i,n,a,o))},p4I=e=>{let t=!1,r;try{t=h2.default.statSync(e).isDirectory()}catch(i){r=i?.code}finally{if(!t)throw new xno(e,r??"ENOTDIR")}},vF_=(e,t)=>{e=F_(e);let r=t.umask??18,i=t.mode|448,n=(i&r)!==0,a=t.uid,o=t.gid,c=typeof a=="number"&&typeof o=="number"&&(a!==t.processUid||o!==t.processGid),d=t.preserve,s=t.unlink,u=F_(t.cwd),f=y=>{y&&c&&wul(y,a,o),n&&h2.default.chmodSync(e,i)};if(e===u)return p4I(u),f();if(d)return f(h2.default.mkdirSync(e,{mode:i,recursive:!0})??void 0);let h=F_(Gno.default.relative(u,e)).split("/"),_;for(let y=h.shift(),b=u;y&&(b+="/"+y);y=h.shift()){b=F_(Gno.default.resolve(b));try{h2.default.mkdirSync(b,i),_=_||b}catch{let O=h2.default.lstatSync(b);if(O.isDirectory())continue;if(s){h2.default.unlinkSync(b),h2.default.mkdirSync(b,i),_=_||b;continue}else if(O.isSymbolicLink())return new Hno(b,b+"/"+h.join("/"))}}return f(_)};var Mul=require("path");var Sul=Object.create(null),gF_=1e4,Cya=new Set,OF_=e=>{Cya.has(e)?Cya.delete(e):Sul[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Cya.add(e);let t=Sul[e],r=Cya.size-gF_;if(r>gF_/10){for(let i of Cya)if(Cya.delete(i),delete Sul[i],--r<=0)break}return t};var h4I=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,_4I=h4I==="win32",y4I=e=>e.split("/").slice(0,-1).reduce((r,i)=>{let n=r[r.length-1];return n!==void 0&&(i=(0,Mul.join)(n,i)),r.push(i||"/"),r},[]),jDu=class{#e=new Map;#t=new Map;#r=new Set;reserve(t,r){t=_4I?["win32 parallelization disabled"]:t.map(n=>ven((0,Mul.join)(OF_(n))));let i=new Set(t.map(n=>y4I(n)).reduce((n,a)=>n.concat(a)));this.#t.set(r,{dirs:i,paths:t});for(let n of t){let a=this.#e.get(n);a?a.push(r):this.#e.set(n,[r])}for(let n of i){let a=this.#e.get(n);if(!a)this.#e.set(n,[new Set([r])]);else{let o=a[a.length-1];o instanceof Set?o.add(r):a.push(new Set([r]))}}return this.#n(r)}#i(t){let r=this.#t.get(t);if(!r)throw new Error("function does not have any path reservations");return{paths:r.paths.map(i=>this.#e.get(i)),dirs:[...r.dirs].map(i=>this.#e.get(i))}}check(t){let{paths:r,dirs:i}=this.#i(t);return r.every(n=>n&&n[0]===t)&&i.every(n=>n&&n[0]instanceof Set&&n[0].has(t))}#n(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#a(t)),!0)}#a(t){if(!this.#r.has(t))return!1;let r=this.#t.get(t);if(!r)throw new Error("invalid reservation");let{paths:i,dirs:n}=r,a=new Set;for(let o of i){let c=this.#e.get(o);if(!c||c?.[0]!==t)continue;let d=c[1];if(!d){this.#e.delete(o);continue}if(c.shift(),typeof d=="function")a.add(d);else for(let s of d)a.add(s)}for(let o of n){let c=this.#e.get(o),d=c?.[0];if(!(!c||!(d instanceof Set)))if(d.size===1&&c.length===1){this.#e.delete(o);continue}else if(d.size===1){c.shift();let s=c[0];typeof s=="function"&&a.add(s)}else d.delete(t)}return this.#r.delete(t),a.forEach(o=>this.#n(o)),!0}};var mF_=Symbol("onEntry"),Cul=Symbol("checkFs"),AF_=Symbol("checkFs2"),qul=Symbol("isReusable"),gIe=Symbol("makeFs"),Tul=Symbol("file"),Rul=Symbol("directory"),SDu=Symbol("link"),PF_=Symbol("symlink"),jF_=Symbol("hardlink"),wF_=Symbol("unsupported"),EF_=Symbol("checkPath"),Dul=Symbol("stripAbsolutePath"),men=Symbol("mkdir"),X5=Symbol("onError"),wDu=Symbol("pending"),SF_=Symbol("pend"),qya=Symbol("unpend"),Iul=Symbol("ended"),Bul=Symbol("maybeClose"),zul=Symbol("skip"),Kno=Symbol("doChown"),$no=Symbol("uid"),Jno=Symbol("gid"),Yno=Symbol("checkedCwd"),b4I=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Xno=b4I==="win32",v4I=1024,g4I=(e,t)=>{if(!Xno)return KA.default.unlink(e,t);let r=e+".DELETE."+(0,Nul.randomBytes)(16).toString("hex");KA.default.rename(e,r,i=>{if(i)return t(i);KA.default.unlink(r,t)})},O4I=e=>{if(!Xno)return KA.default.unlinkSync(e);let t=e+".DELETE."+(0,Nul.randomBytes)(16).toString("hex");KA.default.renameSync(e,t),KA.default.unlinkSync(t)},MF_=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,Tya=class extends h8i{[Iul]=!1;[Yno]=!1;[wDu]=0;reservations=new jDu;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[Iul]=!0,this[Bul]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;t.preserveOwner===void 0&&typeof t.uid!="number"?this.preserveOwner=!!(process.getuid&&process.getuid()===0):this.preserveOwner=!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:v4I,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Xno,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=F_(yAe.default.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:process.umask():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",r=>this[mF_](r))}warn(t,r,i={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(i.recoverable=!1),super.warn(t,r,i)}[Bul](){this[Iul]&&this[wDu]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Dul](t,r){let i=t[r],{type:n}=t;if(!i||this.preservePaths)return!0;let a=i.split("/");if(a.includes("..")||Xno&&/^[a-z]:\.\.$/i.test(a[0]??"")){if(r==="path"||n==="Link")return this.warn("TAR_ENTRY_ERROR",`${r} contains '..'`,{entry:t,[r]:i}),!1;{let d=yAe.default.posix.dirname(t.path),s=yAe.default.posix.normalize(yAe.default.posix.join(d,i));if(s.startsWith("../")||s==="..")return this.warn("TAR_ENTRY_ERROR",`${r} escapes extraction directory`,{entry:t,[r]:i}),!1}}let[o,c]=zno(i);return o&&(t[r]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${r}`,{entry:t,[r]:i})),!0}[EF_](t){let r=F_(t.path),i=r.split("/");if(this.strip){if(i.length<this.strip)return!1;if(t.type==="Link"){let n=F_(String(t.linkpath)).split("/");if(n.length>=this.strip)t.linkpath=n.slice(this.strip).join("/");else return!1}i.splice(0,this.strip),t.path=i.join("/")}if(isFinite(this.maxDepth)&&i.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:r,depth:i.length,maxDepth:this.maxDepth}),!1;if(!this[Dul](t,"path")||!this[Dul](t,"linkpath"))return!1;if(yAe.default.isAbsolute(t.path)?t.absolute=F_(yAe.default.resolve(t.path)):t.absolute=F_(yAe.default.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:F_(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:n}=yAe.default.win32.parse(String(t.absolute));t.absolute=n+rul(String(t.absolute).slice(n.length));let{root:a}=yAe.default.win32.parse(t.path);t.path=a+rul(t.path.slice(a.length))}return!0}[mF_](t){if(!this[EF_](t))return t.resume();switch(DF_.default.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Cul](t);default:return this[wF_](t)}}[X5](t,r){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:r}),this[qya](),r.resume())}[men](t,r,i){yF_(F_(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:r},i)}[Kno](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[$no](t){return MF_(this.uid,t.uid,this.processUid)}[Jno](t){return MF_(this.gid,t.gid,this.processGid)}[Tul](t,r){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,n=new f8i(String(t.absolute),{flags:Aul(t.size),mode:i,autoClose:!1});n.on("error",d=>{n.fd&&KA.default.close(n.fd,()=>{}),n.write=()=>!0,this[X5](d,t),r()});let a=1,o=d=>{if(d){n.fd&&KA.default.close(n.fd,()=>{}),this[X5](d,t),r();return}--a===0&&n.fd!==void 0&&KA.default.close(n.fd,s=>{s?this[X5](s,t):this[qya](),r()})};n.on("finish",()=>{let d=String(t.absolute),s=n.fd;if(typeof s=="number"&&t.mtime&&!this.noMtime){a++;let u=t.atime||new Date,f=t.mtime;KA.default.futimes(s,u,f,p=>p?KA.default.utimes(d,u,f,h=>o(h&&p)):o())}if(typeof s=="number"&&this[Kno](t)){a++;let u=this[$no](t),f=this[Jno](t);typeof u=="number"&&typeof f=="number"&&KA.default.fchown(s,u,f,p=>p?KA.default.chown(d,u,f,h=>o(h&&p)):o())}o()});let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>{this[X5](d,t),r()}),t.pipe(c)),c.pipe(n)}[Rul](t,r){let i=typeof t.mode=="number"?t.mode&4095:this.dmode;this[men](String(t.absolute),i,n=>{if(n){this[X5](n,t),r();return}let a=1,o=()=>{--a===0&&(r(),this[qya](),t.resume())};t.mtime&&!this.noMtime&&(a++,KA.default.utimes(String(t.absolute),t.atime||new Date,t.mtime,o)),this[Kno](t)&&(a++,KA.default.chown(String(t.absolute),Number(this[$no](t)),Number(this[Jno](t)),o)),o()})}[wF_](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[PF_](t,r){this[SDu](t,String(t.linkpath),"symlink",r)}[jF_](t,r){let i=F_(yAe.default.resolve(this.cwd,String(t.linkpath)));this[SDu](t,i,"link",r)}[SF_](){this[wDu]++}[qya](){this[wDu]--,this[Bul]()}[zul](t){this[qya](),t.resume()}[qul](t,r){return t.type==="File"&&!this.unlink&&r.isFile()&&r.nlink<=1&&!Xno}[Cul](t){this[SF_]();let r=[t.path];t.linkpath&&r.push(t.linkpath),this.reservations.reserve(r,i=>this[AF_](t,i))}[AF_](t,r){let i=c=>{r(c)},n=()=>{this[men](this.cwd,this.dmode,c=>{if(c){this[X5](c,t),i();return}this[Yno]=!0,a()})},a=()=>{if(t.absolute!==this.cwd){let c=F_(yAe.default.dirname(String(t.absolute)));if(c!==this.cwd)return this[men](c,this.dmode,d=>{if(d){this[X5](d,t),i();return}o()})}o()},o=()=>{KA.default.lstat(String(t.absolute),(c,d)=>{if(d&&(this.keep||this.newer&&d.mtime>(t.mtime??d.mtime))){this[zul](t),i();return}if(c||this[qul](t,d))return this[gIe](null,t,i);if(d.isDirectory()){if(t.type==="Directory"){let s=this.chmod&&t.mode&&(d.mode&4095)!==t.mode,u=f=>this[gIe](f??null,t,i);return s?KA.default.chmod(String(t.absolute),Number(t.mode),u):u()}if(t.absolute!==this.cwd)return KA.default.rmdir(String(t.absolute),s=>this[gIe](s??null,t,i))}if(t.absolute===this.cwd)return this[gIe](null,t,i);g4I(String(t.absolute),s=>this[gIe](s??null,t,i))})};this[Yno]?a():n()}[gIe](t,r,i){if(t){this[X5](t,r),i();return}switch(r.type){case"File":case"OldFile":case"ContiguousFile":return this[Tul](r,i);case"Link":return this[jF_](r,i);case"SymbolicLink":return this[PF_](r,i);case"Directory":case"GNUDumpDir":return this[Rul](r,i)}}[SDu](t,r,i,n){KA.default[i](r,String(t.absolute),a=>{a?this[X5](a,t):(this[qya](),t.resume()),n()})}},EDu=e=>{try{return[null,e()]}catch(t){return[t,null]}},Zno=class extends Tya{sync=!0;[gIe](t,r){return super[gIe](t,r,()=>{})}[Cul](t){if(!this[Yno]){let a=this[men](this.cwd,this.dmode);if(a)return this[X5](a,t);this[Yno]=!0}if(t.absolute!==this.cwd){let a=F_(yAe.default.dirname(String(t.absolute)));if(a!==this.cwd){let o=this[men](a,this.dmode);if(o)return this[X5](o,t)}}let[r,i]=EDu(()=>KA.default.lstatSync(String(t.absolute)));if(i&&(this.keep||this.newer&&i.mtime>(t.mtime??i.mtime)))return this[zul](t);if(r||this[qul](t,i))return this[gIe](null,t);if(i.isDirectory()){if(t.type==="Directory"){let o=this.chmod&&t.mode&&(i.mode&4095)!==t.mode,[c]=o?EDu(()=>{KA.default.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[gIe](c,t)}let[a]=EDu(()=>KA.default.rmdirSync(String(t.absolute)));this[gIe](a,t)}let[n]=t.absolute===this.cwd?[]:EDu(()=>O4I(String(t.absolute)));this[gIe](n,t)}[Tul](t,r){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,n=c=>{let d;try{KA.default.closeSync(a)}catch(s){d=s}(c||d)&&this[X5](c||d,t),r()},a;try{a=KA.default.openSync(String(t.absolute),Aul(t.size),i)}catch(c){return n(c)}let o=this.transform&&this.transform(t)||t;o!==t&&(o.on("error",c=>this[X5](c,t)),t.pipe(o)),o.on("data",c=>{try{KA.default.writeSync(a,c,0,c.length)}catch(d){n(d)}}),o.on("end",()=>{let c=null;if(t.mtime&&!this.noMtime){let d=t.atime||new Date,s=t.mtime;try{KA.default.futimesSync(a,d,s)}catch(u){try{KA.default.utimesSync(String(t.absolute),d,s)}catch{c=u}}}if(this[Kno](t)){let d=this[$no](t),s=this[Jno](t);try{KA.default.fchownSync(a,Number(d),Number(s))}catch(u){try{KA.default.chownSync(String(t.absolute),Number(d),Number(s))}catch{c=c||u}}}n(c)})}[Rul](t,r){let i=typeof t.mode=="number"?t.mode&4095:this.dmode,n=this[men](String(t.absolute),i);if(n){this[X5](n,t),r();return}if(t.mtime&&!this.noMtime)try{KA.default.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Kno](t))try{KA.default.chownSync(String(t.absolute),Number(this[$no](t)),Number(this[Jno](t)))}catch{}r(),t.resume()}[men](t,r){try{return vF_(F_(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:r})}catch(i){return i}}[SDu](t,r,i,n){let a=`${i}Sync`;try{KA.default[a](r,String(t.absolute)),n(),t.resume()}catch(o){return this[X5](o,t)}}};var m4I=e=>{let t=new Zno(e),r=e.file,i=Ful.default.statSync(r),n=e.maxReadSize||16*1024*1024;new xMu(r,{readSize:n,size:i.size}).pipe(t)},A4I=(e,t)=>{let r=new Tya(e),i=e.maxReadSize||16*1024*1024,n=e.file;return new Promise((o,c)=>{r.on("error",c),r.on("close",o),Ful.default.stat(n,(d,s)=>{if(d)c(d);else{let u=new lwn(n,{readSize:i,size:s.size});u.on("error",c),u.pipe(r)}})})},Qul=Xkt(m4I,A4I,e=>new Zno(e),e=>new Tya(e),(e,t)=>{t?.length&&kol(e,t)});var _2=ce(require("fs"),1),Uul=ce(require("path"),1);var P4I=(e,t)=>{let r=new Pwn(e),i=!0,n,a;try{try{n=_2.default.openSync(e.file,"r+")}catch(d){if(d?.code==="ENOENT")n=_2.default.openSync(e.file,"w+");else throw d}let o=_2.default.fstatSync(n),c=Buffer.alloc(512);e:for(a=0;a<o.size;a+=512){for(let u=0,f=0;u<512;u+=f){if(f=_2.default.readSync(n,c,u,c.length-u,a+u),a===0&&c[0]===31&&c[1]===139)throw new Error("cannot append to compressed archives");if(!f)break e}let d=new _Ae(c);if(!d.cksumValid)break;let s=512*Math.ceil((d.size||0)/512);if(a+s+512>o.size)break;a+=s,e.mtimeCache&&d.mtime&&e.mtimeCache.set(String(d.path),d.mtime)}i=!1,j4I(e,r,a,n,t)}finally{if(i)try{_2.default.closeSync(n)}catch{}}},j4I=(e,t,r,i,n)=>{let a=new Sya(e.file,{fd:i,start:r});t.pipe(a),E4I(t,n)},w4I=(e,t)=>{t=Array.from(t);let r=new Oen(e),i=(a,o,c)=>{let d=(h,_)=>{h?_2.default.close(a,y=>c(h)):c(null,_)},s=0;if(o===0)return d(null,0);let u=0,f=Buffer.alloc(512),p=(h,_)=>{if(h||typeof _>"u")return d(h);if(u+=_,u<512&&_)return _2.default.read(a,f,u,f.length-u,s+u,p);if(s===0&&f[0]===31&&f[1]===139)return d(new Error("cannot append to compressed archives"));if(u<512)return d(null,s);let y=new _Ae(f);if(!y.cksumValid)return d(null,s);let b=512*Math.ceil((y.size??0)/512);if(s+b+512>o||(s+=b+512,s>=o))return d(null,s);e.mtimeCache&&y.mtime&&e.mtimeCache.set(String(y.path),y.mtime),u=0,_2.default.read(a,f,0,512,s,p)};_2.default.read(a,f,0,512,s,p)};return new Promise((a,o)=>{r.on("error",o);let c="r+",d=(s,u)=>{if(s&&s.code==="ENOENT"&&c==="r+")return c="w+",_2.default.open(e.file,c,d);if(s||!u)return o(s);_2.default.fstat(u,(f,p)=>{if(f)return _2.default.close(u,()=>o(f));i(u,p.size,(h,_)=>{if(h)return o(h);let y=new f8i(e.file,{fd:u,start:_});r.pipe(y),y.on("error",o),y.on("close",a),S4I(r,t)})})};_2.default.open(e.file,c,d)})},E4I=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?Own({file:Uul.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>e.add(i)}):e.add(r)}),e.end()},S4I=async(e,t)=>{for(let r=0;r<t.length;r++){let i=String(t[r]);i.charAt(0)==="@"?await Own({file:Uul.default.resolve(String(e.cwd),i.slice(1)),noResume:!0,onReadEntry:n=>e.add(n)}):e.add(i)}e.end()},jwn=Xkt(P4I,w4I,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!zN_(e))throw new TypeError("file is required");if(e.gzip||e.brotli||e.zstd||e.file.endsWith(".br")||e.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!t?.length)throw new TypeError("no paths specified to add/replace")});var M4I=Xkt(jwn.syncFile,jwn.asyncFile,jwn.syncNoFile,jwn.asyncNoFile,(e,t=[])=>{jwn.validate?.(e,t),D4I(e)}),D4I=e=>{let t=e.filter;e.mtimeCache||(e.mtimeCache=new Map),e.filter=t?(r,i)=>t(r,i)&&!((e.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0)):(r,i)=>!((e.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0))};var RF_=ce(GQ(),1);var I4I=E3i();async function zF_({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:i,cliVersion:n,settings:a,loadAPIWorkspace:o}){let c,d={type:sh.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},s=t.dependencies[e];return s==null?d={type:sh.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${N4I(s)}`},async u=>{switch(s.type){case"version":c=await R4I({context:u,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:o});return;case"local":c=await T4I({context:u,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:o});return;default:fe(s)}}),c!=null?{didSucceed:!0,definition:c}:{didSucceed:!1,failure:d}}var NF_="dependencies";var B4I="metadata.json",C4I=".fern";function q4I(e){return ut(vr.of((0,CF_.homedir)()),me.of(C4I),me.of(NF_),me.of(e.organization),me.of(e.apiName),me.of(e.version))}async function T4I({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){if(n==null){t.failWithoutThrowing("Failed to load api definition");return}t.logger.info("Parsing...");let a=await n({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!a.didSucceed){t.failWithoutThrowing("Failed to load api definition",a.failures);return}t.logger.info("Modifying source filepath ...");let o=await a.workspace.getDefinition({context:t,relativePathToDependency:me.of(e.path)},i);return t.logger.info("Loaded..."),o}async function R4I({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){let a=q4I(e),o=ut(a,me.of(NF_)),c=ut(a,me.of(B4I)),d;if(!await ii(o)||!await ii(c)){t.logger.info("Downloading manifest...");let f=await I4I.definitionRegistry.get(Lul.FernFiddle.OrganizationId(e.organization),Lul.FernFiddle.ApiId(e.apiName),e.version);if(!f.ok){f.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:y=>{t.failWithoutThrowing("Failed to download API manifest",y)}});return}let p=f.body.yamlSchemaVersion!=null?parseInt(f.body.yamlSchemaVersion):void 0,h=uwn(r),_=uwn(f.body.cliVersion);if(p!=null){if(p>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${f.body.cliVersion}`);return}else if(p<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(h.major!==_.major||h.minor!==_.minor){t.failWithoutThrowing(`CLI version is ${f.body.cliVersion}. Expected ${h.major}.${h.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+f.body.definitionS3DownloadUrl),await(0,Rya.mkdir)(o,{recursive:!0});try{await z4I({s3PreSignedReadUrl:f.body.definitionS3DownloadUrl,absolutePathToLocalOutput:o})}catch(y){t.failWithoutThrowing("Failed to download API",y);return}d=f.body,await(0,Rya.writeFile)(c,JSON.stringify(d))}else d=JSON.parse((await(0,Rya.readFile)(c)).toString());if(t.logger.info("Parsing..."),n==null){t.failWithoutThrowing("Failed to load API");return}let s=await n({absolutePathToWorkspace:o,context:t,cliVersion:d.cliVersion,workspaceName:void 0});if(!s.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",s.failures);return}if(s.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await s.workspace.getDefinition({context:t},i)}async function z4I({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await BC.get(e,{responseType:"stream"}),i=await RF_.default.dir(),n=qF_.default.join(i.path,"api.tgz");await(0,TF_.pipeline)(r.data,(0,BF_.createWriteStream)(n)),await Qul({file:n,cwd:t})}function N4I(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:fe(e)}}async function FF_({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:i,settings:n,loadAPIWorkspace:a}){let o={},c={},d={};return await Promise.all(KI(t.packageMarkers).map(async([s,u])=>{if(u.contents.export==null)o[s]=u;else{let{export:f,...p}=u.contents;if(tj(p)>0)d[s]={type:sh.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:s};else{let h=rn(s);if(v7(t.namedDefinitionFiles).some(y=>y!==s&&y.startsWith(h)))d[s]={type:sh.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:h};else{let y=await zF_({dependencyName:typeof u.contents.export=="string"?u.contents.export:u.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:i,settings:n,loadAPIWorkspace:a});y.didSucceed?c[rn(s)]={definition:y.definition,url:typeof u.contents.export=="object"?u.contents.export.url:void 0}:d[s]=y.failure}}}})),tj(d)>0?{didSucceed:!1,failures:d}:{didSucceed:!0,packageMarkers:o,importedDefinitions:c}}var QF_=ce(require("path"),1);var Vul={};$t(Vul,{additionalProperties:()=>L4I,default:()=>W4I,definitions:()=>V4I,properties:()=>Q4I,required:()=>U4I,type:()=>F4I});var F4I="object",Q4I={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},product:{oneOf:[{$ref:"#/definitions/products.ProductDeclarationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},U4I=["name"],L4I=!1,V4I={"environments.ServerVariableSchema":{type:"object",properties:{id:{type:"string"},default:{oneOf:[{type:"string"},{type:"null"}]},values:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]}},required:["id"],additionalProperties:!1},"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"url-template":{oneOf:[{type:"string"},{type:"null"}]},variables:{oneOf:[{type:"array",items:{$ref:"#/definitions/environments.ServerVariableSchema"}},{type:"null"}]}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.EndpointSecuritySchemaDetails":{type:"object",additionalProperties:!1},"auth.EndpointSecuritySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"endpoint-security":{$ref:"#/definitions/auth.EndpointSecuritySchemaDetails"}},required:["endpoint-security"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"},{$ref:"#/definitions/auth.EndpointSecuritySchema"}]},"auth.AuthScope":{type:"string"},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"token-header":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},omit:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.TokenBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.InferredAuthenticatedRequestHeader":{type:"object",properties:{"response-property":{type:"string"},"header-name":{type:"string"},"value-prefix":{oneOf:[{type:"string"},{type:"null"}]}},required:["response-property","header-name"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchemaObject":{type:"object",properties:{endpoint:{type:"string"},"expiry-response-property":{oneOf:[{type:"string"},{type:"null"}]},"authenticated-request-headers":{oneOf:[{type:"array",items:{$ref:"#/definitions/auth.InferredAuthenticatedRequestHeader"}},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.InferredGetTokenEndpointSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.InferredGetTokenEndpointSchemaObject"}]},"auth.InferredBearerAuthSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},"get-token":{$ref:"#/definitions/auth.InferredGetTokenEndpointSchema"}},required:["scheme","get-token"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{anyOf:[{$ref:"#/definitions/auth.TokenBearerAuthSchema"},{$ref:"#/definitions/auth.InferredBearerAuthSchema"}]},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1},"products.ProductValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},versions:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"products.ProductValue":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductValueDetailed"}]},"products.ProductDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"products.ProductDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/products.ProductDeclarationHeaderObjectSchema"}]},"products.ProductDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/products.ProductValue"}},header:{$ref:"#/definitions/products.ProductDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},W4I={type:F4I,properties:Q4I,required:U4I,additionalProperties:L4I,definitions:V4I};var Wul={};$t(Wul,{additionalProperties:()=>G4I,default:()=>$4I,definitions:()=>K4I,properties:()=>H4I,type:()=>x4I});var x4I="object",H4I={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},G4I=!1,K4I={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/service.HttpEndpointAuth"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"method-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},$4I={type:x4I,properties:H4I,additionalProperties:G4I,definitions:K4I};var xul={};$t(xul,{additionalProperties:()=>X4I,default:()=>k4I,definitions:()=>Z4I,properties:()=>Y4I,type:()=>J4I});var J4I="object",Y4I={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},X4I=!1,Z4I={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ListValidationSchema":{type:"object",properties:{minItems:{oneOf:[{type:"integer"},{type:"null"}]},maxItems:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.MapValidationSchema":{type:"object",properties:{minProperties:{oneOf:[{type:"integer"},{type:"null"}]},maxProperties:{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"},{$ref:"#/definitions/validation.ListValidationSchema"},{$ref:"#/definitions/validation.MapValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"auth.AuthScope":{type:"string"},"service.HttpEndpointSecurityItem":{type:"object",additionalProperties:{type:"array",items:{$ref:"#/definitions/auth.AuthScope"}}},"service.HttpEndpointSecurity":{type:"array",items:{$ref:"#/definitions/service.HttpEndpointSecurityItem"}},"service.HttpEndpointAuth":{anyOf:[{type:"boolean"},{$ref:"#/definitions/service.HttpEndpointSecurity"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.RetriesDisabledSchema":{type:"object",properties:{disabled:{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"service.RetriesConfiguration":{anyOf:[{$ref:"#/definitions/service.RetriesDisabledSchema"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/service.HttpEndpointAuth"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},retries:{oneOf:[{$ref:"#/definitions/service.RetriesConfiguration"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"method-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},k4I={type:J4I,properties:Y4I,additionalProperties:X4I,definitions:Z4I};function UF_({files:e,absolutePathToDefinition:t}){let r,i={},n={},a={};for(let[o,c]of KI(e)){let d=c.contents,s=u=>{a[o]={type:sh.JSONSCHEMA_VALIDATION,error:u}};if(o===zC){let u=l5t(d,Vul);if(u.success){let f=TC.serialization.RootApiFileSchema.parseOrThrow(d);r={defaultUrl:f["default-url"],contents:f,rawContents:c.rawContents}}else s(u)}else if(QF_.default.basename(o)===Gv){let u=l5t(d,xul);if(u.success){let f=TC.serialization.PackageMarkerFileSchema.parseOrThrow(d);n[o]={defaultUrl:typeof f.export=="object"?f.export.url:void 0,contents:f,rawContents:c.rawContents}}else s(u)}else{let u=l5t(d,Wul);if(u.success){let f=TC.serialization.DefinitionFileSchema.parseOrThrow(d);i[o]={defaultUrl:void 0,contents:f,rawContents:c.rawContents,absoluteFilePath:ut(t,o)}}else s(u)}}return r==null?{didSucceed:!1,failures:{[me.of(zC)]:{type:sh.FILE_MISSING},...a}}:Object.keys(a).length>0?{didSucceed:!1,failures:a}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:r,packageMarkers:n}}var Z5=class extends W5t{type="fern";context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...i}){super(i),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){return(await this.toFernWorkspace({context:t},r)).definition}async toFernWorkspace({context:t},r){let i=(0,LF_.default)(r??{}),n=this.fernWorkspaces[i];if(n==null){let a=t||this.context,o=ut(this.absoluteFilePath,me.of(HM)),c=await Iil({absolutePathToWorkspace:this.absoluteFilePath,context:a}),d=await MN_(o,"{yml,yaml}"),s=await DN_(d);if(!s.didSucceed)return UMu(s.failures,a.logger),a.failAndThrow();let u=UF_({files:s.files,absolutePathToDefinition:o});if(!u.didSucceed)return UMu(u.failures,a.logger),a.failAndThrow();let f=await FF_({dependenciesConfiguration:c,structuralValidationResult:u,context:a,cliVersion:this.cliVersion,settings:r,loadAPIWorkspace:this.loadAPIWorkspace});if(!f.didSucceed)return UMu(f.failures,a.logger),a.failAndThrow();let p={absoluteFilePath:o,rootApiFile:u.rootApiFile,namedDefinitionFiles:u.namedDefinitionFiles,packageMarkers:f.packageMarkers,importedDefinitions:f.importedDefinitions};r?.auth!=null&&(p={...p,rootApiFile:{...p.rootApiFile,contents:{...p.rootApiFile.contents,auth:r?.auth}}}),n=new xZ({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:c,workspaceName:this.workspaceName,definition:p,cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[i]=n}return n}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var gU_=require("fs/promises");var dU_=ce(fU_(),1);async function yao(e){return(await(0,dU_.convertObj)(e,{})).openapi}var hU_=require("fs/promises");var pU_=require("fs/promises");async function Wya({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:i}){let n=null;try{let a=(await(0,pU_.readFile)(e,"utf8")).toString();try{n=JSON.parse(a)}catch{n=Mi.load(a,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return szc({data:t,overrides:n,allowNullKeys:i})}async function psl({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,hU_.readFile)(t)).toString(),n=await Mi.load(i);return r!=null?await Wya({absoluteFilePathToOverrides:r,context:e,data:n}):n}var vU_=require("fs/promises");var HDu=require("fs/promises");var xDu=ce(require("path"),1),_U_=ce(GQ(),1),hsl;async function V3I(){return hsl===void 0&&(hsl=(await _U_.default.dir({prefix:"fern-overlay-"})).path),hsl}async function yU_({absoluteFilePathToOverlay:e,absoluteFilePathToOpenAPI:t,data:r,context:i}){let n=await W3I(e,i);if(!x3I(n,i))return r;i.logger.debug(`Applying overlay "${n.info.title}" v${n.info.version}`);let a=ezc({data:r,overlay:n}),o=await V3I(),c=xDu.default.basename(t),d=`${xDu.default.parse(c).name}.overlaid.json`,s=xDu.default.join(o,d);return await(0,HDu.writeFile)(s,JSON.stringify(a,null,2),"utf8"),i.logger.info(`Wrote overlaid OpenAPI spec to: ${s}`),a}async function W3I(e,t){let r;try{r=await(0,HDu.readFile)(e,"utf8")}catch(i){return t.failAndThrow(`Failed to read overlay file at ${e}: ${i}`)}try{try{return JSON.parse(r)}catch{return Mi.load(r,{json:!0})}}catch(i){return t.failAndThrow(`Failed to parse overlay file at ${e}: ${i}`)}}function x3I(e,t){if(!e.overlay)return t.logger.error("Overlay file missing required 'overlay' version field"),!1;if(!e.info?.title||!e.info?.version)return t.logger.error("Overlay file missing required 'info.title' or 'info.version' field"),!1;if(!Array.isArray(e.actions)||e.actions.length===0)return t.logger.error("Overlay file must have at least one action"),!1;for(let r=0;r<e.actions.length;r++){let i=e.actions[r];if(!i?.target)return t.logger.error(`Overlay action at index ${r} missing required 'target' field`),!1;if(i.update===void 0&&!i.remove)return t.logger.error(`Overlay action at index ${r} must have either 'update' or 'remove'`),!1}return!0}var gao=ce(NEu(),1);var bU_=ce(NEu(),1),bao=ce(require("path"),1),vao=class extends bU_.BaseResolver{absolutePathToOpenAPIOverrides;absolutePathToOpenAPIOverlays;constructor({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r}){super(),this.absolutePathToOpenAPIOverrides=t,this.absolutePathToOpenAPIOverlays=r}resolveExternalRef(t,r){let i=super.resolveExternalRef(t,r);if(i.startsWith("http://")||i.startsWith("https://")||WMe(vr.of(i)))return i;if(this.absolutePathToOpenAPIOverlays!=null){let n=bao.default.resolve(bao.default.dirname(this.absolutePathToOpenAPIOverlays),r);if(WMe(vr.of(n)))return n}return this.absolutePathToOpenAPIOverrides!=null?bao.default.resolve(bao.default.dirname(this.absolutePathToOpenAPIOverrides),r):i}};async function _sl({absolutePathToOpenAPI:e,absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r,parsed:i}){return(i!=null?await(0,gao.bundle)({...FEu,doc:{source:new gao.Source(e,"<openapi>"),parsed:i},externalRefResolver:new vao({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r})}):await(0,gao.bundle)({...FEu,ref:e,externalRefResolver:new vao({absolutePathToOpenAPIOverrides:t,absolutePathToOpenAPIOverlays:r})})).bundle.parsed}function H3I(e,t){if(t.includes(e))return e;for(let r of t){let i=r.replace(/\{[^}]+\}/g,"([^/]+)");if(new RegExp(`^${i}$`).test(e))return r}}var G3I=["examples","example",nn.EXAMPLES,V3.REDOCLY_CODE_SAMPLES_CAMEL,V3.REDOCLY_CODE_SAMPLES_KEBAB];async function Oao({context:e,absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r,absolutePathToOpenAPIOverlays:i,loadAiExamples:n=!1}){let a=await _sl({absolutePathToOpenAPI:t}),o;r!=null?o=r:typeof a=="object"&&a[nn.OPENAPI_OVERIDES_FILEPATH]!=null&&(o=ut(rn(t),me.of(a[nn.OPENAPI_OVERIDES_FILEPATH])));let c=a;if(o!=null&&(c=await Wya({absoluteFilePathToOverrides:o,context:e,data:c,allowNullKeys:G3I})),i!=null&&(c=await yU_({absoluteFilePathToOverlay:i,absoluteFilePathToOpenAPI:t,context:e,data:c})),n){let d=ut(rn(t),me.of("ai_examples_override.yml"));try{let s=await(0,vU_.readFile)(d,"utf-8"),u=Mi.load(s);if(u?.paths&&c.paths){for(let[f,p]of Object.entries(u.paths))if(p&&typeof p=="object")for(let[h,_]of Object.entries(p)){let y=h.toLowerCase(),b=c.paths[f];if(!b&&c.paths){let v=H3I(f,Object.keys(c.paths));v&&(b=c.paths[v],e.logger.debug(`Matched override path "${f}" to OpenAPI path "${v}" using pattern matching`))}if(b&&typeof b=="object"){let O=b[y];if(O&&typeof O=="object"){let m=O;!m["x-fern-examples"]&&_["x-fern-examples"]&&(m["x-fern-examples"]=_["x-fern-examples"],e.logger.debug(`Added AI examples for ${h.toUpperCase()} ${f} from override file`))}}}}e.logger.debug(`Processed AI examples from ${d}`)}catch{}}return o!=null||i!=null||c!==a?await _sl({absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:o,absolutePathToOpenAPIOverlays:i,parsed:c}):c}var PHt=class{absoluteFilePath;constructor(t){this.absoluteFilePath=t}async loadDocuments({context:t,specs:r,loadAiExamples:i=!1}){let n=[];for(let a of r)try{let o=(await(0,gU_.readFile)(a.absoluteFilepath)).toString(),c=Jl(this.absoluteFilePath,a.source.file);a.source.relativePathToDependency!=null&&(c=ut(a.source.relativePathToDependency,c));let d=a.source.type==="protobuf"?q5.protobuf({file:c}):q5.openapi({file:c});if(o.includes("openapi")||o.includes("swagger"))try{let s=await Oao({absolutePathToOpenAPI:a.absoluteFilepath,context:t,absolutePathToOpenAPIOverrides:a.absoluteFilepathToOverrides,absolutePathToOpenAPIOverlays:a.absoluteFilepathToOverlays,loadAiExamples:i});if(Dil(s)){n.push({type:"openapi",value:s,source:d,namespace:a.namespace,settings:iIe({options:a.settings})});continue}else if(Tio(s)){(!s.schemes||s.schemes.length===0)&&(s.schemes=["https"]);let u=await yao(s);n.push({type:"openapi",value:u,source:d,namespace:a.namespace,settings:iIe({options:a.settings})});continue}}catch(s){t.logger.debug(`Failed to parse OpenAPI document at ${a.absoluteFilepath}: ${s}. Skipping...`);continue}if(o.includes("asyncapi"))try{let s=await psl({context:t,absoluteFilePath:a.absoluteFilepath,absoluteFilePathToOverrides:a.absoluteFilepathToOverrides});n.push({type:"asyncapi",value:s,source:d,namespace:a.namespace,settings:iIe({options:a.settings})});continue}catch(s){t.logger.error(`Failed to parse AsyncAPI document at ${a.absoluteFilepath}: ${s}. Skipping...`);continue}if(o.includes("openrpc"))try{let s=await psl({context:t,absoluteFilePath:a.absoluteFilepath,absoluteFilePathToOverrides:a.absoluteFilepathToOverrides});n.push({type:"asyncapi",value:s,source:d,namespace:a.namespace,settings:iIe({options:a.settings})});continue}catch(s){t.logger.error(`Failed to parse OpenRPC document at ${a.absoluteFilepath}: ${s}. Skipping...`);continue}t.logger.warn(`${a.absoluteFilepath} is not a valid OpenAPI, AsyncAPI, or OpenRPC file. Skipping...`)}catch(o){t.logger.error(`Failed to read or process file ${a.absoluteFilepath}: ${o}. Skipping...`);continue}return n}};var Va=class e{breadcrumbs=[];context;static STRING=Ir.TypeReference.primitive({v1:"STRING",v2:Ir.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Ir.TypeReference.container(Ir.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}};var mU_=require("fs/promises");var ysl=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:i,position:n,lineStart:a}=t;this._map[r]={line:i,position:n,lineStart:a}}t.children&&t.children.length>0&&t.children.forEach(i=>{this.resolveNode(i,(r==="."?"":r)+"."+i.path)})}iterFragments(t,r){for(let i=this._fragments.length-1;i>=0;i--){if(!this._fragments[i].path.startsWith(t)||this._fragments[i].path===t)continue;let n=this._fragments.pop();r(n)}}handleState(t,r){if(t==="close"){let i=r.result,n=r.kind,a=this._path.join(".");if(n==="scalar"){this._path.pop(),this._lastScalar=`${i}`;let{line:o,position:c,lineStart:d}=r;this._path.length===0?this._map["."+i]={line:o,position:c,lineStart:d}:this._fragments.push({path:this._path.join(".")+"."+i,line:o,position:c,lineStart:d})}else if(n==="mapping"){let o={path:a,children:[],line:0,position:0,lineStart:0},c=0;this.iterFragments(a,d=>{c++,!((!d.children||d.children.length===0)&&c%2===1)&&(this._path.length===1?this.resolveNode(d,d.path):(o.children.push({...d,path:d.path.slice(a.length+1)}),o.line=d.line,o.position=d.position,o.lineStart=d.lineStart))}),o.children&&o.children.length>0&&this._fragments.push(o),this._path.pop()}else if(n==="sequence"){let o={path:a,children:[],line:0,position:0,lineStart:0},c=new Set,d=i.length;this.iterFragments(a,s=>{c.has(s.position)||(d--,c.add(s.position),this._path.length===1?this.resolveNode(s,`${a}.${d}`):(o.children.push({...s,path:d.toString()}),o.line=s.line,o.position=s.position,o.lineStart=s.lineStart))}),o.children&&o.children.length>0&&this._fragments.push(o),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:i,position:n,lineStart:a}=r;this._map["."]={line:i,position:n,lineStart:a}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(n=>`${n}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let i=this._map[r];if(i)return{line:i.line+1,column:i.position-i.lineStart+1,position:i.position}}},OU_=ysl;var PR;(function(e){e.WARNING="warning",e.ERROR="error"})(PR||(PR={}));var mIe=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new bsl({logger:t,relativePathToFile:me.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,i=0;for(let n of this.errors){let a=n.path?n.path.join("->"):"",o=`${n.message}|${n.level||PR.WARNING}|${a}`;r.has(o)?i++:(r.add(o),t.push(n))}return this.errors=t,i}getErrorStats(){this.dedupe();let t=0,r=0;for(let i of this.errors)i.level===PR.ERROR?t++:(i.level===PR.WARNING||i.level===void 0)&&r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors){let i=r.level??PR.WARNING;if(!(i===PR.WARNING&&!t))switch(i){case PR.ERROR:if(this.logger.log(na.Debug,r.message),r.path&&r.path.length>0){let n=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),a=n?`${this.relativeFilepathToSpec}:${n.line}:${n.column}`:r.path.join(" -> ");this.logger.log(na.Debug,` - at location (${a})`)}break;case PR.WARNING:if(this.logger.log(na.Warn,r.message),r.path&&r.path.length>0){let n=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),a=n?`${this.relativeFilepathToSpec}:${n.line}:${n.column}`:r.path.join(" -> ");this.logger.log(na.Warn,` - at location (${a})`)}r.resolution&&this.logger.log(na.Warn,` - resolution: ${r.resolution}`);break}}}},bsl=class{logger;relativePathToFile;map=new OU_;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,mU_.readFile)(this.relativePathToFile,"utf-8");Mi.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(na.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}};var kq=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=X7({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples,this.documentBaseDir=t.documentBaseDir}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=An(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i}){let n=this.spec,a=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(o=>o.replace(/~1/g,"/"));for(let o of a){if(typeof n!="object"||n==null)return i||this.errorCollector.collect({level:PR.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};n=n[o]}return n==null?(i||this.errorCollector.collect({level:PR.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:n}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,i,n=!1,a=null,o;if(this.isExternalReference(t.$ref)){n=!0;let s=t.$ref.split("#"),u=s[0];if(i=s[1],!u)return{resolved:!1};o=u;let f=await fetch(u);if(!f.ok)return{resolved:!1};try{let p=await f.text();try{a=JSON.parse(p),r=a}catch{a=Mi.load(p),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let c=i??t.$ref;if(c==null||typeof c!="string")return{resolved:!1};let d=c.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of d){if(typeof r!="object"||r==null)return{resolved:!1};r=r[s]}if(r==null)return{resolved:!1};if(n&&typeof r=="object"&&r!==null){let s=new Set;s.add(t.$ref),r=await this.resolveNestedExternalReferences(r,a,s,o)}return{resolved:!0,value:r}}async resolveNestedExternalReferences(t,r,i,n){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let o=[];for(let c of t)o.push(await this.resolveNestedExternalReferences(c,r,i,n));return o}if(this.isReferenceObject(t)){let o=t.$ref;if(this.isExternalReference(o)){if(i.has(o))return t;i.add(o);let c=await this.resolveMaybeExternalReference({$ref:o});if(i.delete(o),c.resolved)return c.value}else{let c=`${n}${o}`;if(i.has(c))return t;i.add(c);let d=r,s=o.substring(2).split("/").map(u=>u.replace(/~1/g,"/").replace(/~0/g,"~"));for(let u of s){if(typeof d!="object"||d===null)return t;d=d[u]}if(d!=null){let u=await this.resolveNestedExternalReferences(d,r,i,n);return i.delete(o),u}i.delete(o)}return t}let a={};for(let[o,c]of Object.entries(t))typeof c=="object"&&c!==null?a[o]=await this.resolveNestedExternalReferences(c,r,i,n):a[o]=c;return a}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,{value:t.example}])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:i}){if(this.isReferenceObject(t)){let n=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:i});return n.resolved?n.value:void 0}return t}resolveExampleRecursively({example:t,breadcrumbs:r,maxDepth:i=10}){let n=t,a=0;for(;this.isReferenceObject(n);){if(a>=i){this.errorCollector.collect({message:`Maximum reference depth (${i}) exceeded while resolving example reference`,path:r});return}let o=this.resolveReference({reference:n,breadcrumbs:r,skipErrorCollector:!0});if(!o.resolved)return;n=o.value,a++}return n}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let a=this.resolveReference({reference:r});if(!a.resolved)return;r=a.value}let{readOnly:i,writeOnly:n}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(i&&n)){if(i)return k2t.ReadOnly;if(n)return k2t.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,i=!0;for(let n of t.allOf){let a=n;if(this.isReferenceObject(n)){let c=this.resolveReference({reference:n});if(!c.resolved)continue;a=c.value}let o=this.getReadOnlyWriteOnlyFromSchema(a);r=r&&o.readOnly,i=i&&o.writeOnly}return{readOnly:r,writeOnly:i}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let n=new BN.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(n!=null)return n.audiences}getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=this.resolveReference({reference:t});if(!a.resolved)return;t=a.value}let n=new BN.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:lR.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return hi.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:t,displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://"))}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t||"summary"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t&&typeof t.summary=="string"&&t.summary.length>0}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}};var Nl=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let i=t[this.key];if(i!=null)return i;if(r!=null)return t[r]}};var BN={};$t(BN,{AudienceExtension:()=>GDu,FernAvailabilityExtension:()=>KDu,FernEnumExtension:()=>$Du,FernIgnoreExtension:()=>Bwn,FernOptionalExtension:()=>JDu,FernTypeExtension:()=>kDu,FernTypeNameExtension:()=>eIu,SdkGroupNameExtension:()=>YDu,SdkMethodNameExtension:()=>XDu,ServerFromOperationNameExtension:()=>ZDu});var GDu=class extends Nl{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}};var KDu=class extends Nl{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return lR.InDevelopment;case"PRE_RELEASE":case"BETA":return lR.PreRelease;case"GENERAL_AVAILABILITY":case"GA":return lR.GeneralAvailability;case"DEPRECATED":return lR.Deprecated;default:return}}};var K3I=Bt.object({snake:Bt.string().optional(),camel:Bt.string().optional(),screamingSnake:Bt.string().optional(),pascal:Bt.string().optional()}),$3I=Bt.object({description:Bt.string().optional(),name:Bt.string().optional(),casing:K3I.optional()}),AU_=Bt.record($3I);var $Du=class extends Nl{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=AU_.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var Bwn=class extends Nl{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var JDu=class extends Nl{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var YDu=class extends Nl{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var XDu=class extends Nl{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var ZDu=class extends Nl{operation;key="x-fern-server-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation,"x-name");if(!(t==null||typeof t!="string"))return t}};var kDu=class extends Nl{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var eIu=class extends Nl{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}};var jHt=class extends Va{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:i}){super({breadcrumbs:t,context:r}),this.audiences=i,this.irGraph=new Jjn(i),this.ir={auth:{docs:void 0,requirement:Ir.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Ir.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((i,n)=>!new Bwn({breadcrumbs:[...r,String(n)],operation:i,context:this.context}).convert()).map((i,n)=>this.removeXFernIgnores({document:i,breadcrumbs:[...r,String(n)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([i,n])=>!new Bwn({breadcrumbs:[...r,i],operation:n,context:this.context}).convert()).map(([i,n])=>[i,this.removeXFernIgnores({document:n,breadcrumbs:[...r,i]})])):t}finalizeIr(){let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(t=this.filterIrForAudiences(t));let r=this.context.exampleGenerationArgs,i=ral({ir:t,exampleGeneration:r});if(this.context.generateV1Examples){let n=uno({ir:t,exampleGeneration:r});return{...t,...n,...i}}return{...t,...i}}filterIrForAudiences(t){let r=this.irGraph.getFilteredEndpoints(),i=this.irGraph.getFilteredChannels(),n=this.irGraph.getFilteredWebhooks();for(let a of Object.values(t.services)){let o=[];for(let c of a.endpoints)r.has(c.id)&&o.push(c);a.endpoints=o}return t.websocketChannels=Object.fromEntries(Object.entries(t.websocketChannels??{}).filter(([a])=>i.has(a))),t.webhookGroups=Object.fromEntries(Object.entries(t.webhookGroups).map(([a,o])=>{let c=o.filter(d=>d.id!=null&&n.has(d.id));return[a,c]})),t}async resolveAllExternalRefs({spec:t}){let r=[t];for(;r.length>0;){let i=r.shift();i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let i=0;i<t.length;i++)t[i]=await this.resolveReferenceChain(t[i],r)}async resolveExternalRefsInObject(t,r){for(let[i,n]of Object.entries(t))t[i]=await this.resolveReferenceChain(n,r)}async resolveReferenceChain(t,r){let i=t;if(!this.context.isReferenceObject(i))return r.push(i),t;for(;this.context.isReferenceObject(i);){let n=this.context.isExternalReference(i.$ref),a=await this.context.resolveMaybeExternalReference(i);if(a.resolved){if(i=a.value,n)return i}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:i="openapi"}){return i==="openapi"?!r.some(n=>n.url===t.url&&"x-fern-server-name"in n&&"x-fern-server-name"in t&&n["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(n=>n.url===t.url&&"name"in n&&"name"in t&&n.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:i,endpointGroupDisplayName:n,serviceName:a}){let o=this.context.getGroup({groupParts:i,namespace:this.context.namespace}),c=this.getOrCreatePackage({group:i}),d=[...o].map(f=>this.context.casingsGenerator.generateName(f)),s=d[d.length-1];c.service==null&&(c.service=a??`service_${o.map(f=>An(f)).join("/")}`),this.ir.services[c.service]==null&&(this.ir.services[c.service]=this.createNewService({allParts:d,finalpart:s,endpointGroupDisplayName:n})),this.ir.services[c.service]?.endpoints.push(t);let u=this.ir.services[c.service];u!=null&&(this.irGraph.addEndpoint(u,t),this.irGraph.markEndpointForAudience(u.name,[t],r))}addWebhookToIr({webhook:t,operationId:r,audiences:i,group:n}){let a=n?.join(".")??r,o=this.getOrCreatePackage({group:n});this.ir.webhookGroups[a]==null&&(this.ir.webhookGroups[a]=[]),this.ir.webhookGroups[a].push(t),o.webhooks=a;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),i!=null&&this.irGraph.markWebhookForAudiences(c,t,i)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:i,websocketGroup:n}){let a=An(n?.join(".")),o=An(r),c=this.context.namespace?`${An(this.context.namespace)}/`:"",d=a?`channel_${c}${a}`:`channel_${c}${o}`,s=n?this.getOrCreatePackage({group:n}):this.getOrCreatePackage({group:[o]});this.ir.websocketChannels={...this.ir.websocketChannels,[d]:t},d!==""?s.websocket==null&&(s.websocket=d):this.ir.rootPackage.websocket="";let u=this.context.createFernFilepath();this.irGraph.addChannel(u,d,t),i!=null&&this.irGraph.markChannelForAudiences(u,d,i)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,r!=null)for(let[i,n]of Object.entries(t??{}))r[i]!=null&&this.irGraph.markEnvironmentForAudiences(n,r[i])}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:i,inlinedTypes:n}=r,o=Object.keys(n).some(c=>c===t)?`${t}Wrapper`:t;this.addTypeToPackage(o),this.addTypesToIr({...n,[o]:i})}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,i])=>[r,i.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let i of r.endpoints)i.baseUrl==null&&(i.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:i}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:i,basePath:eI(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(n=>An(n))),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n]??"",c=`subpackage_${r.slice(0,n+1).join("/")}`;this.ir.subpackages[c]==null&&(this.ir.subpackages[c]={name:this.context.casingsGenerator.generateName(a),displayName:void 0,...this.createPackage({name:a})});let d=this.ir.subpackages[c];i.subpackages.includes(c)||i.subpackages.push(c),i=d}return i}};var $A={};$t($A,{AbstractConverters:()=>gsl,ExampleConverter:()=>NU,SchemaConverters:()=>vsl,ServersConverter:()=>vAe});var gsl={};$t(gsl,{AbstractMediaTypeObjectConverter:()=>iIu,AbstractParameterConverter:()=>nIu});var J3I=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/;function Y3I(e){return e.type==="array"||e.properties||e.oneOf||e.anyOf||e.allOf||e.additionalProperties?!1:!!(e.type==="string"||e.type==="number"||e.type==="integer"||e.type==="boolean"||e.const!==void 0||Array.isArray(e.enum)&&e.enum.length>0)}function PU_(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var NU=class e extends Va{MAX_DEPTH=12;EXAMPLE_STRING=pa.STRING;EXAMPLE_NUMBER=pa.DOUBLE;EXAMPLE_BOOLEAN=pa.BOOLEAN;EXAMPLE_INTEGER=pa.INT;EXAMPLE_DATE=pa.DATE;EXAMPLE_DATE_TIME=pa.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,exampleGenerationStrategy:o,generateOptionalProperties:c=!1,seenRefs:d=new Set}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.exampleGenerationStrategy=o,this.generateOptionalProperties=c,this.seenRefs=d}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let i=this.schema.$ref;if(this.seenRefs.has(i))return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(t==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]};if(typeof t!="object")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]};if("nullable"in t&&t.nullable===!0&&this.example===null)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.maybeConvertLiteralFernType(t);return r??(Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]})}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof i=="boolean"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i??r,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let i=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return i!==void 0&&t.enum?.includes(i)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i,errors:[]}:{isValid:r,coerced:!1,usedProvidedExample:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,i=r?.default;return typeof i=="number"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:i,maximum:n,exclusiveMinimum:a,exclusiveMaximum:o}=r,c;a!=null?typeof a=="boolean"?c=i!=null?i+Math.max(Number.EPSILON,Math.abs(i)*1e-10):void 0:c=a+Math.max(Number.EPSILON,Math.abs(a)*1e-10):i!=null&&(c=i);let d;return o!=null?typeof o=="boolean"?d=n!=null?n-Math.max(Number.EPSILON,Math.abs(n)*Number.EPSILON):void 0:d=o-Math.max(Number.EPSILON,Math.abs(o)*Number.EPSILON):n!=null&&(d=n),c!==void 0&&d!==void 0?(t<c||t>d)&&(t=c+(d-c)/2):c!==void 0&&t<c?t=c+Math.abs(c*.1):d!==void 0&&t>d&&(t=d-Math.abs(d*.1)),Number(Number(t).toPrecision(3))}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,i=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??i,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,i=this.example??t.example,a=(Array.isArray(i)?i:[i]).map(d=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:d,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),o=a.every(d=>d?.isValid??!1)&&!r,c=!r&&a.some(d=>d.usedProvidedExample);return{isValid:o,coerced:!1,usedProvidedExample:c,validExample:a.map(d=>d.validExample),errors:o?[]:a.flatMap(d=>d.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=Object.entries(t.properties??{}).map(([f,p])=>{if(typeof p!="object")return{key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(p)&&!this.isRequiredProperty({key:f,resolvedSchema:t}))return{key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in p&&p.readOnly===!0&&"writeOnly"in p&&p.writeOnly===!0)return{key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in p&&p.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in p&&p.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let h=!(f in r)||!("nullable"in p)&&r[f]==null||"nullable"in p&&p.nullable===!0&&r[f]===void 0,_=!t.required?.includes(f);if(h&&_){if(this.example===void 0&&this.generateOptionalProperties){let y=this.maybeResolveSchemaExample(p),b=new e({breadcrumbs:[...this.breadcrumbs,f],context:this.context,schema:p,example:y,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:f,result:b.convert()}}return{key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let y=r[f],b=y!==void 0?y:this.maybeResolveSchemaExample(p),O=new e({breadcrumbs:[...this.breadcrumbs,f],context:this.context,schema:p,example:b,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:f,result:O}}}),n=(t.allOf??[]).map((f,p)=>{let h=this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:[...this.breadcrumbs,`allOf[${p}]`],skipErrorCollector:!0});return h&&this.isConstraintOnlySchema(h)?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:new e({breadcrumbs:[...this.breadcrumbs,`allOf[${p}]`],context:this.context,schema:{...t,...f,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()}),a=this.example!==void 0&&(i.some(({result:f})=>f.usedProvidedExample)||n.some(f=>f.usedProvidedExample)),o=Object.fromEntries(i.map(({key:f,result:p})=>[f,p.validExample]).filter(([f,p])=>p!==void 0));for(let f of n)if(typeof f.validExample=="object"&&f.validExample!==null){let p=f.validExample;o={...o,...Object.fromEntries(Object.entries(p).filter(([h,_])=>_!==void 0))}}let c=[],d=this.collectAllPropertyKeys(t),s=Object.keys(r).filter(f=>!d.has(f));if(s.length>0)if(t.additionalProperties===!1)s.forEach(f=>{let p=[...this.breadcrumbs,f].join("."),h={message:`Found unexpected property '${f}' in example. This property does not exist in the schema${p?` at path: ${p}`:""}`,path:[...this.breadcrumbs,f]};c.push({key:f,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[h]}})});else if(t.additionalProperties===!0||t.additionalProperties===void 0)s.forEach(f=>{c.push({key:f,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[f],errors:[]}})});else{let f=t.additionalProperties;s.forEach(p=>{let _=new e({breadcrumbs:[...this.breadcrumbs,p],context:this.context,schema:f,example:r[p],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();c.push({key:p,result:_})})}for(let{key:f,result:p}of c)p.validExample!==void 0&&o[f]===void 0&&(o[f]=p.validExample);let u=i.every(f=>f.result.isValid)&&n.every(f=>f.isValid)&&c.every(({result:f})=>f.isValid);if(Object.keys(o).length===0){let f=n.find(p=>p.validExample!==void 0&&(typeof p.validExample!="object"||p.validExample===null));f&&(o=f.validExample)}return{isValid:u,coerced:!1,usedProvidedExample:a,validExample:o,errors:[...i.flatMap(({result:f})=>f.errors),...n.flatMap(f=>f.errors),...c.flatMap(({result:f})=>f.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((c,d)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${d}]`],context:this.context,schema:{...t,type:c},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),i=r.some(c=>c?.isValid??!1),a=r.find(c=>c.isValid)?.validExample??r[0]?.validExample??null,o=r.some(c=>c.usedProvidedExample);return{isValid:i,coerced:!1,usedProvidedExample:o,validExample:a,errors:i?[]:r.flatMap(c=>c?.errors??[])}}convertUnion({resolvedSchema:t,unionType:r}){let i=r==="oneOf"?t.oneOf:t.anyOf;if(!(r in t)||i==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};let n=this.example??this.maybeResolveSchemaExample(t);if(this.example===void 0){let p=[];for(let _ of i){if(!_)continue;let y=this.context.resolveMaybeReference({schemaOrReference:_,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});y&&p.push(y)}if(p.length>0&&p.every(_=>Y3I(_))){let _=p.findIndex(y=>PU_(y)!==void 0);if(_!==-1){let y=i[_],b=p[_];if(y&&b){let v=PU_(b),m=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${_}]`],context:this.context,schema:r==="oneOf"?{...t,...y,oneOf:void 0}:y,example:v,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(m.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:m.validExample,errors:[]}}}}}let a=[],o=null,c=null;for(let p=0;p<i.length;p++){let h=i[p];if(!h)continue;let _=r==="oneOf"?{...t,...h,oneOf:void 0}:h,y=n??this.maybeResolveSchemaExample(_),v=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${p}]`],context:this.context,schema:_,example:y,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(v.isValid&&!v.coerced&&v.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:v.validExample,errors:[]};if(v.isValid&&!v.coerced)return{isValid:!0,coerced:!1,usedProvidedExample:v.usedProvidedExample,validExample:v.validExample,errors:[]};a.push(v),v.isValid&&v.usedProvidedExample&&c===null&&(c=v),v.isValid&&o===null&&(o=v)}let d=c??o,s=d!==null,u=d?.validExample??a[0]?.validExample,f=d?.usedProvidedExample??!1;return{isValid:s,coerced:!1,usedProvidedExample:f,validExample:u,errors:s?[]:a.flatMap(p=>p.errors)}}convertOneOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"oneOf"})}convertAnyOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"anyOf"})}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){if("example"in t)return t.example;if("examples"in t){let i=t.examples;if(Array.isArray(i)&&i.length>0)return i[0];if(i!=null&&typeof i=="object")return Object.values(i)[0]}let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r){let i=r.examples;return Array.isArray(i)&&i.length>0?i[0]:Object.values(i??{})[0]}}}maybeConvertLiteralFernType(t){let r=t["x-fern-type"];if(typeof r!="string")return;let i=r.match(J3I);if(i!=null){if(i[1]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i[1],errors:[]};if(i[2]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:i[2]==="true",errors:[]}}}isConstraintOnlySchema(t){if(t.type!==void 0||t.properties!==void 0||t.allOf!==void 0||t.oneOf!==void 0||t.anyOf!==void 0||"items"in t||t.additionalProperties!==void 0||t.enum!==void 0||t.const!==void 0)return!1;let r=new Set(["required","description","title","deprecated","readOnly","writeOnly","nullable","example","examples","default","minLength","maxLength","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minItems","maxItems","uniqueItems","pattern","format"]),i=Object.keys(t);return i.length>0&&i.every(n=>r.has(n))}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}collectAllPropertyKeys(t,r=new Set){let i=new Set;if(t.properties)for(let n of Object.keys(t.properties))i.add(n);for(let n of t.allOf??[]){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(a){let o=this.context.isReferenceObject(n)?n.$ref:JSON.stringify(a);if(!r.has(o)){r.add(o);let c=this.collectAllPropertyKeys(a,r);for(let d of c)i.add(d)}}}for(let n of[...t.oneOf??[],...t.anyOf??[]]){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(a){let o=this.context.isReferenceObject(n)?n.$ref:JSON.stringify(a);if(!r.has(o)){r.add(o);let c=this.collectAllPropertyKeys(a,r);for(let d of c)i.add(d)}}}return i}};var vsl={};$t(vsl,{ArraySchemaConverter:()=>Kya,EnumSchemaConverter:()=>xya,ObjectSchemaConverter:()=>Hya,OneOfSchemaConverter:()=>Cwn,PrimitiveSchemaConverter:()=>Gya,SchemaConverter:()=>Den,SchemaOrReferenceConverter:()=>rH});function jU_(e){return xq({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return hi.primitive({v1:"BASE_64",v2:Cn.base64({})});case"BOOLEAN":return hi.primitive({v1:"BOOLEAN",v2:Cn.boolean({default:void 0})});case"DATE":return hi.primitive({v1:"DATE",v2:Cn.date({})});case"DATE_TIME":return hi.primitive({v1:"DATE_TIME",v2:Cn.dateTime({})});case"FLOAT":return hi.primitive({v1:"FLOAT",v2:Cn.float({default:void 0,validation:void 0})});case"DOUBLE":return hi.primitive({v1:"DOUBLE",v2:Cn.double({default:void 0,validation:void 0})});case"UINT":return hi.primitive({v1:"UINT",v2:Cn.uint({default:void 0,validation:void 0})});case"UINT_64":return hi.primitive({v1:"UINT_64",v2:Cn.uint64({default:void 0,validation:void 0})});case"INTEGER":return hi.primitive({v1:"INTEGER",v2:Cn.integer({default:void 0,validation:void 0})});case"LONG":return hi.primitive({v1:"LONG",v2:Cn.long({default:void 0,validation:void 0})});case"STRING":return hi.primitive({v1:"STRING",v2:Cn.string({default:void 0,validation:void 0})});case"UUID":return hi.primitive({v1:"UUID",v2:Cn.uuid({})});case"BIG_INTEGER":return hi.primitive({v1:"BIG_INTEGER",v2:Cn.bigInteger({default:void 0})});default:return}},unknown:()=>hi.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return hi.container(Js.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return hi.container(Js.list(t))},optional:t=>{if(t!=null)return hi.container(Js.optional(t))},nullable:t=>{if(t!=null)return hi.container(Js.nullable(t))},set:t=>{if(t!=null)return hi.container(Js.set(t))},literal:t=>hi.container(Js.literal(t._visit({string:r=>sU.string(r),boolean:r=>sU.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var xya=class extends Va{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),o=this.maybeFernEnum?.[a],c=o?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:c,wireValue:a}),docs:o?.description,availability:void 0,casing:o?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:Yl.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var tIu=class extends Va{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:i}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=i}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=hi.container(Js.map({keyType:Va.STRING,valueType:hi.unknown()}));return{type:Yl.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new rH({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let i=hi.container(Js.map({keyType:Va.STRING,valueType:r.type})),n=new Set;for(let a of r.schema?.typeDeclaration.referencedTypes??[])n.add(a);for(let a of Object.keys(r.inlinedTypes))n.add(a);return{type:Yl.alias({aliasOf:i,resolvedType:i}),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}};function mao({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],o={},c={},d=new Set;for(let[s,u]of Object.entries(e??{})){let f=[...r,"properties",s];if(typeof u!="object"){n.collect({message:`Schema property ${s} should be an object`,path:f});continue}let p=X3I(r,u,i)??i.convertBreadcrumbsToName(f),h="nullable"in u?u.nullable:!1,y=new rH({context:i,breadcrumbs:f,schemaOrReference:u,schemaIdOverride:p,wrapAsOptional:!t.includes(s),wrapAsNullable:h}).convert();if(y!=null){a.push({name:i.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),valueType:y.type,docs:u.description,availability:y.availability,propertyAccess:i.getPropertyAccess(u),v2Examples:y.schema?.typeDeclaration?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),o={...o,...y.inlinedTypes},y.schema?.typeDeclaration.referencedTypes!=null&&y.schema.typeDeclaration.referencedTypes.forEach(b=>{d.add(b)});for(let b of y.schema?.audiences??[])c[b]==null&&(c[b]=new Set),c[b].add(s)}}for(let s of Object.keys(o))d.add(s);return{convertedProperties:a,propertiesByAudience:c,inlinedTypesFromProperties:o,referencedTypes:d}}function X3I(e,t,r){return r.isReferenceObject(t)?void 0:new BN.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}var Hya=class extends Va{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:Yl.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set};let{convertedProperties:r,inlinedTypesFromProperties:i,referencedTypes:n,propertiesByAudience:a}=mao({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),o=[],c=n,d=this.schema.required!=null&&this.schema.required.length>0,s=i,u=a;for(let[f,p]of(this.schema.allOf??[]).entries()){let h=[...this.breadcrumbs,"allOf",f.toString()],_;if(this.context.isReferenceObject(p)){let m=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:h});if(m==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${f}] reference could not be resolved. Skipping: ${JSON.stringify(p)}`);continue}if(_=m,typeof _.additionalProperties=="boolean"&&_.additionalProperties&&(t=!0),!d||Object.keys(_.properties??{}).every(g=>!this.schema.required?.includes(g))){this.addTypeReferenceToExtends({reference:p,breadcrumbs:h,extends_:o,referencedTypes:c});continue}}else _=p;typeof _.additionalProperties=="boolean"&&_.additionalProperties&&(t=!0);let{convertedProperties:y,inlinedTypesFromProperties:b,referencedTypes:v,propertiesByAudience:O}=mao({properties:_.properties??{},required:[...this.schema.required??[],..._.required??[]],breadcrumbs:h,context:this.context,errorCollector:this.context.errorCollector});r.push(...y),s={...s,...b},u={...u,...O},v.forEach(m=>{c.add(m)})}for(let f of Object.keys(s))c.add(f);return{type:Yl.object({properties:r,extends:o.map(f=>this.context.typeReferenceToDeclaredTypeName(f)).filter($s),extendedProperties:[],extraProperties:t}),propertiesByAudience:u,referencedTypes:c,inlinedTypes:s}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:i,referencedTypes:n}){let a=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});a.ok&&i.push(a.reference);let o=this.context.getTypeIdFromSchemaReference(t);o!=null&&n.add(o)}};var rIu=class extends Nl{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}};var Cwn=class extends Va{schema;id;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlinedTypes:a}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n}convert(){return this.shouldConvertAsNullableSchemaOrReference()?this.convertAsNullableSchemaOrReference():new rIu({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1?this.convertAsUndiscriminatedUnion():this.schema.discriminator!=null?this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}filterDiscriminantFromSchema(t,r){if(t.properties==null||!(r in t.properties))return t;let{[r]:i,...n}=t.properties,a=t.required?.filter(o=>o!==r);return{...t,properties:n,required:a}}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=this.schema.discriminator.propertyName,r=[],i=new Set,n={};for(let[s,u]of Object.entries(this.schema.discriminator.mapping??{})){let f=this.context.getTypeIdFromSchemaReference({$ref:u}),p=[...this.breadcrumbs,"discriminator","mapping",s],h=this.context.resolveReference({reference:{$ref:u},breadcrumbs:p}),_={$ref:u};h.resolved&&h.value.properties!=null&&t in h.value.properties&&(_=this.filterDiscriminantFromSchema(h.value,t));let y=new rH({context:this.context,schemaOrReference:_,schemaIdOverride:f??void 0,breadcrumbs:p});f!=null&&i.add(f);let b=y.convert();if(b?.type!=null&&f!=null){for(let O of Object.keys(b?.inlinedTypes??{}))i.add(O);for(let O of b.schema?.typeDeclaration.referencedTypes??[])i.add(O);let v=this.context.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s});r.push({docs:void 0,discriminantValue:v,availability:b.availability,displayName:s,shape:cU.samePropertiesAsObject({typeId:f,name:this.context.casingsGenerator.generateName(f),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:s})}),n={...n,...b.inlinedTypes}}}let{convertedProperties:a,referencedTypes:o,inlinedTypesFromProperties:c}=mao({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});i=new Set([...i,...o]);let d=[];for(let[s,u]of(this.schema.allOf??[]).entries()){let f=[...this.breadcrumbs,"allOf",s.toString()];if(this.context.isReferenceObject(u)){let p=this.context.convertReferenceToTypeReference({reference:u,breadcrumbs:f});if(p.ok){let _=this.context.typeReferenceToDeclaredTypeName(p.reference);_!=null&&d.push(_)}let h=this.context.getTypeIdFromSchemaReference(u);h!=null&&i.add(h);continue}}for(let s of Object.keys({...n,...c}))i.add(s);return{type:Yl.union({baseProperties:a,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:d,types:r}),referencedTypes:i,inlinedTypes:{...n,...c}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,i={},n=[...this.schema.oneOf??[],...this.schema.anyOf??[]].filter(a=>!this.context.isReferenceObject(a));for(let[a,o]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(o)){let p;if(this.context.isReferenceObjectWithIdentifier(o))p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.summary??o.title??o.name??o.messageId,displayNameOverrideSource:"reference_identifier"});else if(this.getDiscriminatorKeyForRef(o)!=null){let _=this.getDiscriminatorKeyForRef(o);p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:_,displayNameOverrideSource:"discriminator_key"})}else p=this.context.convertReferenceToTypeReference({reference:o,displayNameOverride:o.$ref.split("/").pop(),displayNameOverrideSource:"schema_identifier"});p.ok&&t.push({type:p.reference,docs:o.description});let h=this.context.getTypeIdFromSchemaReference(o);h!=null&&r.add(h);continue}let c=this.extendSubSchema(o),d=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),s=o.title,f=new Den({context:this.context,id:d,nameOverride:s,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:c??o}).convert();if(f!=null){let p=f.convertedSchema.typeDeclaration.shape;p.type==="alias"&&this.typeReferenceIsWrappedPrimitive(p.aliasOf)?t.push({type:p.aliasOf,docs:o.description}):p.type==="object"&&p.properties.length===0&&p.extends.length===0?t.push({type:hi.container(Js.map({keyType:Va.STRING,valueType:hi.unknown()})),docs:o.description}):(t.push({type:this.context.createNamedTypeReference(d,s),docs:o.description}),i={...i,...f.inlinedTypes,[d]:f.convertedSchema}),f.convertedSchema.typeDeclaration.referencedTypes.forEach(h=>{r.add(h)})}}return{type:Yl.undiscriminatedUnion({members:t}),referencedTypes:r,inlinedTypes:i}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=new rH({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:Yl.alias({aliasOf:n,resolvedType:n}),referencedTypes:i.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:i.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return hi.container(Js.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,i])=>i===t.$ref)?.[0]}};var Gya=class extends Va{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return hi.container(Js.literal(sU.string(t)));if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return hi.primitive({v1:Ps.Date,v2:Cn.date({})});if(this.schema.format==="date-time")return hi.primitive({v1:Ps.DateTime,v2:Cn.dateTime({})})}return hi.primitive({v1:"STRING",v2:Cn.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return hi.primitive({v1:"DOUBLE",v2:Cn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return hi.primitive({v1:"FLOAT",v2:Cn.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return hi.primitive({v1:"INTEGER",v2:Cn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return hi.primitive({v1:"LONG",v2:Cn.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return hi.primitive({v1:"UINT",v2:Cn.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return hi.primitive({v1:"UINT_64",v2:Cn.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return hi.primitive({v1:"DOUBLE",v2:Cn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return hi.primitive({v1:"DOUBLE",v2:Cn.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return hi.primitive({v1:"FLOAT",v2:Cn.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return hi.primitive({v1:"INTEGER",v2:Cn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return hi.primitive({v1:"LONG",v2:Cn.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return hi.primitive({v1:"UINT",v2:Cn.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return hi.primitive({v1:"UINT_64",v2:Cn.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return hi.primitive({v1:"INTEGER",v2:Cn.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?hi.container(Js.literal(sU.boolean(t))):hi.primitive({v1:"BOOLEAN",v2:Cn.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){let r=t.minimum,i=t.maximum,n,a;return typeof t.exclusiveMinimum=="boolean"?n=t.exclusiveMinimum:typeof t.exclusiveMinimum=="number"&&(r=t.exclusiveMinimum,n=!0),typeof t.exclusiveMaximum=="boolean"?a=t.exclusiveMaximum:typeof t.exclusiveMaximum=="number"&&(i=t.exclusiveMaximum,a=!0),{max:i,min:r,exclusiveMax:a,exclusiveMin:n,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var Z3I=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],Den=class e extends Va{schema;id;inlined;audiences;nameOverride;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1,nameOverride:o}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a,this.nameOverride=o,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertEnumSchema();if(r!=null)return r;let i=this.tryConvertSingularAllOfSchema();if(i!=null)return i;let n=this.tryConvertPrimitiveSchema();if(n!=null)return n;let a=this.tryConvertArraySchema();if(a!=null)return a;let o=this.tryConvertTypeArraySchema();if(o!=null)return o;let c=this.tryConvertOneOfAnyOfSchema();if(c!=null)return c;let d=this.tryConvertMapSchema();if(d!=null)return d;let s=this.tryConvertDiscriminatorMappingSchema();if(s!=null)return s;let u=this.tryConvertObjectAllOfSchema();if(u!=null)return u;let f=this.tryConvertUntypedSchema();if(f!=null)return f;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new BN.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),n=new xya({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.context.resolveMaybeReference({schemaOrReference:this.schema.allOf[0],breadcrumbs:this.breadcrumbs});if(r!=null){let n=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:r,id:this.id,inlined:!0}).convert();if(n?.convertedSchema.typeDeclaration?.shape.type!=="object")return n}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r={};for(let n of this.schema.allOf??[]){if(this.context.isReferenceObject(n))return;r=Jua(r,n,(a,o)=>{if(o===n)return a;if(Array.isArray(a)&&Array.isArray(o))return[...a,...o]})}return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,id:this.id,inlined:!0}).convert()}}tryConvertPrimitiveSchema(){let r=new Gya({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Yl.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new Kya({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Yl.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new Cwn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new tIu({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertDiscriminatorMappingSchema(){if(this.schema.discriminator?.mapping!=null&&Object.keys(this.schema.discriminator.mapping).length>0&&this.schema.oneOf==null&&this.schema.anyOf==null){let t={...this.schema,oneOf:Object.values(this.schema.discriminator.mapping).map(n=>({$ref:n}))},i=new Cwn({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:t,inlinedTypes:{}}).convert();if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:i.type,referencedTypes:i.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:i.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new Hya({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Yl.alias({aliasOf:hi.unknown(),resolvedType:hi.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new BN.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let i=jU_(r);if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:Yl.alias({aliasOf:i,resolvedType:i}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:i?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...Z3I,...t];return Object.keys(this.schema).every(n=>r.includes(n))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=this.context.resolveExample(n),o=`${this.id}_example_${i}`,c=this.generateOrValidateExample({example:a,exampleName:o});r[o]=c}return r}generateOrValidateExample({example:t}){let r=new NU({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:i}=r.convert();return i}};var rH=class extends Va{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:o=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=o}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{}}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null||this.schemaOrReference.allOf.length!==1)return;let t=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new Den({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=i.convert();if(a!=null){let o=a.convertedSchema.typeDeclaration.shape;return o.type==="alias"?{type:this.wrapTypeReference(o.aliasOf),schema:a.convertedSchema,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.convertedSchema,inlinedTypes:{...a.inlinedTypes,[r]:a.convertedSchema},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return hi.container(Js.optional(t))}wrapInNullable(t){return hi.container(Js.nullable(t))}};var Kya=class e extends Va{static LIST_UNKNOWN=hi.container(Js.list(hi.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new rH({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let i=new Set;for(let n of r.schema?.typeDeclaration.referencedTypes??[])i.add(n);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(n=>{n.typeDeclaration.referencedTypes.forEach(a=>{i.add(a)})}),{typeReference:hi.container(Js.list(r.type)),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}};var iIu=class extends Va{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:i,schemaId:n}){if(t.schema==null)return;if(r){let d=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",i]});if(d==null)return;t.schema=d}let o=new rH({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",i,"schema"],schemaOrReference:t.schema,schemaIdOverride:n}).convert();if(o==null)return;let c=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([d,s])=>{if(this.context.isReferenceObject(s)){let u=this.context.resolveReference({reference:s,breadcrumbs:[...this.breadcrumbs,"content",i,"examples"],skipErrorCollector:!0});return u.resolved?[d,u.value.value??u.value]:null}return[d,s.value??s]}).filter(d=>d!=null)):void 0;return{...o,examples:c}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let n=new rH({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(n!=null)return{...n,examples:void 0}}getIdForExample({key:t,example:r,usedExampleNames:i}){if(this.context.isExampleWithSummary(r)){let n=r.summary;if(!i.has(n))return n;let a=`${n} (${t})`;return i.has(a)?t:a}return t}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t?.schema,o=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),c=new Set;for(let[d,s]of o){let u=this.context.resolveExampleWithValue(s),f=this.context.resolveExampleRecursively({example:s,breadcrumbs:this.breadcrumbs}),p=this.getIdForExample({key:d,example:f,usedExampleNames:c});c.add(p),u!=null&&(a!=null?n.userSpecifiedExamples[p]=this.generateOrValidateExample({schema:a,example:u,exampleGenerationStrategy:i,exampleName:p}):n.userSpecifiedExamples[p]=u)}if(Object.keys(n.userSpecifiedExamples).length===0&&a!=null){let d=An(`${[...this.group,this.method].join("_")}_example`);n.autogeneratedExamples[d]=this.generateOrValidateExample({schema:a,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:i,exampleName:d})}return n}generateOrValidateExample({schema:t,example:r,generateOptionalProperties:i,exampleGenerationStrategy:n}){let a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(a==null)return;let o=this.context.getExamplesFromSchema({schema:a,breadcrumbs:this.breadcrumbs}),c=new NU({breadcrumbs:this.breadcrumbs,context:this.context,schema:a,example:r??o[0],generateOptionalProperties:i??!1,exampleGenerationStrategy:n}),{validExample:d}=c.convert();return d}};var nIu=class extends Va{parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),a=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),o=this.getParameterSchemaWithExampleOverride({schema:a});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??Va.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:this.convertParameterExamples({schema:o??t}),availability:n,explode:this.getExplodeForQueryParameter()},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??Va.OPTIONAL_STRING,env:void 0,v2Examples:this.convertParameterExamples({schema:o??t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??Va.STRING,location:"ENDPOINT",variable:void 0,v2Examples:this.convertParameterExamples({schema:o??t}),explode:this.getExplodeForPathParameter()},inlinedTypes:i};default:return}}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,o]of Object.entries(n??{})){let c=this.context.resolveExampleWithValue(o);c!=null&&(r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:c,exampleName:a}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=this.generateOrValidateExample({schema:t,example:i,exampleName:a})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0,exampleName:a})}return r}generateOrValidateExample({schema:t,example:r}){let i=new NU({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:n}=i.convert();return n}getExplodeForQueryParameter(){let t=this.parameter.style??"form",r=this.parameter.explode;if(r!==void 0)return t==="form"?r===!0?void 0:r:r===!1?void 0:r}getExplodeForPathParameter(){let t=this.parameter.explode;if(t!==void 0)return t===!1?void 0:t}};var aIu=class extends Nl{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}};var wU_="Base",k3I="x-fern-default-url",vAe=class e extends Va{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let i=this.getDefaultBaseUrlName(),n={id:i,name:this.context.casingsGenerator.generateName(i)},a=this.endpointLevelServers.map(d=>{let s=e.getServerName({server:d,context:this.context});return{id:s,name:this.context.casingsGenerator.generateName(s)}}).filter((d,s,u)=>u.findIndex(f=>f.id===d.id)===s),o=[n,...a],c=this.servers.map(d=>{let s=e.getServerName({server:d,context:this.context}),u=this.endpointLevelServers?.map(_=>[e.getServerName({server:_,context:this.context}),this.getServerUrl(_)]),{defaultUrls:f,urlTemplates:p,urlVariables:h}=this.buildMultiUrlTemplateFields({defaultBaseUrlId:i,topLevelServer:d,endpointServers:this.endpointLevelServers??[]});return{id:s,name:this.context.casingsGenerator.generateName(s),urls:{[i]:this.getServerUrl(d),...Object.fromEntries(u??[])},docs:d.description,defaultUrls:f,urlTemplates:p,urlVariables:h}});return{value:{defaultEnvironment:c[0]?.id,environments:JD.multipleBaseUrls({baseUrls:o,environments:c})},defaultUrl:n.id}}let t=this.extractFernDefaultUrl(),r=this.servers.map(i=>{let n=e.getServerName({server:i,context:this.context});return i.variables!=null&&Object.keys(i.variables).length>0&&i.variables!=null?{id:n,name:this.context.casingsGenerator.generateName(n),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(i)),defaultUrl:t,urlTemplate:this.maybeRemoveTrailingSlashIfNotEmpty(i.url),urlVariables:this.convertServerVariables(i.variables),docs:i.description}:{id:n,name:this.context.casingsGenerator.generateName(n),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(i)),defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0,docs:i.description}}).filter($s);return{value:{defaultEnvironment:r[0]?.id,environments:JD.singleBaseUrl({environments:r})},defaultUrl:r[0]?.id}}convertServerVariables(t){return Object.entries(t).map(([r,i])=>({id:r,name:this.context.casingsGenerator.generateName(r),default:i.default,values:i.enum}))}static getServerExtensionName({server:t,context:r}){return new aIu({breadcrumbs:[],server:t,context:r}).convert()}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,encodeURIComponent(n.default)));return r}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?wU_:e.getServerExtensionName({server:this.servers[0],context:this.context})??wU_}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}buildMultiUrlTemplateFields({defaultBaseUrlId:t,topLevelServer:r,endpointServers:i}){let n={},a={},o={},c=!1;if(r.variables!=null&&Object.keys(r.variables).length>0){c=!0;let d=this.extractFernDefaultUrlFromServer(r);d!=null&&(n[t]=d),a[t]=this.maybeRemoveTrailingSlashIfNotEmpty(r.url),o[t]=this.convertServerVariables(r.variables)}for(let d of i){let s=e.getServerName({server:d,context:this.context});if(d.variables!=null&&Object.keys(d.variables).length>0){c=!0;let u=this.extractFernDefaultUrlFromServer(d);u!=null&&(n[s]=u),a[s]=this.maybeRemoveTrailingSlashIfNotEmpty(d.url),o[s]=this.convertServerVariables(d.variables)}}return c?{defaultUrls:Object.keys(n).length>0?n:void 0,urlTemplates:a,urlVariables:o}:{defaultUrls:void 0,urlTemplates:void 0,urlVariables:void 0}}extractFernDefaultUrlFromServer(t){let r=t[k3I];if(typeof r=="string")return this.maybeRemoveTrailingSlashIfNotEmpty(r)}extractFernDefaultUrl(){if(this.servers!=null)for(let t of this.servers){let r=this.extractFernDefaultUrlFromServer(t);if(r!=null)return r}}};var qwn=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:i,exampleGenerationStrategy:n}){return new NU({breadcrumbs:i,context:this.context,schema:r,example:t,depth:0,exampleGenerationStrategy:n,generateOptionalProperties:!1}).convert()}validateEndpointExample({exampleToValidate:t}){let r=[],i=[],n=!0,a=!1,o,c=[t.endpointPath,t.method];if(t.requestExample!==void 0&&t.requestSchema!==void 0){let s=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...c,"request"],exampleGenerationStrategy:"request"});if(!s.isValid){n=!1;let u=t.exampleSource==="human"?PR.WARNING:PR.ERROR;r.push(...s.errors.map(f=>({...f,level:u,message:`Invalid request example: ${f.message}`})))}s.coerced&&(a=!0,i.push({level:PR.WARNING,message:"Request example was coerced to match schema",path:[...c,"request"]})),o={request:s.validExample}}let d=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&d!==void 0){let s=this.validateExample({example:t.responseExample,schema:d,breadcrumbs:[...c,"response"],exampleGenerationStrategy:"response"});if(!s.isValid){n=!1;let u=t.exampleSource==="human"?PR.WARNING:PR.ERROR;r.push(...s.errors.map(f=>({...f,level:u,message:`Invalid response example: ${f.message}`})))}s.coerced&&(a=!0,i.push({level:PR.WARNING,message:"Response example was coerced to match schema",path:[...c,"response"]})),o={...typeof o=="object"&&o!==null?o:{},response:s.validExample}}return{isValid:n,errors:r,warnings:i,endpointPath:t.endpointPath,method:t.method,exampleSource:t.exampleSource,exampleName:t.exampleName,validExample:o,coerced:a}}getResponseSchemaForValidation(t){let{responseStatusCode:r,responseSchemas:i,responseSchema:n}=t;return i&&Object.keys(i).length>0?r&&i[r]?i[r]:i[200]??i[201]:n}validateAiExamples({aiExamples:t,spec:r}){let i=[],n=[];for(let a of t){let{requestSchema:o,responseSchema:c,responseSchemas:d}=this.getSchemasForEndpoint({spec:r,endpointPath:a.endpointPath,method:a.method}),s={endpointPath:a.endpointPath,method:a.method,exampleSource:"ai",requestExample:a.request?.body,responseExample:a.response?.body,requestSchema:o,responseSchema:c,responseSchemas:d},u=this.validateEndpointExample({exampleToValidate:s}),f=this.hasUnexpectedProperties({requestExample:a.request?.body,responseExample:a.response?.body,requestSchema:o,responseSchema:c}),p=u.errors.length>0||u.warnings.length>0;!u.isValid||p||f?n.push({example:a,validationResult:u}):i.push(a)}return{validExamples:i,invalidExamples:n}}hasUnexpectedProperties({requestExample:t,responseExample:r,requestSchema:i,responseSchema:n}){return!!(t&&i&&this.exampleHasUnexpectedProperties(t,i)||r&&n&&this.exampleHasUnexpectedProperties(r,n))}exampleHasUnexpectedProperties(t,r){if(!t||typeof t!="object"||t===null)return!1;let i=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[],skipErrorCollector:!0});if(!i||!i.properties&&!i.allOf&&!i.oneOf&&!i.anyOf)return!1;let n=t,a=this.collectAllPropertyKeys(i);return Object.keys(n).some(c=>!a.has(c))}collectAllPropertyKeys(t,r=new Set){let i=new Set;if(t.properties)for(let n of Object.keys(t.properties))i.add(n);for(let n of t.allOf??[]){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[],skipErrorCollector:!0});if(a){let o=this.context.isReferenceObject(n)?n.$ref:JSON.stringify(a);if(!r.has(o)){r.add(o);let c=this.collectAllPropertyKeys(a,r);for(let d of c)i.add(d)}}}for(let n of[...t.oneOf??[],...t.anyOf??[]]){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[],skipErrorCollector:!0});if(a){let o=this.context.isReferenceObject(n)?n.$ref:JSON.stringify(a);if(!r.has(o)){r.add(o);let c=this.collectAllPropertyKeys(a,r);for(let d of c)i.add(d)}}}return i}validateHumanExamples({spec:t}){let r=[],i=0,n=0,a=0,o=[],c=[];if(!t.paths)return{endpoints:r,totalExamples:i,validExamples:n,invalidExamples:a,hasInvalidHumanExamples:!1,hasInvalidAiExamples:!1,invalidHumanExamples:o,invalidAiExamples:c};for(let[d,s]of Object.entries(t.paths)){if(!s)continue;let u=["get","post","put","delete","patch","options","head","trace"];for(let f of u){let p=s[f];if(!p)continue;let h=[],{requestSchema:_,responseSchema:y,responseSchemas:b}=this.getSchemasForOperation({operation:p}),v=this.extractExamplesFromOperation({operation:p,path:d,method:f});for(let O of v){i++;let m={endpointPath:d,method:f,exampleName:O.name,exampleSource:O.source,requestExample:O.request,responseExample:O.response,requestSchema:_,responseSchema:y,responseStatusCode:O.statusCode,responseSchemas:b},g=this.validateEndpointExample({exampleToValidate:m});h.push(g),g.isValid?n++:(a++,O.source==="human"?o.push(g):O.source==="ai"&&c.push(g))}h.length>0&&r.push({endpointPath:d,method:f,results:h,hasInvalidExamples:h.some(O=>!O.isValid),invalidExampleCount:h.filter(O=>!O.isValid).length})}}return{endpoints:r,totalExamples:i,validExamples:n,invalidExamples:a,hasInvalidHumanExamples:o.length>0,hasInvalidAiExamples:c.length>0,invalidHumanExamples:o,invalidAiExamples:c}}getSchemasForEndpoint({spec:t,endpointPath:r,method:i}){let n=t.paths?.[r];if(!n)return{responseSchemas:{}};let a=n[i.toLowerCase()];return!a||typeof a!="object"||!("responses"in a)?{responseSchemas:{}}:this.getSchemasForOperation({operation:a})}getSchemasForOperation({operation:t}){let r,i,n={};if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let o=t.requestBody.content?.["application/json"];o?.schema&&(r=o.schema)}if(t.responses){for(let[a,o]of Object.entries(t.responses)){if(!o||this.context.isReferenceObject(o))continue;let d=o.content?.["application/json"];d?.schema&&(n[a]=d.schema)}i=n[200]??n[201]}return{requestSchema:r,responseSchema:i,responseSchemas:n}}extractExamplesFromOperation({operation:t,path:r,method:i}){let n=[];if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let c=t.requestBody.content?.["application/json"];if(c?.example!==void 0&&n.push({name:`${i}_${r}_request_example`,source:"openapi",request:c.example}),c?.examples)for(let[d,s]of Object.entries(c.examples)){let u=this.context.isReferenceObject(s)?this.context.resolveExample(s):s;u&&typeof u=="object"&&"value"in u&&n.push({name:d,source:"human",request:u.value})}}if(t.responses)for(let[o,c]of Object.entries(t.responses)){if(!c||this.context.isReferenceObject(c))continue;let s=c.content?.["application/json"];if(s?.example!==void 0){let u=n.find(f=>f.request!==void 0&&f.response===void 0);u?(u.response=s.example,u.statusCode=o):n.push({name:`${i}_${r}_response_${o}_example`,source:"openapi",response:s.example,statusCode:o})}if(s?.examples)for(let[u,f]of Object.entries(s.examples)){let p=this.context.isReferenceObject(f)?this.context.resolveExample(f):f;if(p&&typeof p=="object"&&"value"in p){let h=n.find(_=>_.name===u);h?(h.response=p.value,h.statusCode=o):n.push({name:u,source:"human",response:p.value,statusCode:o})}}}let a=t["x-fern-examples"];if(Array.isArray(a)){for(let o of a)if(typeof o=="object"&&o!==null){let c=o;n.push({name:c.name,source:"human",request:c.request?.body,response:c.response?.body})}}return n}};var oIu={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},eWI=new Set(Object.values(oIu));var tWI=Bt.object({type:Bt.string(),channelId:Bt.string().optional(),messageId:Bt.string(),value:Bt.any()}),rWI=Bt.object({summary:Bt.string().optional(),description:Bt.string().optional(),"query-parameters":Bt.record(Bt.string()).optional(),headers:Bt.record(Bt.string()).optional(),messages:Bt.array(tWI)}),EU_=Bt.array(rWI);var uIu=class extends Nl{channel;baseDir;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:i,baseDir:n}){super({breadcrumbs:t??[],context:i}),this.channel=r,this.baseDir=n}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=EU_.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(i=>({summary:i.summary,description:i.description,queryParameters:i["query-parameters"],headers:i.headers,messages:i.messages.map(n=>({type:n.type,channelId:n.channelId,messageId:n.messageId,value:n.value}))}))}};var $ya=class extends Va{channel;channelPath;inlinedTypes={};websocketGroup;constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r}),this.websocketGroup=i,this.channel=n,this.channelPath=a}convertExamples({fullPath:t,baseUrl:r,asyncApiVersion:i}){let a=new uIu({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel,baseDir:this.context.documentBaseDir}).convert();return a==null?{}:Object.fromEntries(a.map((o,c)=>[c.toString(),{channel:{method:"GET",path:t},baseUrl:t,environment:r,auth:void 0,pathParameters:{},queryParameters:o.queryParameters,headers:o.headers,messages:o.messages.map(d=>({type:i==="v2"?d.type:d.messageId,body:d.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var Ien=class extends $A.AbstractConverters.AbstractParameterConverter{parameterNamePrefix;constructor({context:t,breadcrumbs:r,parameter:i,parameterNamePrefix:n}){super({context:t,breadcrumbs:r,parameter:i}),this.parameterNamePrefix=n}convert(){let t,r={},n=new BN.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required===!1,a=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example??this.parameter.name,examples:Object.values(this.parameter.examples??{}),deprecated:this.parameter.deprecated,required:void 0},c=new $A.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameterNamePrefix?`${this.parameterNamePrefix}_${this.parameter.name}`:this.parameter.name,schemaOrReference:a,wrapAsOptional:n}).convert();return c!=null&&(t=c.type,r=c.inlinedTypes??{}),this.convertToOutput({schema:a,typeReference:t,inlinedTypes:r})}};var sIu=class extends Nl{channel;key="x-fern-address";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var Jya=class extends Nl{channel;key="x-fern-display-name";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t,context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}};var cIu=class extends $ya{inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a})}convert(){let t=[],r=[],i=[],a=new Jya({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".");this.channel.parameters&&this.convertPathParameters({context:this.context,pathParameters:t}),this.channel.bindings?.ws!=null&&(this.convertHeaders({context:this.context,headers:i}),this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let o;this.channel.subscribe!=null&&(o=this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let c;this.channel.publish!=null&&(c=this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let d=[];o!=null&&d.push(o),c!=null&&d.push(c);let u=new sIu({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),f=this.transformToValidPath(u??this.channelPath),p=this.channel.servers?.[0]??Object.keys(this.context.spec.servers??{})[0],h=eI(f),_=An(this.channelPath),y=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(_),displayName:a,baseUrl:p,path:h,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:d,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:f,baseUrl:p,asyncApiVersion:"v2"})}},audiences:y,inlinedTypes:this.inlinedTypes}}convertMessage({context:t,operation:r,origin:i}){let n,a=i==="server"?"subscribe":"publish",o=[...this.breadcrumbs,a],c=t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:o});c!=null&&(r.message=c);let d=Pmn(An(`${this.channelPath}_${a}`)).replace(/ /g,"");if("oneOf"in r.message){let u=new $A.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:o,schemaOrReference:r.message,schemaIdOverride:d}).convert();u!=null&&u.schema!=null&&(n=u.schema,this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let s=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:o});if(s!=null){let f=new $A.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:o,schemaOrReference:s,schemaIdOverride:d}).convert();f!=null&&f.schema!=null&&(n=f.schema,this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes})}}if(n!=null){let s=n,u=hi.named({fernFilepath:t.createFernFilepath(),name:s.typeDeclaration.name.name,typeId:s.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),f=R3.reference({bodyType:u,docs:r.description}),p=i==="server"?"subscribe":"publish";return{type:p,displayName:p,origin:i,body:f,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description,methodName:void 0}}}convertPathParameters({context:t,pathParameters:r}){for(let[i,n]of Object.entries(this.channel.parameters??{})){let a=t.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(a==null)continue;let c=new Ien({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:i,in:"path",description:a.description,required:a.required??!0}}).convert();c!=null&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},c.type==="path"&&r.push(c.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let i=this.channel.bindings.ws.headers.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let o=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(o==null)continue;let d=new Ien({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"header",required:i.includes(n),schema:o,description:"description"in o?o.description:void 0}}).convert();d!=null&&d.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let i=this.channel.bindings.ws.query.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.query.properties??{})){let o=t.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,n]});if(o==null)continue;let d=new Ien({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"query",required:i.includes(n),schema:o,description:"description"in o?o.description:void 0,deprecated:o.deprecated??!1}}).convert();d!=null&&d.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}};var Yya=class extends Va{servers;constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r}),this.servers=i}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[i,n]of Object.entries(this.servers)){let a=this.buildSingleBaseUrlEnvironment(this.context,i,n);t.push(a),r==null&&(r=a.id)}return{defaultEnvironment:r,environments:JD.singleBaseUrl({environments:t})}}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var lIu=class extends Yya{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.url),docs:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}};var Osl="$message.",SU_="#/channels/",MU_="#/servers/",fIu=class extends $ya{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a,operations:o}){super({context:t,breadcrumbs:r,websocketGroup:i,channel:n,channelPath:a}),this.operations=o}convert(){let t=[],r=[],i=[],a=new Jya({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".")??this.channelPath;this.channel.parameters&&this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:this.channelPath});let o=Object.entries(this.operations).reduce((p,[h,_])=>{try{this.getChannelPathFromOperation(_)===this.channelPath&&(p[h]=_)}catch{}return p},{}),c=[];for(let[p,h]of Object.entries(o))for(let _ of h.messages){let y=this.context.convertReferenceToTypeReference({reference:_});if(y.ok){let b=R3.reference({bodyType:y.reference,docs:h.description});c.push({type:p,displayName:p,origin:h.action==="send"?"client":"server",body:b,availability:this.context.getAvailability({node:h,breadcrumbs:this.breadcrumbs}),docs:h.description,methodName:void 0})}}let d=this.resolveChannelServersFromReference(this.channel.servers??[])??Object.keys(this.context.spec.servers??{})[0],s=this.transformToValidPath(this.channel.address??this.channelPath),u=eI(s),f=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[];return{channel:{name:this.context.casingsGenerator.generateName(a),displayName:a,baseUrl:d,path:u,auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:c,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:s,baseUrl:d,asyncApiVersion:"v3"})}},audiences:f,inlinedTypes:this.inlinedTypes}}convertChannelParameters({pathParameters:t,queryParameters:r,headers:i,channelPath:n}){for(let a of Object.values(this.channel.parameters??{})){let o=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(o==null)continue;let c=this.convertChannelParameterLocation(o.location);if(c==null)continue;let{type:d,parameterKey:s}=c,f=new Ien({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:s,in:d},parameterNamePrefix:this.channelPath}).convert();if(f!=null)switch(this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes},f.type){case"path":t.push(f.parameter);break;case"query":r.push(f.parameter);break;case"header":i.push(f.parameter);break}}}convertChannelParameterLocation(t){try{let[r,i]=t.split("#/");if(r==null||i==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(Osl)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${Osl} prefix`,path:this.breadcrumbs});return}let n=r.substring(Osl.length);if(n!=="header"&&n!=="path"&&n!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${n}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return n==="payload"?{type:"query",parameterKey:i}:{type:n,parameterKey:i}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(MU_)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let i=r.$ref.substring(MU_.length);if(i==null){this.context.errorCollector.collect({message:`Failed to find server with name ${i}`,path:this.breadcrumbs});return}return i}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(SU_))throw new Error(`Failed to resolve channel path from operation ${t.channel.$ref}`);return t.channel.$ref.substring(SU_.length)}};var dIu=class extends Yya{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.host),docs:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}};var Aao=class extends jHt{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){return this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.isAsyncAPIV3(this.context)?this.convertChannelMessages():this.convertComponentMessages(),this.convertSchemas(),this.convertServers(),this.convertChannels(),this.finalizeIr()}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}convertChannelMessages(){let t=this.context.spec;for(let[r,i]of Object.entries(t.channels??{}))for(let[n,a]of Object.entries(i.messages??{})){if(!this.context.isMessageWithPayload(a)&&!this.context.isReferenceObject(a))continue;let o=["channels",r,"messages",n],c=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:o});if(!this.context.isMessageWithPayload(c))continue;let d=this.context.resolveMaybeReference({schemaOrReference:c.payload,breadcrumbs:o});if(d==null)continue;let s=`${r}_${n}`;this.convertSchema({id:s,breadcrumbs:o,schema:d})}}convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let i=["components","messages",t],n=this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:i});n!=null&&this.convertSchema({id:t,breadcrumbs:i,schema:n})}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}convertSchema({id:t,breadcrumbs:r,schema:i}){let a=new $A.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:i}).convert();a!=null&&this.addSchemaOutputToIr(t,a)}convertServers(){let t;if(this.isAsyncAPIV3(this.context)){let r=this.context.spec.servers;t=new dIu({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new lIu({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let n=new BN.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,a;if(this.isAsyncAPIV3(this.context)){let c=this.context.spec.operations??{};a=new fIu({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t,operations:c}).convert()}else a=new cIu({context:this.context,breadcrumbs:["channels",t],websocketGroup:n,channel:r,channelPath:t}).convert();a!=null&&(this.addWebsocketChannelToIr({websocketChannel:a.channel,channelPath:t,audiences:a.audiences,websocketGroup:n}),this.addTypesToIr(a.inlinedTypes))}}};var Pao=class extends kq{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a,o=t.$ref.match(/^.*\/schemas\/(.+)$/),c=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),d=t.$ref.match(/^.*\/messages\/(.+)$/);if(o&&o[1])return a=o[1],this.convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a});if(c&&c[2]){let s=c[1],u=c[2];return a=`${s}_${u}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})}else return d&&d[1]?(a=d[1],this.convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a})):{ok:!1}}convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.title??i),{ok:!0,reference:hi.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.name??i),{ok:!0,reference:hi.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n,typeId:a}){let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.messageId??o.value.name:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.messageId??o.value.name??i),{ok:!0,reference:hi.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}};var RU_=ce(pIu(),1);var hIu=class extends Nl{document;key="x-fern-base-path";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-base-path",path:this.breadcrumbs});return}return t}}};var _Iu=class extends Nl{document;key="x-fern-global-headers";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-headers",path:this.breadcrumbs});return}return t}}};function DU_({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?Va.OPTIONAL_STRING:Va.STRING,env:r.env,v2Examples:r.optional?void 0:aWI({header:r,context:t}),availability:void 0,docs:void 0}))}function aWI({header:e,context:t}){let r=new NU({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:i}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:i}}}var yIu=class extends $A.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let i=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),a=new $A.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:i}).convert();a!=null&&(t=a.type,r=a.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var bIu=class extends $A.AbstractConverters.AbstractMediaTypeObjectConverter{contentType;mediaType;description;required;schemaId;streamingExtension;queryParameters;constructor({context:t,breadcrumbs:r,contentType:i,mediaType:n,description:a,required:o,group:c,method:d,streamingExtension:s,queryParameters:u}){super({context:t,breadcrumbs:r,group:c,method:d}),this.contentType=i,this.mediaType=n,this.description=a,this.required=o,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=s,this.queryParameters=u??[]}convert(){return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleStreamConditionJsonOrFormContent({contentType:this.contentType})}convertNonStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleJsonOrFormContent({contentType:this.contentType});if(iA.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=iA.parse(this.contentType);return t?t.isJSON()||t.isURLEncoded()||t.isPlainText()||t.isCSV()||t.isHTML()||t.isXML()||t.isDNS()||t.isApplicationText():!1}isBinaryContentType(){let t=iA.parse(this.contentType);return t?t.isBinary():!1}handleJsonOrFormContent({contentType:t}){let r=this.mediaType;if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;return n?.type==="object"?this.hasBodyQueryParameterOverlap(n.properties)?{requestBody:FA.reference({contentType:t,docs:this.description,requestBodyType:i.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i.inlinedTypes??{}}:{requestBody:FA.inlinedRequestBody({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:n.extendedProperties,extends:n.extends,properties:n.properties,extraProperties:n.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes})}:{requestBody:FA.reference({contentType:t,docs:this.description,requestBodyType:i.type,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i.inlinedTypes??{}}}handleMultipartContent({contentType:t}){let r=this.mediaType;if(r==null||r.schema==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,resolveSchema:!0,contentType:t});if(i==null)return;let n=i.schema?.typeDeclaration.shape;if(n?.type==="object")return{requestBody:FA.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:n.properties.map(a=>{let o=r.encoding?.[a.name.wireValue];return this.convertRequestBodyProperty({property:a,contentType:t,encoding:o})}),v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:i.inlinedTypes}),examples:i.examples}}handleBinaryContent({contentType:t}){let r=this.mediaType;if(r==null)return;let i=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});return{requestBody:FA.bytes({contentType:t,isOptional:this.required===!1,docs:this.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:i?.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r,encoding:i}){let{isFile:n,isOptional:a,isArray:o}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return n?o?dR.file(QZ.fileArray({key:t.name,isOptional:a,contentType:r,docs:t.docs})):dR.file(QZ.file({key:t.name,isOptional:a,contentType:r,docs:t.docs})):dR.bodyProperty({...t,contentType:i?.contentType??r,style:uWI({encoding:i}),name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.mediaType;if(r==null||r.schema==null)return;let i=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(i==null)return;let n=i.properties?.[this.streamingExtension.streamConditionProperty];if(n==null||this.context.isReferenceObject(n))return;let a=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!0,contentType:t,mediaTypeObject:r}),o=this.buildStreamConditionInlinedRequestBody({streamConditionProperty:n,resolvedMediaTypeSchema:i,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(a==null||o==null))return{requestBody:o.requestBody,streamRequestBody:a.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...a.inlinedTypes,...o.inlinedTypes}})}}buildStreamConditionInlinedRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:i,contentType:n,mediaTypeObject:a}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let o={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{type:"boolean",const:i,...t}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},c={...a,schema:o},d=this.parseMediaTypeObject({mediaTypeObject:c,schemaId:this.schemaId,contentType:n});if(d==null)return;let s=d.schema?.typeDeclaration.shape;if(s?.type==="object")return{requestBody:FA.inlinedRequestBody({contentType:n,docs:void 0,name:this.context.casingsGenerator.generateName(i?`${this.schemaId}_streaming`:this.schemaId),extendedProperties:s.extendedProperties,extends:s.extends,properties:s.properties,extraProperties:s.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:c,exampleGenerationStrategy:"request"})}),inlinedTypes:d.inlinedTypes}}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:i}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:i}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:i}):{isFile:this.context.isFile(t),isOptional:r??!1,isArray:i??!1}}hasBodyQueryParameterOverlap(t){if(this.queryParameters.length===0)return!1;let r=new Set(this.queryParameters.map(i=>i.name.wireValue.toLowerCase()));return t.some(i=>r.has(i.name.wireValue.toLowerCase()))}},oWI={"application/json":"json"};function uWI({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return oWI[e.contentType]}}var sWI=/{([^}]+)}/g,cWI=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),Xya=class extends Va{operation;method;path;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r}),this.operation=i,this.method=n,this.path=a}convertHttpMethod(){switch(this.method){case"get":return EE.Get;case"post":return EE.Post;case"put":return EE.Put;case"delete":return EE.Delete;case"patch":return EE.Patch;case"head":return EE.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],i=[],n=[];if(!this.operation.parameters)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n};for(let a of this.operation.parameters){let o=this.context.resolveMaybeReference({schemaOrReference:a,breadcrumbs:t});if(o==null)continue;let d=new yIu({context:this.context,breadcrumbs:t,parameter:o}).convert();if(d!=null)switch(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},d.type){case"path":r.push(d.parameter);break;case"query":i.push(d.parameter);break;case"header":{let s=d.parameter.name.name.originalName,u=d.parameter.name.wireValue,f=!1,p=this.context.authOverrides?.["auth-schemes"];if(p!=null){for(let _ of Object.values(p))if(pWI(_)&&_.header.toLowerCase()===u.toLowerCase()){f=!0;break}}let h=this.context.globalHeaderNames;if(h!=null){for(let _ of h)if(_.toLowerCase()===u.toLowerCase()){f=!0;break}}!cWI.has(s.toLowerCase())&&!f&&n.push(d.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:i,headers:n}}checkMissingPathParameters(t){let i=[...this.path.matchAll(sWI)].map(n=>n[1]).filter(n=>!t.some(a=>a.name.originalName===n));for(let n of i){if(n==null)continue;let a=`${n}_example`;t.push({name:this.context.casingsGenerator.generateName(n),valueType:Va.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[a]:this.generateStringParameterExample({example:n})}},explode:void 0})}}convertRequestBody({breadcrumbs:t,group:r,method:i,streamingExtension:n,queryParameters:a}){if(this.operation.requestBody==null)return;let o=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(o==null)return null;let c=[];for(let[d,s]of Object.entries(o.content)){let f=new bIu({context:this.context,breadcrumbs:t,contentType:d,mediaType:s,description:o.description,required:o.required,group:r??[],method:i,streamingExtension:n,queryParameters:a}).convert();f!=null&&(this.inlinedTypes={...this.inlinedTypes,...f.inlinedTypes},c.push({requestBody:f.requestBody,streamRequestBody:f.streamRequestBody,examples:f.examples}))}return c}computeGroupNameAndLocationFromExtensions(){let r=new BN.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,n=new BN.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:n,method:r}}evaluateMethodNameFromOperation(){let t=this.operation.operationId;return t??(this.operation.summary!=null?An(this.operation.summary):An(`${this.method}_${this.path.split("/").join("_")}`))}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:r};let i=IU_(t),n=IU_(r);return EC(i,n)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,methodName:r,methodNameTokens:n})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:i,methodNameTokens:n}){if(r.some((c,d)=>c!==n[d]))return{group:[t],method:i};let o=n.slice(r.length);return{group:[t],method:An(o.join("_"))}}generateStringParameterExample({example:t}){let r=new $A.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:i}=r.convert();return i}};function IU_(e){let t=lWI(e)?fWI(e):dWI(e);return t=t.map(r=>r.toLowerCase()),t=$Me(t),t}function lWI(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function fWI(e){return e.split(/(?=[A-Z])/)}function dWI(e){return e.split(/[^a-zA-Z0-9]+/)}function pWI(e){return e?.header!=null}var Zya=class extends Xya{constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=[...this.breadcrumbs,"Payload"],{headers:a,queryParameters:o}=this.convertParameters({breadcrumbs:n}),c=this.convertRequestBody({breadcrumbs:n,group:r,method:i,streamingExtension:void 0,queryParameters:o});if(c==null)return;let d=c[0]?.requestBody;if(d==null)return;let s,u;if(d.type==="inlinedRequestBody")s=lU.inlinedPayload({name:d.name,extends:d.extends,properties:d.properties});else if(d.type==="reference")s=lU.reference({payloadType:d.requestBodyType,docs:d.docs});else if(d.type==="fileUpload")u={name:d.name,properties:d.properties,docs:d.docs,v2Examples:d.v2Examples,contentType:d.contentType},s=lU.inlinedPayload({name:d.name,extends:[],properties:[]});else return;let f=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,webhook:{id:`${r?.join(".")??""}.${i}`,name:this.context.casingsGenerator.generateName(i),displayName:this.operation.summary,method:t,headers:a,payload:s,fileUploadPayload:u,responses:f.length>0?f:void 0,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(d.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(d.v2Examples?.userSpecifiedExamples??{})}},inlinedTypes:this.inlinedTypes}}convertWebhookResponses(){let t=[];if(this.operation.responses==null)return t;for(let[r,i]of Object.entries(this.operation.responses)){let n=/^\d[Xx]{2}$/.test(r),a;if(n)a=parseInt(r.charAt(0))*100;else if(a=parseInt(r),isNaN(a))continue;let c=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[...this.breadcrumbs,"responses",r]})?.description;t.push({statusCode:a,isWildcardStatusCode:n?!0:void 0,body:void 0,docs:c})}return t}getWebhookV2ExamplesFromRequestBodyV2Examples(t){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,{name:r,payload:i}]))}};var Psl=ce(pIu(),1);var BU_=["get","post","put","delete","patch","head"];var vIu=class extends Nl{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}};var hWI=Bt.object({cursor:Bt.string(),next_cursor:Bt.string(),results:Bt.string()}),_WI=Bt.object({offset:Bt.string(),results:Bt.string(),step:Bt.string().optional(),"has-next-page":Bt.string().optional()}),msl=Bt.union([Bt.boolean(),hWI,_WI]);var Asl="$request.",gIu="$response.",OIu=class extends Nl{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:i,context:n}){super({breadcrumbs:t,context:n}),this.operation=r,this.document=i}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=msl.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let i=this.getExtensionValue(this.document);if(i==null)return;if(typeof i=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let n=msl.safeParse(i);if(!n.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${n.error.message}`,path:this.breadcrumbs});return}if(typeof n.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:n.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:kq.maybeTrimPrefix(r.cursor,Asl),nextCursor:kq.maybeTrimPrefix(r.next_cursor,gIu),results:kq.maybeTrimPrefix(r.results,gIu)};let i=t;return{type:"offset",offset:kq.maybeTrimPrefix(i.offset,Asl),results:kq.maybeTrimPrefix(i.results,gIu),step:i.step!=null?kq.maybeTrimPrefix(i.step,Asl):void 0,hasNextPage:i["has-next-page"]!=null?kq.maybeTrimPrefix(i["has-next-page"],gIu):void 0}}};var yWI="$request.",bWI=Bt.object({"stream-condition":Bt.string().optional(),format:Bt.enum(["sse","json"]).optional(),"stream-description":Bt.string().optional(),"response-stream":Bt.any(),response:Bt.any()}),vWI=Bt.union([Bt.boolean(),bWI]),mIu=class extends Nl{operation;key="x-fern-streaming";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=vWI.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json"}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",streamDescription:r.data["stream-description"],streamConditionProperty:kq.maybeTrimPrefix(r.data["stream-condition"],yWI),responseStream:r.data["response-stream"],response:r.data.response}}};var AIu=class extends Nl{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}};var jIu=require("fs"),CU_=require("path");function gWI(e){return Wl(e)&&typeof e.$ref=="string"}function OWI(e,t){if(e!=null){if(typeof e=="string")return e;if(gWI(e)){let r=(0,CU_.resolve)(t??process.cwd(),e.$ref);if((0,jIu.existsSync)(r))try{return(0,jIu.readFileSync)(r,"utf-8")}catch{return}}}}var PIu=class extends Nl{operation;baseDir;key="x-codeSamples";constructor({context:t,breadcrumbs:r,operation:i,baseDir:n}){super({breadcrumbs:r,context:t}),this.operation=i,this.baseDir=n}convert(){let t=Wl(this.operation)?this.operation:{},r=t["x-codeSamples"],i=t["x-code-samples"],n=Array.isArray(r)?r:[],a=Array.isArray(i)?i:[],o=[...n,...a];if(o.length===0)return;let c=[];for(let d of o){if(!Wl(d))continue;let s=d,u=s.lang,f=s.label,p=s.source;if(typeof u!="string")continue;let h=OWI(p,this.baseDir);h!=null&&c.push({name:typeof f=="string"?f:u,language:u,code:h,install:void 0,docs:void 0})}if(c.length!==0)return[{"code-samples":c}]}};var EIu=require("fs"),qU_=require("path");function mWI(e){return Wl(e)&&typeof e.$ref=="string"}function AWI(e,t){if(e!=null){if(typeof e=="string")return e;if(mWI(e)){let r=(0,qU_.resolve)(t??process.cwd(),e.$ref);if((0,EIu.existsSync)(r))try{return(0,EIu.readFileSync)(r,"utf-8")}catch{return}}}}function PWI(e,t){if(!Array.isArray(e))return[];let r=[];for(let i of e){if(!Wl(i))continue;let a=AWI(i.code,t);a!=null&&r.push({...i,code:a})}return r}var wIu=class extends Nl{operation;baseDir;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:i,baseDir:n}){super({breadcrumbs:r,context:t}),this.operation=i,this.baseDir=n}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).map(a=>{if(!Wl(a))return a;let c=a["code-samples"];if(c!=null){let d=PWI(c,this.baseDir);return{...a,"code-samples":d}}return a}).filter(a=>{let o=TC.serialization.ExampleEndpointCallSchema.parse(a);return o.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),o.ok})}};var jao=class extends Nl{document;key="x-fern-explorer";constructor({breadcrumbs:t,document:r,context:i}){super({breadcrumbs:t,context:i}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}};var wao=class extends $A.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:i,group:n,method:a,statusCode:o,streamingExtension:c}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseBody=i,this.statusCode=o,this.streamingExtension=c}convert(){return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,i=[...this.group,this.method,"Response",this.statusCode].join("_"),n=`${i}_streaming`,a=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:n}),o=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:i});return this.convertStreamConditionResponse({convertedStreamingSchema:a,convertedNonStreamingSchema:o})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{});for(let i of r){let n=this.responseBody.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:t,contentType:this.streamingExtension.format});if(a!=null)return this.convertStreamingResponse({mediaTypeObject:n,convertedSchema:a})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(a=>a.includes("json"));for(let a of r){let o=this.responseBody.content?.[a];if(o==null)continue;let c=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:a});if(c!=null&&this.shouldReturnJsonResponse(a))return this.returnJsonResponse({mediaTypeObject:o,convertedSchema:c})}let i=Object.keys(this.responseBody.content??{}).filter(a=>!a.includes("json"));for(let a of i){let o=this.responseBody.content?.[a];if(o==null)continue;let c=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:a});if(c!=null){if(this.isBinarySchema(c))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:o}):this.returnFileDownloadResponse({mediaTypeObject:o});if(this.shouldReturnTextResponse(a))return this.returnTextResponse({mediaTypeObject:o})}}let n=parseInt(this.statusCode);if(!isNaN(n)&&n>=200&&n<300){let a={schema:{type:"object",description:"Empty response body"}},o=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:t,contentType:"application/json",resolveSchema:!0});if(o!=null)return this.returnJsonResponse({mediaTypeObject:a,convertedSchema:o})}}convertStreamConditionResponse({convertedStreamingSchema:t,convertedNonStreamingSchema:r}){if(t==null||r==null)return;let i=this.responseBody.description;return this.streamingExtension?.type==="streamCondition"&&this.streamingExtension.streamDescription!=null&&(i=this.streamingExtension.streamDescription),{responseBody:np.json(Lq.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:np.streaming(RC.json({docs:i,payload:t.type,terminator:void 0,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes},headers:this.convertResponseHeaders()}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:np.streaming(RC.json({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()};case"sse":return{responseBody:np.streaming(RC.sse({docs:this.responseBody.description,payload:r.type,terminator:void 0,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:np.json(Lq.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:r.inlinedTypes,examples:r.examples,headers:this.convertResponseHeaders()}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:np.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:np.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}returnTextResponse({mediaTypeObject:t}){return{responseBody:np.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:{},headers:this.convertResponseHeaders()}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return iA.parse(t)?.isText()??!1}convertResponseHeaders(){let t=[],r=this.responseBody.headers;if(r==null)return t;for(let[i,n]of Object.entries(r)){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"headers",i]});if(a==null)continue;let o=a.schema,c=Va.OPTIONAL_STRING;if(o!=null){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,"headers",i,"schema"]});s!=null&&(s.type==="number"||s.type==="integer"?c=hi.primitive({v1:s.type==="integer"?"INTEGER":"DOUBLE",v2:s.type==="integer"?Cn.integer({default:void 0,validation:void 0}):Cn.double({default:void 0,validation:void 0})}):s.type==="boolean"&&(c=hi.primitive({v1:"BOOLEAN",v2:Cn.boolean({default:void 0})})))}let d=this.convertHeaderExamples({header:a,headerName:i,schema:o});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:i,wireValue:i}),docs:a.description,valueType:c,env:void 0,v2Examples:d,availability:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t.example,o=t.examples;for(let[c,d]of Object.entries(o??{})){let s=this.context.resolveExampleWithValue(d);s!=null&&(n.userSpecifiedExamples[c]=this.generateHeaderExample({schema:i,example:s}))}if(a!=null){let c=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[c]=this.generateHeaderExample({schema:i,example:a})}if(Object.keys(n.userSpecifiedExamples).length===0&&i!=null){let c=`${r}_example`;n.autogeneratedExamples[c]=this.generateHeaderExample({schema:i,example:void 0,ignoreErrors:!0})}return n}generateHeaderExample({schema:t,example:r,ignoreErrors:i}){if(t==null)return r;let n=new NU({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:a,errors:o}=n.convert();return i||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}};var SIu=class extends $A.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;constructor({context:t,breadcrumbs:r,responseError:i,group:n,method:a,methodName:o,statusCode:c,isWildcardStatusCode:d}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseError=i,this.statusCode=c,this.methodName=o,this.isWildcardStatusCode=d}convert(){if(!this.responseError.content){let i=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(i==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let n=this.getErrorIdFromErrorName(i);return{error:{error:{name:this.context.casingsGenerator.generateName(n),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:n},docs:this.responseError.description},errorType:hi.unknown(),displayName:i,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:{},examples:{},headers:this.convertResponseHeaders()}}let t=Object.keys(this.responseError.content).filter(i=>i.includes("json")),r=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let i of[...t]){let n=this.responseError.content?.[i];if(n==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:n,schemaId:TU_(`${this.methodName}Request${r}`),contentType:i});if(a==null)continue;let o=this.getErrorIdFromErrorName(r);if(a.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:o,fernFilepath:a.schema.typeDeclaration.name.fernFilepath,convertedSchema:a,mediaTypeObject:n});if(a.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:o,fernFilepath:a.type.fernFilepath,convertedSchema:a,mediaTypeObject:n})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:i,convertedSchema:n,mediaTypeObject:a}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:i,errorId:r},docs:this.responseError.description},errorType:n.type,displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:n.inlinedTypes,examples:this.convertErrorExamples({mediaTypeObject:a}),headers:this.convertResponseHeaders()}}convertErrorExamples({mediaTypeObject:t}){let r=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_error_example`});if(r.length===0)return;let i=new Set,n={};for(let[a,o]of r){let c=this.context.resolveExampleWithValue(o),d=this.context.resolveExampleRecursively({example:o,breadcrumbs:this.breadcrumbs}),s=this.getIdForErrorExample({key:a,example:d,usedExampleNames:i});i.add(s),c!=null&&(n[s]=c)}return Object.keys(n).length>0?n:void 0}getIdForErrorExample({key:t,example:r,usedExampleNames:i}){if(this.context.isExampleWithSummary(r)){let n=r.summary;if(!i.has(n))return n;let a=`${n} (${t})`;return i.has(a)?t:a}return t}getErrorNameForStatusCode(t,r){if(r){if(t===400)return"ClientRequestError";if(t===500)return"ServerError"}return oIu[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?TU_(`${this.methodName}Request${t}`):t}convertResponseHeaders(){let t=[],r=this.responseError.headers;if(r==null)return t;for(let[i,n]of Object.entries(r)){let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"headers",i]});if(a==null)continue;let o=a.schema,c=Va.OPTIONAL_STRING;if(o!=null){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,"headers",i,"schema"]});s!=null&&(s.type==="number"||s.type==="integer"?c=hi.primitive({v1:s.type==="integer"?"INTEGER":"DOUBLE",v2:s.type==="integer"?Cn.integer({default:void 0,validation:void 0}):Cn.double({default:void 0,validation:void 0})}):s.type==="boolean"&&(c=hi.primitive({v1:"BOOLEAN",v2:Cn.boolean({default:void 0})})))}let d=this.convertHeaderExamples({header:a,headerName:i,schema:o});t.push({name:this.context.casingsGenerator.generateNameAndWireValue({name:i,wireValue:i}),docs:a.description,valueType:c,env:void 0,v2Examples:d,availability:void 0})}return t}convertHeaderExamples({header:t,headerName:r,schema:i}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},a=t.example,o=t.examples;for(let[c,d]of Object.entries(o??{})){let s=this.context.resolveExampleWithValue(d);s!=null&&(n.userSpecifiedExamples[c]=this.generateHeaderExample({schema:i,example:s}))}if(a!=null){let c=this.context.generateUniqueName({prefix:`${r}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[c]=this.generateHeaderExample({schema:i,example:a})}if(Object.keys(n.userSpecifiedExamples).length===0&&i!=null){let c=`${r}_example`;n.autogeneratedExamples[c]=this.generateHeaderExample({schema:i,example:void 0,ignoreErrors:!0})}return n}generateHeaderExample({schema:t,example:r,ignoreErrors:i}){if(t==null)return r;let n=new NU({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:a,errors:o}=n.convert();return i||o.forEach(c=>{this.context.errorCollector.collect({message:c.message,path:c.path})}),a}};function TU_(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}var MIu=class e extends Xya{idempotent;idToAuthScheme;topLevelServers;pathLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a,idempotent:o,idToAuthScheme:c,topLevelServers:d,pathLevelServers:s,streamingExtension:u}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a}),this.idempotent=o,this.idToAuthScheme=c,this.topLevelServers=d,this.pathLevelServers=s,this.streamingExtension=u}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=this.getGroupDisplayName(r),{headers:a,pathParameters:o,queryParameters:c}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),d=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:i,streamingExtension:this.streamingExtension,queryParameters:c}),s=d?.[0]?.requestBody,u=d?.[0]?.streamRequestBody,f={requestBodies:d?.map(W=>W.requestBody)},p=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:i,streamingExtension:this.streamingExtension}),h=p?.response,_=p?.streamResponse,y=p!=null?p.errors:[],b={},v=y.map(W=>W.error),O=eI(this.path),m=this.getEndpointBaseUrl(),g=this.getEndpointBaseUrls(),A=this.convertExamples({httpPath:O,httpMethod:t,baseUrl:m}),j=new Set(this.operation.security?.flatMap(W=>Object.keys(W))??[]),S=this.authSchemeToHeaders(Array.from(j));S.length>0&&a.push(...S);for(let W of y){let Oe=W.error,Ae=W.errorType,L=Oe.error.errorId,Q=W.examples;b[L]={name:Oe.error,displayName:W.displayName,discriminantValue:{name:Oe.error.name,wireValue:L},type:Ae,statusCode:W.statusCode,isWildcardStatusCode:W.isWildcardStatusCode,docs:Oe.docs,examples:[],v2Examples:{userSpecifiedExamples:Q??{},autogeneratedExamples:{}},headers:W.headers}}let w=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],I=new jao({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),T=new jao({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??I,K={displayName:this.operation.summary,method:t,baseUrl:m,v2BaseUrls:g,path:O,pathParameters:o,queryParameters:c,headers:a.filter((W,Oe,Ae)=>Oe===Ae.findIndex(L=>L.name.wireValue===W.name.wireValue)),responseHeaders:p?.responseHeaders,sdkRequest:void 0,errors:v,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:O,allPathParameters:o,pagination:void 0,transport:void 0,source:j5.openapi(),audiences:w,retries:void 0,apiPlayground:T},G=this.context.namespace!=null?[this.context.namespace]:[],z=r?.map(W=>An(W));return G.push(...z??[]),{audiences:w,group:r,groupDisplayName:n,errors:b,endpoint:{...K,id:`endpoint_${G.join("/")}.${i}`,name:this.context.casingsGenerator.generateName(i),requestBody:s,v2RequestBodies:f,response:h,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:A.examples},v2Responses:{responses:p?.v2Responses}},streamEndpoint:_!=null&&_.body!=null?{...K,id:`endpoint_${G.join("/")}.${i}_stream`,name:this.context.casingsGenerator.generateName(`${i}_stream`),requestBody:u,v2RequestBodies:void 0,response:_,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:A.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:_.body,docs:_.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[])}}convertResponseBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.responses==null)return;let a,o=!1;for(let[c,d]of Object.entries(this.operation.responses)){let s=/^[45]XX$/i.test(c),u,f=!1;if(s)u=parseInt(c.charAt(0))*100,f=!0;else{if(u=parseInt(c),isNaN(u)||u<200||u>=300&&u<400)continue;f=u>=400&&u<600}if(a==null&&(a={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]}),u>=200&&u<300){let p=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,c]});if(p==null)continue;let _=new wao({context:this.context,breadcrumbs:[...t,c],responseBody:p,group:r??[],method:i,statusCode:c,streamingExtension:n}).convert();_!=null&&(this.inlinedTypes={...this.inlinedTypes,..._.inlinedTypes},o||(o=!0,a.response={statusCode:u,isWildcardStatusCode:s?!0:void 0,body:_.responseBody,docs:p.description},a.streamResponse={statusCode:u,isWildcardStatusCode:s?!0:void 0,body:_.streamResponseBody,docs:p.description},_.headers!=null&&(a.responseHeaders=_.headers)),a.v2Responses=[...a.v2Responses??[],{statusCode:u,isWildcardStatusCode:s?!0:void 0,body:_.responseBody,docs:p.description}])}if(f){let p=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:[...t,c]});if(p==null)continue;let _=new SIu({context:this.context,breadcrumbs:[...t,c],responseError:p,group:r??[],method:i,methodName:this.evaluateMethodNameFromOperation(),statusCode:u,isWildcardStatusCode:s?!0:void 0}).convert();_!=null&&(this.inlinedTypes={...this.inlinedTypes,..._.inlinedTypes},a.errors.push(_))}}if(this.streamingExtension!=null){a==null&&(a={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]});let d=new wao({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:i,statusCode:"stream",streamingExtension:n}).convert();d!=null&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},a.response={statusCode:200,isWildcardStatusCode:void 0,body:d.responseBody,docs:void 0},a.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:d.streamResponseBody,docs:void 0},a.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:d.responseBody,docs:void 0}])}return a}computeEndpointAuth(){return this.operation.security!=null&&this.operation.security.length===0?!1:this.operation.security!=null&&this.operation.security.length>0?!0:this.context.spec.security!=null&&this.context.spec.security.length>0||this.shouldApplyDefaultAuthOverrides()}computeEndpointSecurity(){return this.operation.security!=null&&this.operation.security.length===0?[]:this.context.authOverrides?.auth!=null?this.getDefaultSecurityFromAuthOverrides():this.operation.security??this.context.spec.security}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth)return!1;let t=this.context.spec.security!=null&&this.context.spec.security.length>0,r=this.operation.security!=null&&this.operation.security.length>0;return!(t||r)}getDefaultSecurityFromAuthOverrides(){if(!this.context.authOverrides?.auth)return;let t=this.context.authOverrides.auth;if(typeof t=="string"){let r={};return r[t]=[],[r]}if(typeof t=="object"&&"any"in t){let r=t.any;if(Array.isArray(r))return r.map(i=>{let n=typeof i=="string"?i:i.scheme,a={};return a[n]=[],a})}}authSchemeToHeaders(t){let r=[];for(let i of t){let n=this.idToAuthScheme?.[i];if(n==null)continue;let a={valueType:Va.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0};switch(n.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...a});break;case"header":r.push({name:n.name,...a});break}}return r}convertExamples({httpPath:t,httpMethod:r,baseUrl:i}){let a=new wIu({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],c=new PIu({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],s=a.some(u=>Array.isArray(u["code-samples"])&&u["code-samples"].length>0)?a:[...a,...c];return s.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:s}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:s}),streamExamples:{}}}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){let a=n.filter(s=>!(s.response!=null&&"stream"in s.response)),o=n.filter(s=>s.response!=null&&"stream"in s.response),c=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:a}),d=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:o});return{examples:c,streamExamples:d}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:i,fernExamples:n}){return Object.fromEntries(n.map((a,o)=>[this.getExampleName({example:a,exampleIndex:o}),{displayName:void 0,request:a.request!=null||a["path-parameters"]!=null||a["query-parameters"]!=null||a.headers!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,a["path-parameters"]??{})},baseUrl:void 0,environment:i,auth:void 0,pathParameters:a["path-parameters"]??{},queryParameters:a["query-parameters"]??{},headers:a.headers??{},requestBody:a.request??void 0}:void 0,response:a.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:a})}:void 0,codeSamples:a["code-samples"]?.map(c=>{let d=("language"in c?c.language:c.sdk)??void 0;return{name:c.name,docs:void 0,language:d,code:c.code}})}]))}getExampleName({example:t,exampleIndex:r}){return t.name??t["code-samples"]?.[0]?.name??`Example_${r}`}getExampleResponseBody({example:t}){if(t.response!=null){if("stream"in t.response)return Ir.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return Ir.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new BN.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert();if(r!=null)return this.context.logger.debug(`[getEndpointBaseUrl] Endpoint ${this.method.toUpperCase()} ${this.path} specifies a server with "${nn.SERVER_NAME_V2}" extension. Returning server type: ${r}`),r;let i=this.operation.servers?.[0]??this.pathLevelServers?.[0];if(i==null)return;let a=this.topLevelServers?.find(o=>o.url===i.url)??i;return vAe.getServerName({server:a,context:this.context})}getEndpointBaseUrls(){let t=this.operation.servers??this.pathLevelServers;return t?.map(i=>{let a=this.topLevelServers?.find(o=>o.url===i.url)??i;return vAe.getServerName({server:a,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(i=>`${r[i.pathParameter]?.toString()??i.pathParameter}${i.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(i=>i.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0];r!=null&&(r=this.context.getDisplayNameForTag(r));let i=t?.[t.length-1];if(i!=null&&r!=null)return r.toLowerCase().replaceAll(" ","")===i?r:void 0}};var DIu=class extends Va{pathItem;path;idToAuthScheme;topLevelServers;constructor({context:t,breadcrumbs:r,pathItem:i,path:n,idToAuthScheme:a,topLevelServers:o}){super({context:t,breadcrumbs:r}),this.pathItem=i,this.path=n,this.idToAuthScheme=a,this.topLevelServers=o}convert(){let t=[],r=[],i={};for(let n of BU_){let a=this.pathItem[n];if(a==null)continue;let o=[...this.breadcrumbs,n],c=this.tryParseAsWebhook({operationBreadcrumbs:o,operation:a,method:n,context:this.context});if(c!=null){r.push(c),Object.assign(i,c.inlinedTypes);continue}let s=new mIu({breadcrumbs:o,operation:a,context:this.context}).convert(),u=this.tryParseAsHttpEndpoint({operationBreadcrumbs:o,operation:a,method:n,streamingExtension:s});u!=null&&(t.push(u),Object.assign(i,u.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:i}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:i,context:n}){return new AIu({breadcrumbs:i,operation:t,context:n}).convert()?new Zya({context:this.context,breadcrumbs:i,operation:t,method:Psl.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:i,streamingExtension:n}){new OIu({breadcrumbs:i,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let d=new vIu({breadcrumbs:i,operation:t,context:this.context}).convert();return new MIu({context:this.context,breadcrumbs:i,operation:t,method:Psl.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:n}).convert()}};var IIu=class extends Va{securityScheme;schemeId;constructor({context:t,breadcrumbs:r,securityScheme:i,schemeId:n}){super({context:t,breadcrumbs:r}),this.securityScheme=i,this.schemeId=n}getExtension(t){return this.securityScheme[t]}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme?.toLowerCase()==="bearer"){let t=this.getExtension("x-fern-bearer"),r=t?.name??"token",i=t?.env;return AP.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName(r),tokenEnvVar:i,docs:this.securityScheme.description})}if(this.securityScheme.scheme?.toLowerCase()==="basic"){let t=this.getExtension("x-fern-basic"),r=t?.username?.name??"username",i=t?.password?.name??"password",n=t?.username?.env,a=t?.password?.env;return AP.basic({key:this.schemeId,username:this.context.casingsGenerator.generateName(r),password:this.context.casingsGenerator.generateName(i),usernameEnvVar:n,passwordEnvVar:a,usernameOmit:!1,passwordOmit:!1,docs:this.securityScheme.description})}break}case"apiKey":{if(this.securityScheme.in==="header"){let t=this.getExtension("x-fern-header"),r=t?.name??"apiKey",i=t?.env,n=t?.prefix;return AP.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(r),wireValue:this.securityScheme.name},valueType:Va.OPTIONAL_STRING,prefix:n,headerEnvVar:i,docs:this.securityScheme.description})}break}case"oauth2":return AP.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var Eao=class extends jHt{constructor({breadcrumbs:t,context:r,audiences:i}){super({breadcrumbs:t,context:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertBasePath(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:t,errors:r}=this.convertPaths();this.addErrorsToIr(r);let{defaultUrl:i}=this.convertServers({endpointLevelServers:t});this.updateEndpointsWithDefaultUrl(i);let n=this.context.spec.info?.title?.trim();return n&&n!=='""'&&(this.ir.apiDisplayName=n),this.finalizeIr()}convertGlobalHeaders(){this.context.globalHeaderOverrides;let r=new _Iu({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let i=DU_({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(i),this.context.setGlobalHeaders(i)}}convertBasePath(){let r=new hIu({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();r!=null&&(this.ir.basePath=eI(r))}convertSecuritySchemes(){if(this.context.authOverrides){let r=Xnl({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertOpenApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertOpenApiSecuritySchemes(){let t=[];for(let[r,i]of Object.entries(this.context.spec.components?.securitySchemes??{})){let n=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:["components","securitySchemes",r]});if(n==null)continue;let o=new IIu({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:n,schemeId:r}).convert();o!=null&&t.push(o)}return t}convertServers({endpointLevelServers:t}){if(this.context.environmentOverrides){let n=ano({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return n!=null&&this.addEnvironmentsToIr({environmentConfig:n.environmentsConfig,audiences:n.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let i=new vAe({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new $A.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&this.addSchemaOutputToIr(t,n)}}convertWebhooks(){for(let[,t]of Object.entries(this.context.spec.webhooks??{})){if(t==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});continue}if(!("post"in t)){this.context.errorCollector.collect({message:"Skipping webhook as it is not a POST method",path:this.breadcrumbs});continue}if(t.post?.operationId==null){this.context.errorCollector.collect({message:"Skipping webhook as no operationId is present",path:this.breadcrumbs});continue}let r=t.post.operationId,n=new Zya({context:this.context,breadcrumbs:["webhooks",r],operation:t.post,method:RU_.OpenAPIV3.HttpMethods.POST,path:r}).convert();n!=null&&(this.addWebhookToIr({webhook:n.webhook,operationId:r,audiences:n.audiences,group:n.group}),this.addTypesToIr(n.inlinedTypes))}}convertPaths(){let t=[],r={};for(let[i,n]of Object.entries(this.context.spec.paths??{})){if(n==null)continue;let o=new DIu({context:this.context,breadcrumbs:["paths",i],topLevelServers:this.context.spec.servers,pathItem:n,path:i}).convert();if(o!=null){for(let c of o.endpoints){if(c.streamEndpoint!=null&&this.addEndpointToIr({endpoint:c.streamEndpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName}),this.addEndpointToIr({endpoint:c.endpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName}),c.servers)for(let d of c.servers)this.shouldAddServerToCollectedServers({server:d,currentServers:t})&&t.push(d);if(c.errors)for(let[d,s]of Object.entries(c.errors))r[d]=s}for(let c of o.webhooks){let d=this.context.getGroup({groupParts:c.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:c.webhook,operationId:d.join("."),group:d,audiences:c.audiences})}this.addTypesToIr(o.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;this.context.spec.components||(this.context.spec.components={}),this.context.spec.components.securitySchemes={};let t={};for(let r of Object.keys(this.context.authOverrides["auth-schemes"]))this.context.spec.components.securitySchemes[r]={type:"http",scheme:"bearer"},t[r]=[];this.context.spec.security=[t],this.removeEndpointSpecificAuth()}removeEndpointSpecificAuth(){if(this.context.spec.paths)for(let t of Object.values(this.context.spec.paths)){if(!t)continue;let r=["get","post","put","patch","delete","options","head","trace"];for(let i of r){let n=t[i];n?.security&&delete n.security}}}};var BIu=class extends Nl{tag;key="x-displayName";constructor({breadcrumbs:t,tag:r,context:i}){super({breadcrumbs:t,context:i}),this.tag=r}convert(){if(typeof this.tag!="object"||this.tag==null)return;let t=this.tag[this.key];if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"x-displayName extension must be a string",path:this.breadcrumbs});return}if(t.trim().length!==0)return{displayName:t}}}};var g8i=class extends kq{globalHeaderNames;tagToDisplayName={};isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;n==="reference_identifier"?c=i??o.value.title:n==="discriminator_key"?c=o.value.title??i:n==="schema_identifier"&&(c=o.value.title);let d;if(a.includes("/")){let u=new $A.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:o.value,id:a}).convert();u!=null&&(d={[a]:u.convertedSchema})}return{ok:!0,reference:hi.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,default:void 0,inline:!1,displayName:c}),inlinedTypes:d}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>r.name.wireValue)}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let n=new BIu({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName??r.name;this.tagToDisplayName[r.name]=n}return this.tagToDisplayName[t]??t}};var jWI=Bt.object({description:Bt.string().optional(),required:Bt.boolean().optional(),deprecated:Bt.boolean().optional(),allowEmptyValue:Bt.boolean().optional(),style:Bt.string().optional(),explode:Bt.boolean().optional(),allowReserved:Bt.boolean().optional(),schema:Bt.any().optional(),example:Bt.any().optional(),examples:Bt.record(Bt.string(),Bt.any()).optional(),content:Bt.record(Bt.string(),Bt.any()).optional()}),wWI=jWI.extend({name:Bt.string(),in:Bt.string()}),EWI=Bt.array(wWI),CIu=class extends Nl{operation;key="x-fern-parameters";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null)try{return EWI.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${r instanceof Error?r.message:String(r)}`,path:this.breadcrumbs});return}}};var qIu=class extends Va{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:i,pathParameters:n=[],queryParameters:a=[],headers:o=[],topLevelServers:c=[]}){super({context:t,breadcrumbs:r}),this.method=i,this.pathParameters=n,this.queryParameters=a,this.headers=o,this.topLevelServers=c}convert(){let t={},r="";for(let s of this.pathParameters)r+=`/{${s.name.originalName}}`;let i=eI(r),n=[];for(let[s,u]of this.method.params.entries()){let f;if(this.context.isReferenceObject(u)){let y=this.context.resolveReference({reference:u});if(y.resolved)f=y.value;else continue}else f=u;let p=[this.method.name,"Param",f.name].join("_"),_=new $A.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",f.name],schemaIdOverride:p,context:this.context,schemaOrReference:f.schema,wrapAsOptional:!f.required}).convert();_!=null&&(n.push({docs:f.description,availability:this.context.getAvailability({node:u,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:f.name,wireValue:f.name}),valueType:_.type,v2Examples:_.schema?.typeDeclaration.v2Examples,propertyAccess:void 0}),t={..._.inlinedTypes,...t,..._.schema!=null?{[p]:_.schema}:{}})}let a;if(this.method.result!=null){let s=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(s!=null){let u=new $A.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:s.schema}),f=[this.method.name,"Result"].join("_"),p=u.convert();p!=null&&(a={docs:s.description,v2Examples:p.schema?.typeDeclaration.v2Examples,responseBodyType:p.type},t={...p.inlinedTypes,...t,...p.schema!=null?{[f]:p.schema}:{}})}}let o=this.getEndpointBaseUrls(),c=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:o,basePath:void 0,auth:!1,security:void 0,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:i,fullPath:i,requestBody:n.length>0?FA.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:n,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,v2RequestBodies:void 0,sdkRequest:void 0,response:a!=null?{body:np.json(Lq.response(a)),statusCode:void 0,isWildcardStatusCode:void 0,docs:a.docs}:void 0,v2Responses:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples()},transport:void 0,availability:void 0,source:j5.openrpc(),audiences:c,retries:void 0,apiPlayground:void 0,responseHeaders:[]},audiences:c,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(i=>i.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(i=>{if(this.topLevelServers.find(c=>c.name===i.name&&c.url!==i.url)!=null)return i.url;let o=this.topLevelServers.find(c=>c.url===i.url)??i;return vAe.getServerName({server:o,context:this.context})})}convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let i of this.method.examples??[]){let n;if(this.context.isReferenceObject(i)){let d=this.context.resolveReference({reference:i});if(d.resolved)n=d.value;else continue}else n=i;let a;if(n.result)if(this.context.isReferenceObject(n.result)){let d=this.context.resolveReference({reference:n.result});d.resolved&&(a=d.value)}else a=n.result;let o=n.name??`Example ${r+1}`,c=[];if(n.params&&Array.isArray(n.params)){c=[];for(let d of n.params)if(this.context.isReferenceObject(d)){let s=this.context.resolveReference({reference:d});if(s.resolved)c.push(s.value);else continue}else c.push(d)}t[o]={displayName:void 0,request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:c.map(d=>d.value)??void 0},response:{docs:void 0,statusCode:void 0,body:a?.value?Ir.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:n.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++r}return t}};var TIu=class extends $A.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}convert(){let t,r={};if(this.parameter.schema!=null){let n=new $A.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();n!=null&&(t=n.type,r=n.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var Sao=class extends jHt{constructor({context:t,breadcrumbs:r,audiences:i}){super({context:t,breadcrumbs:r,audiences:i})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.convertSchemas();let{endpointLevelServers:t}=this.convertMethods(),{defaultUrl:r}=this.convertServers({endpointLevelServers:t});return this.updateEndpointsWithDefaultUrl(r),this.finalizeIr()}convertServers({endpointLevelServers:t}){let i=new vAe({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:i?.value}),{defaultUrl:i?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=new $A.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&this.addSchemaOutputToIr(t,n)}}convertMethods(){let t=[],i=new CIu({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),n=[],a=[],o=[];if(i&&i.length>0)for(let[d,s]of i.entries()){let f=new TIu({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${d}]`],parameter:s}).convert();if(f!=null)switch(f.type){case"path":{n.push(f.parameter);break}case"query":{a.push(f.parameter);break}case"header":{o.push(f.parameter);break}}}let c=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let d of this.context.spec.methods??[]){let s=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:["methods"]});if(s==null)continue;let f=new qIu({context:this.context,breadcrumbs:["methods"],method:s,pathParameters:n,queryParameters:a,headers:o,topLevelServers:this.context.spec.servers}).convert();if(f!=null&&(this.addEndpointToIr({endpoint:f.endpoint,audiences:f.audiences,endpointGroup:c,serviceName:"service_root"}),this.addTypesToIr(f.inlinedTypes),f.servers))for(let p of f.servers)this.shouldAddServerToCollectedServers({server:p,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(p))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(i=>i.name===t.name&&i.url!==t.url)?{...t,name:t.url}:t}};var Mao=class extends kq{isReferenceObject(t){return t!=null&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:i,displayNameOverrideSource:n}){let a=this.getTypeIdFromSchemaReference(t);if(a==null)return{ok:!1};let o=this.resolveReference({reference:t,breadcrumbs:r});if(!o.resolved)return{ok:!1};let c;return n==="reference_identifier"?c=i??o.value.title:(n==="discriminator_key"||n==="schema_identifier")&&(c=o.value.title??i),{ok:!0,reference:hi.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(a),typeId:a,displayName:c,default:void 0,inline:!1})}}};var Y3_=require("fs/promises");var zU_={[Ki.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,xf(e)])),[Ki.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[Ki.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[Ki.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all","kwargs"]),[Ki.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","vendor","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[Ki.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime","object_id","hash","eql?","equal?","method","send","respond_to?","respond_to_missing?","instance_of?","kind_of?","is_a?","extend","singleton_class","instance_variables","instance_variable_get","instance_variable_set","instance_variable_defined?","remove_instance_variable","public_methods","private_methods","protected_methods","singleton_methods"]),[Ki.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[Ki.GenerationLanguage.RUST]:new Set(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","union","unsafe","use","where","while","abstract","become","box","do","final","macro","override","priv","try","typeof","unsized","virtual","yield","bool","char","f32","f64","i8","i16","i32","i64","i128","isize","str","u8","u16","u32","u64","u128","usize","String","Vec","Option","Result","Box","Rc","Arc","Cell","RefCell","HashMap","HashSet","BTreeMap","BTreeSet"]),[Ki.GenerationLanguage.SWIFT]:new Set([])};var SWI=["go","ruby"];function NIu({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let o=zWI(n),c=p=>({unsafeName:p,safeName:MWI({name:p,keywords:DWI({generationLanguage:e,keywords:t})})}),d=An(o),s=xf(d),u=l2t(o),f=gmn(d);return r&&(!CWI(f)&&(e==null||SWI.includes(e))&&(d=f.map((p,h)=>{if(h>0){let _=RIu(p);if(_!=null)return _;if(zIu(p))return p.toUpperCase()}return p}).join(""),s=xf(f.map((p,h)=>{let _=RIu(p);return _??(zIu(p)?p.toUpperCase():h===0?xf(p):p)}).join(""))),u=o.split(" ").map(p=>p.split(/(\d+)/).map(l2t).join("")).join("_")),{originalName:n,camelCase:c(a?.casingOverrides?.camel??d),snakeCase:c(a?.casingOverrides?.snake??u),screamingSnakeCase:c(a?.casingOverrides?.["screaming-snake"]??u.toUpperCase()),pascalCase:c(a?.casingOverrides?.pascal??s)}},generateNameAndWireValue:({name:n,wireValue:a,opts:o})=>({name:i.generateName(n,o),wireValue:a})};return i}function MWI({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":BWI(e)?"_"+e:e}function DWI({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return zU_[e]}var IWI=/^[0-9]/;function BWI(e){return IWI.test(e)}function CWI(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=RIu(i)!=null||zIu(i),a=RIu(t)!=null||zIu(t);return n&&a})}function RIu(e){return TWI.get(e.toUpperCase())}function zIu(e){return qWI.has(e.toUpperCase())}var qWI=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),TWI=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]),RWI=[[/\[\]/g,"Array"]];function zWI(e){return RWI.reduce((t,[r,i])=>t.replace(r,i),e)}var NU_=require("fs/promises");async function jsl({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,NU_.readFile)(t)).toString(),n;try{n=JSON.parse(i)}catch{n=Mi.load(i)}return r!=null?await Wya({absoluteFilePathToOverrides:r,context:e,data:n}):n}var f4_=ce(l4_(),1);function ner(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...o}={}){let c=n.reduce((s,u)=>({...s,[u]:"<redacted>"}),a),d=[t,...r].join(" ");for(let[s,u]of Object.entries(c))d=d.replaceAll(s,u);return e?.debug(`+ ${d}`),(0,f4_.default)(t,r,o)}async function Q_(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...o}={}){let c=ner(e,t,r,{doNotPipeOutput:i,secrets:n,substitutions:a,...o});i||(c.stdout?.pipe(process.stdout),c.stderr?.pipe(process.stderr));let d=await c;return d.stdout==null&&(d.stdout=""),d.stderr==null&&(d.stderr=""),d}function Cen(e,{logger:t,...r}={}){return(i,n)=>Q_(t,e,i,{...r,...n})}var k7=require("fs/promises"),m4_=ce(require("path"),1),Wsl=ce(GQ(),1);var Twn=require("fs/promises"),d4_=ce(GQ(),1);function Tao(e){return e.includes("server hosted at that remote is unavailable")||e.includes("fetch failed")||e.includes("failed to connect")||e.includes("network")||e.includes("ENOTFOUND")||e.includes("ETIMEDOUT")||e.includes("TIMEDOUT")||e.includes("timed out")||e.includes("ECONNREFUSED")||e.includes("ECONNRESET")||e.includes("socket hang up")}var qao,Lsl;async function Vsl(e,t,r=5e3){return qao!==void 0?qao:(Lsl==null&&(Lsl=DxI(e,t,r)),Lsl)}async function DxI(e,t,r){t.debug(`Detecting air-gapped mode by checking connectivity to ${e}`);try{return await fetch(e,{method:"GET",signal:AbortSignal.timeout(r)}),qao=!1,t.debug("Network check succeeded - not in air-gapped mode"),!1}catch(i){let n=i instanceof Error?i.message:String(i);return Tao(n)?(qao=!0,t.debug(`Network check failed - entering air-gapped mode: ${n}`),!0):(qao=!1,!1)}}async function HIu(e,t){let r=ut(e,me.of("buf.lock")),i=!1;try{await(0,Twn.access)(r),i=!0,t.debug(`Found buf.lock at: ${r}`)}catch{t.debug(`No buf.lock found at: ${r}`)}if(!i)return!1;let n=vr.of((await d4_.default.dir()).path);try{let a=ut(e,me.of("buf.yaml"));try{await(0,Twn.cp)(a,ut(n,me.of("buf.yaml"))),await(0,Twn.cp)(r,ut(n,me.of("buf.lock")))}catch{return!1}try{return await ner(t,"buf",["dep","update"],{cwd:n,stdio:"pipe",timeout:3e4}),t.debug("Network check succeeded - not in air-gapped mode"),!1}catch(o){let c=o instanceof Error?o.message:String(o);return Tao(c)?(t.debug(`Network check failed - entering air-gapped mode: ${c.substring(0,100)}`),!0):!1}}finally{try{await(0,Twn.rm)(n,{recursive:!0,force:!0})}catch{}}}var p4_="buf.gen.yaml",IxI="output",h4_=`${IxI}/ir.json`,_4_="protoc-gen-fern",y4_=`version: v1
|
|
1601
1601
|
`,b4_=`version: v2
|
|
1602
1602
|
`,GIu=e=>{let t=`version: v1
|
|
1603
1603
|
`;if(e.length>0){t+=`deps:
|
|
@@ -2472,7 +2472,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
|
|
|
2472
2472
|
Run ${Je.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
2473
2473
|
Run ${Je.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),gla(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function ENp({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!KuS(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+=`
|
|
2474
2474
|
${await JF5(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+Je.dim(c.currentVersion)+Je.reset(" \u2192 ")+Je.green(c.latestVersion);return n+=`
|
|
2475
|
-
`,i?gla(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function JF5(e){let r=await new GuS.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 YF5({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await JuS({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=Yki(u.name,f),h=await sHt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});h!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:h})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await JuS({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 f=Yki(s.name,u),p=await sHt({generatorName:f,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 JuS({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 cAe({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?DU(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 YuS(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=p2(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 P_c({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await YF5({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(...YuS(s,d,t.logger));else o.push(...YuS(c.versions,void 0,t.logger))}return o}async function $bn({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:Ato(e.packageName,{version:t?"prerelease":"latest"})}var XuS=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],j_c=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=na.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new BAn(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.64.
|
|
2475
|
+
`,i?gla(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function JF5(e){let r=await new GuS.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 YF5({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await JuS({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=Yki(u.name,f),h=await sHt({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});h!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:h})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await JuS({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 f=Yki(s.name,u),p=await sHt({generatorName:f,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 JuS({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 cAe({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?DU(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 YuS(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=p2(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 P_c({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await YF5({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(...YuS(s,d,t.logger));else o.push(...YuS(c.versions,void 0,t.logger))}return o}async function $bn({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:Ato(e.packageName,{version:t?"prerelease":"latest"})}var XuS=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],j_c=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=na.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new BAn(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.64.4"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${Je.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new gS}failWithoutThrowing(t,r){this.didSucceed=!1,bka({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await ula()).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 $uS({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
2476
2476
|
`)||(r+=`
|
|
2477
2477
|
`),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=YRc(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 E8o(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 gS}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await ula()).sendEvent(t)}logger=P7((t,...r)=>this.log(t,...r));stderr=P7((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=ZuS(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?ZuS(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=XuS[this.numTasks++%XuS.length],o=Je.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===zA.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=>PZ.indexOf(n.level)>=PZ.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===na.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 $bn({cliEnvironment:this.environment,includePreReleases:t}),i=p2(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await P_c({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await jNp({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:Je.yellow("?"),style:{answer:n=>Je.cyan(n),message:n=>Je.bold(n),highlight:n=>Je.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
|
|
2478
2478
|
Cancelled by user.`),new gS):i}}async getInput(t){return await mNp({message:t.message,default:t.default})}};function ZuS(e){return`[${e}]:`}var kuS=require("fs/promises");async function SNp({context:e,nameOverride:t,...r}){let i=await JM(t);return i==null?e.failAndThrow(`Directory "${t??ME}" not found.`):await esS({absolutePathToFernDirectory:i,context:e,nameOverride:t,...r})}async function esS({absolutePathToFernDirectory:e,cliName:t,cliVersion:r,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n,context:a}){let o=[];(await ii(ut(e,me.of(N7)))||await ii(ut(e,me.of(HM)))||await ii(ut(e,me.of(GM)))||await ii(ut(e,me.of(kda)))||await ii(ut(e,me.of(Bto)))||await ii(ut(e,me.of(QYc))))&&(o=await tsS({cliName:t,fernDirectory:e,cliVersion:r,context:a,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n}));let c=await LPp({fernDirectory:e,context:a});return o.length===0&&c==null?a.failAndThrow(`No SDK specifications or docs specifications found. Please ensure one of the following .yml (not .yaml) files is present:
|
|
@@ -2508,7 +2508,7 @@ The generator configuration must be an object with a 'name' property, but the cu
|
|
|
2508
2508
|
|
|
2509
2509
|
Please check your generators.yml file and ensure the generator is properly configured.`);let o=n,c=await csS({generatorName:t,logger:a});if(c==null)return;let d=ZF5({migrations:c.migrations,from:r,to:i,logger:a});if(d.length!==0)return lsS({migrations:d,config:o,logger:a})}function fsS(e){return{"fernapi/fern-typescript-sdk":"https://buildwithfern.com/learn/sdks/generators/typescript/changelog","fernapi/fern-typescript-node-sdk":"https://buildwithfern.com/learn/sdks/generators/typescript/changelog","fernapi/fern-python-sdk":"https://buildwithfern.com/learn/sdks/generators/python/changelog","fernapi/fern-go-sdk":"https://buildwithfern.com/learn/sdks/generators/go/changelog","fernapi/fern-java-sdk":"https://buildwithfern.com/learn/sdks/generators/java/changelog","fernapi/fern-csharp-sdk":"https://buildwithfern.com/learn/sdks/generators/csharp/changelog","fernapi/fern-php-sdk":"https://buildwithfern.com/learn/sdks/generators/php/changelog","fernapi/fern-ruby-sdk":"https://buildwithfern.com/learn/sdks/generators/ruby/changelog","fernapi/fern-swift-sdk":"https://buildwithfern.com/learn/sdks/generators/swift/changelog"}[e]}async function eQ5({absolutePathToWorkspace:e,context:t,generatorFilter:r,groupFilter:i,includeMajor:n,channel:a,cliVersion:o}){let c=await een({absolutePathToWorkspace:e});if(c==null||!await ii(c))return t.logger.debug("Generators configuration file was not found, no generators to upgrade."),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};let d=await(0,S_c.readFile)(c);t.logger.debug(`Found generators: ${d.toString()}`);let s=jGa.default.parseDocument(d.toString()),u=s.get("groups");if(u==null)return t.logger.debug("No groups were found within the generators configuration, no generators to upgrade."),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};if(!jGa.default.isMap(u))return t.failAndThrow(`Expected 'groups' to be a map in ${M8o.default.relative(process.cwd(),c)}`),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};t.logger.debug(`Groups found: ${u.toString()}`);let f=[],p=[],h=[];for(let _ of u.items){let y=_.key.value,b=_.value;if(!jGa.default.isMap(b)){t.failAndThrow(`Expected group ${y} to be a map in ${M8o.default.relative(process.cwd(),c)}`);continue}if(i!=null&&i!==y){t.logger.debug(`Skipping group ${y} as it does not match the filter: ${i}`);continue}let v=b.get("generators");if(!jGa.default.isSeq(v)){t.failAndThrow(`Expected group ${y} to have a 'generators' key in ${M8o.default.relative(process.cwd(),c)}`);continue}t.logger.debug(`Generators found: ${v.toString()}`);for(let O of v.items){jGa.default.isMap(O)||t.failAndThrow(`Expected generator in group ${y} to be a map in ${M8o.default.relative(process.cwd(),c)}`);let m=O.get("name"),g=Yki(m,t),A=r!=null?DU(r):void 0;if(A!=null&&g!==A){t.logger.debug(`Skipping generator ${m} as it does not match the filter: ${r}`);continue}let j=O.get("version"),S=await sHt({generatorName:g,cliVersion:o,currentGeneratorVersion:j,channel:a,includeMajor:n,context:t}),w=S??j;if(S!=null)if(S!==j){t.logger.debug(Je.green(`Upgrading ${m} from ${j} to ${S}`)),O.set("version",S);let E=0,I=[],q=O.toJSON(),R=await MNp({generatorName:g,from:j,to:S,config:q,logger:t.logger});if(R!=null){E=R.migrationsApplied,I=R.appliedVersions;let T=new Set(Object.keys(q)),K=new Set(Object.keys(R.config));for(let G of T)K.has(G)||O.delete(G);for(let[G,z]of Object.entries(R.config))O.set(G,z);t.logger.debug(Je.dim(`Applied ${E} migration(s): ${I.join(", ")}`))}p.push({generatorName:m,groupName:y,previousVersion:j,newVersion:S,migrationsApplied:E>0?E:void 0,migrationVersions:I.length>0?I:void 0})}else t.logger.debug(Je.gray(`${m} is already on the latest version: ${j}`)),h.push({generatorName:m,groupName:y,version:j});if(!n){let E=await sHt({generatorName:g,cliVersion:o,currentGeneratorVersion:w,channel:a,includeMajor:!0,context:t});if(E!=null){let I=DNp.default.parse(w),q=DNp.default.parse(E);I!=null&&q!=null&&q.major>I.major&&f.push({generatorName:m,currentVersion:w,latestMajorVersion:E})}}}}return{updatedConfiguration:s.toString(),skippedMajorUpgrades:f,appliedUpgrades:p,alreadyUpToDate:h}}async function dsS({cliContext:e,generator:t,group:r,project:{apiWorkspaces:i},includeMajor:n,channel:a}){let o=[],c=[],d=[];if(await Promise.all(i.map(async s=>{await e.runTaskForWorkspace(s,async u=>{let f=await X_a({absolutePathToWorkspace:s.absoluteFilePath,context:u})??{};if(f==null||f.groups==null){u.logger.debug("No groups were found within the generators configuration, no generators to upgrade.");return}s.workspaceName==null?u.logger.info("Upgrading generators."):u.logger.info(`Upgrading generators in workspace: ${s.workspaceName}.`);let p=await eQ5({absolutePathToWorkspace:s.absoluteFilePath,context:u,generatorFilter:t,groupFilter:r,includeMajor:n,channel:a,cliVersion:e.environment.packageVersion}),h=await een({absolutePathToWorkspace:s.absoluteFilePath});h!=null&&p.updatedConfiguration!=null&&await(0,S_c.writeFile)(h,p.updatedConfiguration),o.push(...p.skippedMajorUpgrades),p.appliedUpgrades.length>0&&c.push({workspace:s.workspaceName,upgrades:p.appliedUpgrades}),p.alreadyUpToDate.length>0&&d.push({workspace:s.workspaceName,upToDate:p.alreadyUpToDate})})})),c.length>0){e.logger.info(""),e.logger.info(Je.green("Successfully upgraded generators:"));for(let{workspace:s,upgrades:u}of c){let f=new Map;for(let p of u){let h=f.get(p.groupName)??[];h.push(p),f.set(p.groupName,h)}for(let[p,h]of f){let _=s!=null?`[${s}] `:"";e.logger.info(Je.green(`${_}Group ${p}:`));for(let y of h){e.logger.info(Je.green(` - ${y.generatorName}: ${Je.dim(y.previousVersion)} \u2192 ${y.newVersion}`)),y.migrationsApplied!=null&&y.migrationsApplied>0&&e.logger.info(Je.dim(` Applied ${y.migrationsApplied} migration(s): ${y.migrationVersions?.join(", ")??""}`));let b=fsS(DU(y.generatorName));b!=null&&e.logger.info(Je.dim(` Changelog: ${b}`))}}}}if(d.length>0){e.logger.info(""),e.logger.info(Je.dim("Generators already on latest version:"));for(let{workspace:s,upToDate:u}of d){let f=new Map;for(let p of u){let h=f.get(p.groupName)??[];h.push(p),f.set(p.groupName,h)}for(let[p,h]of f){let _=s!=null?`[${s}] `:"";e.logger.info(Je.dim(`${_}Group ${p}:`));for(let y of h)e.logger.info(Je.dim(` - ${y.generatorName}: ${y.version} (latest)`))}}}if(c.length===0&&d.length===0){let s=r!=null?` for group ${r}`:t!=null?` for generator ${t}`:"";e.logger.info(""),e.logger.info(Je.gray(`No generators found${s}.`))}if(o.length>0){e.logger.info(""),e.logger.info(Je.yellow("Major version upgrades available:"));for(let s of o){e.logger.info(Je.yellow(` - ${s.generatorName}: ${s.currentVersion} \u2192 ${s.latestMajorVersion}`));let u=t!=null?`fern generator upgrade --generator ${s.generatorName} --include-major`:"fern generator upgrade --include-major";e.logger.info(Je.yellow(` Run: ${u}`));let f=fsS(DU(s.generatorName));f!=null&&e.logger.info(Je.yellow(` Changelog: ${f}`))}}}function _sS(e,t){e.command("organization",!1,r=>r.option("output",{string:!0,alias:"o",description:"The location to output the organization name as a text file, defaults to standard out."}),async r=>{await t.instrumentPostHogEvent({command:"fern organization",properties:{outputLocation:r.output}}),await usS({project:await Em(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),context:t,outputLocation:r.output})})}function ysS(e,t){e.command("generator","Operate on the generators within your Fern configuration",r=>{r.command("list",!1,i=>i.option("output",{string:!0,alias:"o",description:"The location to output the list as a text file, defaults to standard out."}).option("generators",{string:!0,type:"array",description:"The type of generator to include in the list, ex: `fern-typescript-node-sdk`. If omitted, all generators will be listed."}).option("groups",{type:"array",string:!0,description:"The groups to include generators from, if group is not specified, the all generators of the specified type will be listed."}).option("apis",{type:"array",string:!0,description:"The APIs to list the generators for. If not specified, the generator will be upgraded for all APIs."}).option("api-fallback",{string:!0,description:"The APIs to list the generators for. If not specified, the generator will be upgraded for all APIs."}).option("include-mode",{choices:Object.values(PGa),type:"array",description:"The generator output modes to include within the outputted list."}).option("exclude-mode",{choices:Object.values(PGa),type:"array",description:"The generator output modes to exclude within the outputted list."}),async i=>{await t.instrumentPostHogEvent({command:"fern generator list",properties:{outputLocation:i.output}}),await nsS({project:await Em(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),generatorFilter:i.generators?new Set(i.generators):void 0,groupFilter:i.groups?new Set(i.groups):void 0,apiFilter:i.apis?new Set(i.apis):void 0,apiKeyFallback:i.apiFallback,cliContext:t,outputLocation:i.output,includedModes:i["include-mode"]?new Set(i["include-mode"]):void 0,excludedModes:i["exclude-mode"]?new Set(i["exclude-mode"]):void 0})}).command("upgrade",`Upgrades the specified generator in ${GM} to the latest stable version.`,i=>i.option("generator",{string:!0,description:"The type of generator to upgrade, ex: `fern-typescript-node-sdk`."}).option("group",{string:!0,description:"The group in which the generator is located, if group is not specified, the all generators of the specified type will be upgraded."}).option("api",{string:!0,description:"The API to upgrade the generator for. If not specified, the generator will be upgraded for all APIs."}).option("yes",{alias:"y",boolean:!0,default:!1,description:"Automatically answer yes to any prompts that may appear during the upgrade process."}).option("include-major",{boolean:!0,default:!1,description:"Whether or not to include major versions within the upgrade. Defaults to false, meaning major versions will be skipped."}).option("channel",{demandOption:!1,choices:Object.values(psS.FernRegistry.generators.ReleaseType)}).option("list",{demandOption:!1,boolean:!0,default:!1,description:"When specified, a list of available upgrades will be displayed, but no upgrade will be taken."}),async i=>{await t.instrumentPostHogEvent({command:"fern generator upgrade",properties:{generator:i.generator,version:i.version,api:i.api,group:i.group,includeMajor:i.includeMajor,rc:i.rc}});let n=await Em(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0});if(i.list){t.suppressUpgradeMessage();let a=await P_c({cliContext:t,project:n,generatorFilter:i.generator,groupFilter:i.group,includeMajor:i.includeMajor,channel:i.channel}),o=await ENp({generatorUpgradeInfo:a,header:`Generator Upgrades
|
|
2510
2510
|
`,includeBoxen:!0});o!=null&&t.logger.info(o)}else await dsS({cliContext:t,generator:i.generator,group:i.group,project:await Em(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0}),includeMajor:i.includeMajor,channel:i.channel})}).command("get",!1,i=>i.option("output",{string:!0,alias:"o",description:"The location to output the list as a text file, defaults to standard out."}).option("generator",{string:!0,demandOption:!0,description:"The name of the generator to get, ex: `fern-typescript-node-sdk`."}).option("group",{string:!0,demandOption:!0,description:"The group in which the generator is located."}).option("api",{string:!0,description:"The API in which the generator is located."}).option("version",{boolean:!0,default:!1,description:"Get the version of the specified generator."}).option("language",{boolean:!0,default:!1,description:"Get the language of the specified generator."}).option("repository",{boolean:!0,default:!1,description:"Get repository for the generator invocation, if one is specified."}),async i=>{await t.instrumentPostHogEvent({command:"fern generator get",properties:{generator:i.generator,version:i.version,api:i.api,group:i.group,includeMajor:i.includeMajor}});let n=await asS({cliContext:t,generatorFilter:i.generator,groupFilter:i.group,apiFilter:i.api,project:await Em(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0})});if(n==null){let o=i.api?` for API ${i.api}`:"";t.failAndThrow(`Generator ${i.generator}, in group ${i.group}${o} was not found.`)}let a={};if(i.version&&(a.version=n.version,i.output==null)){process.stdout.write(n.version);return}if(i.language)if(n.language!=null){if(a.language=n.language,i.output==null){process.stdout.write(n.language);return}}else t.logger.warn(`Language information is not available for generator ${n.name} in group ${i.group}`);if(i.repository){let o=n.outputMode.type==="github"?n.outputMode.repo:n.outputMode.type==="githubV2"?n.outputMode.githubV2.repo:void 0;if(o!=null){if(a.repository=o,i.output==null){process.stdout.write(a.repository);return}}else t.logger.warn(`Repository information is not available for generator ${n.name} in group ${i.group}`)}if(i.output)try{await(0,hsS.writeFile)(i.output,JSON.stringify(a,null,2))}catch(o){t.failAndThrow(`Could not write file to the specified location: ${i.output}`,o)}})})}var bsS=require("fs/promises");async function vsS({project:{apiWorkspaces:e},generatorName:t,groupName:r,cliContext:i}){await Promise.all(e.map(async n=>{await i.runTaskForWorkspace(n,async a=>{let o=await X_a({absolutePathToWorkspace:n.absoluteFilePath,context:a})??{},c=await tnl({generatorName:t,generatorsConfiguration:o,groupName:r,context:a,cliVersion:i.environment.packageVersion}),d=n.generatorsConfiguration?.absolutePathToConfiguration??await een({absolutePathToWorkspace:n.absoluteFilePath});d!=null&&(await(0,bsS.writeFile)(d,`# yaml-language-server: $schema=https://schema.buildwithfern.dev/generators-yml.json
|
|
2511
|
-
`+Mi.dump(c)),a.logger.info(Je.green(`Added ${t} generator`)))})}))}var OsS=require("fs/promises"),msS=ce(hZ(),1);async function AsS({context:e,from:t,to:r,fromVersion:i,generatorVersions:n}){let a=new sno,o=tQ5(await a.check({from:await gsS({context:e,filepath:t,flagName:"from"}),to:await gsS({context:e,filepath:r,flagName:"to"})})),c=nQ5(e,n),{bump:d,errors:s}=rQ5(o,c);if(i==null)return{bump:d??"patch",errors:s};if(d==="no_change")return{bump:"no_change",nextVersion:i,errors:s};let u=d??"patch",f=msS.default.inc(i,u);if(!f)throw e.failWithoutThrowing(`Invalid current version: ${i}`),new gS;return{bump:u,nextVersion:f,errors:s}}async function gsS({context:e,filepath:t,flagName:r}){let i=vr.of(xo(AO(),t));if(!await ii(i,"file"))throw e.failWithoutThrowing(`File not found: ${i}`),new gS;let n=await(0,OsS.readFile)(i,"utf-8"),a=ca.IntermediateRepresentation.parse(JSON.parse(n));if(!a.ok)throw e.failWithoutThrowing(`Invalid --${r}; expected a filepath containing a valid IR`),new gS;return a.value}function tQ5(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function rQ5(e,t){return{bump:iQ5(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function iQ5(e,t){if(!(e===void 0&&t===void 0))return e==="no_change"&&(t===void 0||t==="no_change")||t==="no_change"&&(e===void 0||e==="no_change")?"no_change":e===void 0?t:t===void 0?e:e==="no_change"?t:t==="no_change"?e:e==="major"||t==="major"?"major":e==="minor"||t==="minor"?"minor":"patch"}function nQ5(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:i}=t;try{let n=aQ5(Tzc(r,i)),a=[];return n==="major"&&a.push("Generator version changed by major version."),{bump:n,errors:a}}catch(n){throw e.failWithoutThrowing(`Error diffing generator versions ${r} and ${i}: ${n}`),new gS}}function aQ5(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}vE();var N_S=ce(CNp(),1),F_S=ce(dyc(),1),Gyc=require("fs/promises"),Q_S=ce(require("http"),1),U_S=ce(require("path"),1);var vpS=require("events"),byc=ce(require("fs"),1),xra=ce(require("path"),1);var epS=ce(require("os"),1),tpS=300,tvn=20,k8o=1e7,rpS=epS.default.platform();var y85=rpS==="darwin",XFp=rpS==="win32",rvn=y85||XFp,ipS=3e3,npS=2e4,ZFp=1250;var n4i;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(n4i||(n4i={}));var Wra;(function(e){e.CHANGE="change",e.RENAME="rename"})(Wra||(Wra={}));var exo;(function(e){e.CHANGE="change",e.ERROR="error"})(exo||(exo={}));var zf;(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"})(zf||(zf={}));var pX;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(pX||(pX={}));var b85=(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(),A=g-d,j=g-s,S=A>=t||j>=a;return[g,S]},f=g=>{if(s=g,!o)return;let A=o;o=void 0,e.apply(void 0,A)},p=()=>{O(0)},h=()=>{c&&(p(),f(Date.now()))},_=g=>{if(s=g,i)return f(g)},y=g=>{if(n&&o)return f(g);o=void 0},b=()=>{c=void 0;let[g,A]=u();return A?y(g):v(g)},v=g=>{let A=g-d,j=g-s,S=t-A,w=a-j,E=Math.min(S,w);return O(E)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},m=(...g)=>{let[A,j]=u(),S=!!c;if(o=g,d=A,(j||!c)&&O(t),j)return S?f(A):_(A)};return m.cancel=p,m.flush=h,m},pyc=b85;var rQp=ce(require("fs"),1),_yc=ce(require("path"),1);var EA=ce(require("fs"),1),Gx=require("util");var gJi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},a4i=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var kFp=ce(require("process"),1),apS=kFp.default.getuid?!kFp.default.getuid():!1,opS=1e4,YOe=()=>{};var txo={isChangeErrorOk:e=>{if(!txo.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!apS&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!txo.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(!txo.isNodeError(e))throw e;if(!txo.isChangeErrorOk(e))throw e}},NT=txo;var eQp=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=opS,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()}}}}},upS=new eQp;var OJi=(e,t)=>function(i){return function n(...a){return upS.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)})}},mJi=(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 v85={attempt:{chmod:gJi((0,Gx.promisify)(EA.default.chmod),NT.onChangeError),chown:gJi((0,Gx.promisify)(EA.default.chown),NT.onChangeError),close:gJi((0,Gx.promisify)(EA.default.close),YOe),fsync:gJi((0,Gx.promisify)(EA.default.fsync),YOe),mkdir:gJi((0,Gx.promisify)(EA.default.mkdir),YOe),realpath:gJi((0,Gx.promisify)(EA.default.realpath),YOe),stat:gJi((0,Gx.promisify)(EA.default.stat),YOe),unlink:gJi((0,Gx.promisify)(EA.default.unlink),YOe),chmodSync:a4i(EA.default.chmodSync,NT.onChangeError),chownSync:a4i(EA.default.chownSync,NT.onChangeError),closeSync:a4i(EA.default.closeSync,YOe),existsSync:a4i(EA.default.existsSync,YOe),fsyncSync:a4i(EA.default.fsync,YOe),mkdirSync:a4i(EA.default.mkdirSync,YOe),realpathSync:a4i(EA.default.realpathSync,YOe),statSync:a4i(EA.default.statSync,YOe),unlinkSync:a4i(EA.default.unlinkSync,YOe)},retry:{close:OJi((0,Gx.promisify)(EA.default.close),NT.isRetriableError),fsync:OJi((0,Gx.promisify)(EA.default.fsync),NT.isRetriableError),open:OJi((0,Gx.promisify)(EA.default.open),NT.isRetriableError),readFile:OJi((0,Gx.promisify)(EA.default.readFile),NT.isRetriableError),rename:OJi((0,Gx.promisify)(EA.default.rename),NT.isRetriableError),stat:OJi((0,Gx.promisify)(EA.default.stat),NT.isRetriableError),write:OJi((0,Gx.promisify)(EA.default.write),NT.isRetriableError),writeFile:OJi((0,Gx.promisify)(EA.default.writeFile),NT.isRetriableError),closeSync:mJi(EA.default.closeSync,NT.isRetriableError),fsyncSync:mJi(EA.default.fsyncSync,NT.isRetriableError),openSync:mJi(EA.default.openSync,NT.isRetriableError),readFileSync:mJi(EA.default.readFileSync,NT.isRetriableError),renameSync:mJi(EA.default.renameSync,NT.isRetriableError),statSync:mJi(EA.default.statSync,NT.isRetriableError),writeSync:mJi(EA.default.writeSync,NT.isRetriableError),writeFileSync:mJi(EA.default.writeFileSync,NT.isRetriableError)}},spS=v85;var hyc=ce(require("fs"),1),rxo=ce(require("path"),1);var tQp=()=>{};var g85=()=>{let e=tQp,t=tQp,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}},cpS=g85;var O85=()=>{let{promise:e,resolve:t,isPending:r}=cpS(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return n(),queueMicrotask(a),{promise:e,isPending:r,increment:n,decrement:a}},lpS=O85;var fpS={then:e=>{e()}};var dpS=e=>Array.isArray(e)?e:[e],ppS=e=>typeof e=="function";var m85=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=dpS(a).map(L=>ppS(L)?L:Q=>L.test(Q)),c=L=>o.some(Q=>Q(L)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],f=new Set,p={},h=[],_=new Set,y={},b=[],v=new Set,O={},m={},g=new Set,A={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:f,directoriesNamesToPaths:p,files:h,filesNames:_,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:m},{promise:S,increment:w,decrement:E}=lpS(),I=0,q=(L,Q,se,ae)=>{g.has(Q)||I>=n||(I+=1,L.directories.push(Q),L.directoriesNames.add(se),u.push(Q),f.add(se),p.propertyIsEnumerable(se)||(p[se]=[]),p[se].push(Q),g.add(Q),!(ae>=i)&&(I>=n||W(Q,ae+1)))},R=(L,Q,se)=>{g.has(Q)||I>=n||(I+=1,L.files.push(Q),L.filesNames.add(se),h.push(Q),_.add(se),y.propertyIsEnumerable(se)||(y[se]=[]),y[se].push(Q),g.add(Q))},T=(L,Q,se,ae)=>{g.has(Q)||I>=n||(I+=1,L.symlinks.push(Q),L.symlinksNames.add(se),b.push(Q),v.add(se),O.propertyIsEnumerable(se)||(O[se]=[]),O[se].push(Q),g.add(Q),r&&(ae>=i||I>=n||Oe(Q,ae+1)))},K=(L,Q,se,ae,de)=>{d.aborted||c(Q)||(ae.isDirectory()?q(L,Q,se,de):ae.isFile()?R(L,Q,se):ae.isSymbolicLink()&&T(L,Q,se,de))},G=(L,Q,se,ae)=>{if(d.aborted)return;let de=Q===rxo.default.sep?"":rxo.default.sep,ge=se.name,re=`${Q}${de}${ge}`;c(re)||(se.isDirectory()?q(L,re,ge,ae):se.isFile()?R(L,re,ge):se.isSymbolicLink()&&T(L,re,ge,ae))},z=(L,Q,se,ae)=>{for(let de=0,ge=se.length;de<ge;de++)G(L,Q,se[de],ae)},W=(L,Q)=>{d.aborted||Q>i||I>=n||(w(),hyc.default.readdir(L,{withFileTypes:!0},(se,ae)=>{if(se||d.aborted||!ae.length)return E();(s(ae)||fpS).then(()=>{let ge=m[L]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(ge,L,ae,Q),E()})}))},Oe=(L,Q)=>{w(),hyc.default.realpath(L,(se,ae)=>{if(se||d.aborted)return E();hyc.default.stat(ae,(de,ge)=>{if(de||d.aborted)return E();let re=rxo.default.basename(ae),X=m[L]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};K(X,ae,re,ge,Q),E()})})};return(async(L,Q=1)=>(L=rxo.default.normalize(L),g.add(L),W(L,Q),await S,d.aborted?A:j))(e)},hpS=m85;var o4i={lang:{debounce:pyc,attempt:e=>{try{return e()}catch(t){return o4i.lang.castError(t)}},castArray:e=>o4i.lang.isArray(e)?e:[e],castError:e=>o4i.lang.isError(e)?e:o4i.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(o4i.lang.isNaN(e))return o4i.lang.isNaN(t);if(o4i.lang.isPrimitive(e)||o4i.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(_yc.default.sep).length-1),getRealPath:(e,t)=>{try{return t?rQp.default.realpathSync.native(e):rQp.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===_yc.default.sep&&t.length-e.length>_yc.default.sep.length,poll:(e,t=npS)=>spS.retry.stat(t)(e,{bigint:!0}).catch(o4i.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 hpS(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},M_=o4i;var yyc=ce(require("path"),1);var iQp=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||M_.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=tpS){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]),f=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(f)},o=M_.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===zf.CHANGE&&c===zf.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===zf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===zf.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??tvn:Math.min(1,this.options.depth??tvn),o=this.options.limit??k8o,[c,d]=await M_.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())M_.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(zf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!rvn&&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(zf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(zf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(yyc.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(zf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(yyc.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(zf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===zf.ADD?this.onTargetAdd(i):r===zf.ADD_DIR?this.onTargetAddDir(i):r===zf.CHANGE?this.onTargetChange(i):r===zf.UNLINK?this.onTargetUnlink(i):r===zf.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=Wra.CHANGE,r){if(this.watcher.isClosed())return;let i=yyc.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){XFp&&t.code==="EPERM"?this.onWatcherChange(Wra.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(exo.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(exo.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Wra.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&rvn&&this.options.native!==!1?this.options.depth??tvn:Math.min(1,this.options.depth??tvn),i=this.options.limit??k8o,[n,a]=await M_.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(Wra.CHANGE,c,t)}))}}},_pS=iQp;var hX={interval:100,intervalId:void 0,fns:new Map,init:()=>{hX.intervalId||(hX.intervalId=setInterval(hX.resolve,hX.interval))},reset:()=>{hX.intervalId&&(clearInterval(hX.intervalId),delete hX.intervalId)},add:(e,t)=>{hX.fns.set(e,Date.now()+t),hX.init()},remove:e=>{hX.fns.delete(e)},resolve:()=>{if(!hX.fns.size)return hX.reset();let e=Date.now();for(let[t,r]of hX.fns)r>=e||(hX.remove(t),t())}},ixo=hX;var nxo=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=ZFp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let f=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(f&&f!==n){if(M_.fs.getRealPath(n,!0)===f)return;this._watcher.event(a.rename,f,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),ixo.remove(s)},s=()=>{d(),c()};ixo.add(s,r);let u=()=>{let f=o.unlink.get(i);if(!f)return;d();let p=f();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=ZFp){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),ixo.remove(s)},s=()=>{d(),c()};ixo.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,zf.ADD,n4i.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,zf.ADD_DIR,n4i.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,zf.UNLINK,n4i.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,zf.UNLINK_DIR,n4i.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}}};nxo.DIR_EVENTS={add:zf.ADD_DIR,rename:zf.RENAME_DIR,unlink:zf.UNLINK_DIR};nxo.FILE_EVENTS={add:zf.ADD,change:zf.CHANGE,rename:zf.RENAME,unlink:zf.UNLINK};var ypS=nxo;var nQp=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(M_.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(M_.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(M_.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(M_.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return M_.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);M_.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},aQp=nQp;var oQp=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}},bpS=oQp;var uQp=class{constructor(){this.inos={},this.paths=new aQp,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 M_.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new bpS(i)}reset(){this.inos={},this.paths=new aQp,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,zf.ADD,n),[zf.ADD];if(n.isDirectory())return this.updateIno(t,zf.ADD_DIR,n),[zf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,zf.UNLINK,i),[zf.UNLINK];if(i.isDirectory())return this.updateIno(t,zf.UNLINK_DIR,i),[zf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,zf.CHANGE,n),[zf.CHANGE]);if(n.isDirectory())return this.updateIno(t,zf.UNLINK,i),this.updateIno(t,zf.ADD_DIR,n),[zf.UNLINK,zf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,zf.UNLINK_DIR,i),this.updateIno(t,zf.ADD,n),[zf.UNLINK_DIR,zf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,zf.UNLINK_DIR,i),this.updateIno(t,zf.ADD_DIR,n),[zf.UNLINK_DIR,zf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?n4i.FILE:n4i.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)}}},sQp=uQp;var cQp=class e extends vpS.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(pX.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(pX.CLOSE,n)),this._readyWait=new Promise(n=>this.on(pX.READY,n)),this._locker=new ypS(this),this._roots=new Set,this._poller=new sQp,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&&(M_.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(pX.CLOSE))}error(t){if(this.isClosed())return!1;let r=M_.lang.castError(t);return this.emit(pX.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(pX.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(pX.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&M_.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&M_.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)M_.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 _pS(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=M_.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=xra.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??tvn))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&rvn&&u.options.native!==!1)))return!0;if(!rvn)break;let s=xra.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=M_.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||rvn&&r.native!==!1?r:{...r,recursive:!1},u={watcher:byc.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},f=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let h={...r,ignoreInitial:!0,recursive:!1},_=xra.default.dirname(c),y=c;await this.watchDirectories([_],h,i,y,f)}}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||rvn&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??tvn,c=r.limit??k8o,[d]=await M_.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=M_.fs.getDepth(t);for(let f of d){let p=M_.fs.getDepth(f),h=Math.max(0,o-(p-u)),_={...r,depth:h};await this.watchDirectories([f],_,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(pX.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(pX.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=xra.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new sQp,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 M_.lang.noop;if(this.pollerExists(t,r))return M_.lang.noop;let n={...r,interval:r.pollingInterval??ipS},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(pX.CLOSE,c),byc.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(pX.CLOSE,c),byc.default.unwatchFile(t,i)};return M_.lang.attempt(o),()=>M_.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=M_.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!M_.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=xra.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await M_.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=xra.default.dirname(t);return(await M_.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=M_.lang.noop){if(M_.lang.isFunction(t))return this.watch([],{},t);if(M_.lang.isUndefined(t))return this.watch([],r,i);if(M_.lang.isFunction(r))return this.watch(t,{},r);if(M_.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=M_.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==M_.lang.noop&&this.on(pX.ALL,i),r.readdirMap=void 0,this.ready())}},vyc=cQp;Zfc();var UGa=require("fs/promises"),gpS=require("os"),OpS=ce(require("path"),1),A85=".fern",P85="logs";function j85(){return"cli@3.64.3"}var axo=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=ut(vr.of((0,gpS.homedir)()),me.of(A85)),r=ut(t,me.of(P85));await ii(r)||await(0,UGa.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ut(r,me.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${OpS.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2511
|
+
`+Mi.dump(c)),a.logger.info(Je.green(`Added ${t} generator`)))})}))}var OsS=require("fs/promises"),msS=ce(hZ(),1);async function AsS({context:e,from:t,to:r,fromVersion:i,generatorVersions:n}){let a=new sno,o=tQ5(await a.check({from:await gsS({context:e,filepath:t,flagName:"from"}),to:await gsS({context:e,filepath:r,flagName:"to"})})),c=nQ5(e,n),{bump:d,errors:s}=rQ5(o,c);if(i==null)return{bump:d??"patch",errors:s};if(d==="no_change")return{bump:"no_change",nextVersion:i,errors:s};let u=d??"patch",f=msS.default.inc(i,u);if(!f)throw e.failWithoutThrowing(`Invalid current version: ${i}`),new gS;return{bump:u,nextVersion:f,errors:s}}async function gsS({context:e,filepath:t,flagName:r}){let i=vr.of(xo(AO(),t));if(!await ii(i,"file"))throw e.failWithoutThrowing(`File not found: ${i}`),new gS;let n=await(0,OsS.readFile)(i,"utf-8"),a=ca.IntermediateRepresentation.parse(JSON.parse(n));if(!a.ok)throw e.failWithoutThrowing(`Invalid --${r}; expected a filepath containing a valid IR`),new gS;return a.value}function tQ5(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function rQ5(e,t){return{bump:iQ5(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function iQ5(e,t){if(!(e===void 0&&t===void 0))return e==="no_change"&&(t===void 0||t==="no_change")||t==="no_change"&&(e===void 0||e==="no_change")?"no_change":e===void 0?t:t===void 0?e:e==="no_change"?t:t==="no_change"?e:e==="major"||t==="major"?"major":e==="minor"||t==="minor"?"minor":"patch"}function nQ5(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:i}=t;try{let n=aQ5(Tzc(r,i)),a=[];return n==="major"&&a.push("Generator version changed by major version."),{bump:n,errors:a}}catch(n){throw e.failWithoutThrowing(`Error diffing generator versions ${r} and ${i}: ${n}`),new gS}}function aQ5(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}vE();var N_S=ce(CNp(),1),F_S=ce(dyc(),1),Gyc=require("fs/promises"),Q_S=ce(require("http"),1),U_S=ce(require("path"),1);var vpS=require("events"),byc=ce(require("fs"),1),xra=ce(require("path"),1);var epS=ce(require("os"),1),tpS=300,tvn=20,k8o=1e7,rpS=epS.default.platform();var y85=rpS==="darwin",XFp=rpS==="win32",rvn=y85||XFp,ipS=3e3,npS=2e4,ZFp=1250;var n4i;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(n4i||(n4i={}));var Wra;(function(e){e.CHANGE="change",e.RENAME="rename"})(Wra||(Wra={}));var exo;(function(e){e.CHANGE="change",e.ERROR="error"})(exo||(exo={}));var zf;(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"})(zf||(zf={}));var pX;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(pX||(pX={}));var b85=(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(),A=g-d,j=g-s,S=A>=t||j>=a;return[g,S]},f=g=>{if(s=g,!o)return;let A=o;o=void 0,e.apply(void 0,A)},p=()=>{O(0)},h=()=>{c&&(p(),f(Date.now()))},_=g=>{if(s=g,i)return f(g)},y=g=>{if(n&&o)return f(g);o=void 0},b=()=>{c=void 0;let[g,A]=u();return A?y(g):v(g)},v=g=>{let A=g-d,j=g-s,S=t-A,w=a-j,E=Math.min(S,w);return O(E)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},m=(...g)=>{let[A,j]=u(),S=!!c;if(o=g,d=A,(j||!c)&&O(t),j)return S?f(A):_(A)};return m.cancel=p,m.flush=h,m},pyc=b85;var rQp=ce(require("fs"),1),_yc=ce(require("path"),1);var EA=ce(require("fs"),1),Gx=require("util");var gJi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},a4i=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var kFp=ce(require("process"),1),apS=kFp.default.getuid?!kFp.default.getuid():!1,opS=1e4,YOe=()=>{};var txo={isChangeErrorOk:e=>{if(!txo.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!apS&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!txo.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(!txo.isNodeError(e))throw e;if(!txo.isChangeErrorOk(e))throw e}},NT=txo;var eQp=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=opS,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()}}}}},upS=new eQp;var OJi=(e,t)=>function(i){return function n(...a){return upS.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)})}},mJi=(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 v85={attempt:{chmod:gJi((0,Gx.promisify)(EA.default.chmod),NT.onChangeError),chown:gJi((0,Gx.promisify)(EA.default.chown),NT.onChangeError),close:gJi((0,Gx.promisify)(EA.default.close),YOe),fsync:gJi((0,Gx.promisify)(EA.default.fsync),YOe),mkdir:gJi((0,Gx.promisify)(EA.default.mkdir),YOe),realpath:gJi((0,Gx.promisify)(EA.default.realpath),YOe),stat:gJi((0,Gx.promisify)(EA.default.stat),YOe),unlink:gJi((0,Gx.promisify)(EA.default.unlink),YOe),chmodSync:a4i(EA.default.chmodSync,NT.onChangeError),chownSync:a4i(EA.default.chownSync,NT.onChangeError),closeSync:a4i(EA.default.closeSync,YOe),existsSync:a4i(EA.default.existsSync,YOe),fsyncSync:a4i(EA.default.fsync,YOe),mkdirSync:a4i(EA.default.mkdirSync,YOe),realpathSync:a4i(EA.default.realpathSync,YOe),statSync:a4i(EA.default.statSync,YOe),unlinkSync:a4i(EA.default.unlinkSync,YOe)},retry:{close:OJi((0,Gx.promisify)(EA.default.close),NT.isRetriableError),fsync:OJi((0,Gx.promisify)(EA.default.fsync),NT.isRetriableError),open:OJi((0,Gx.promisify)(EA.default.open),NT.isRetriableError),readFile:OJi((0,Gx.promisify)(EA.default.readFile),NT.isRetriableError),rename:OJi((0,Gx.promisify)(EA.default.rename),NT.isRetriableError),stat:OJi((0,Gx.promisify)(EA.default.stat),NT.isRetriableError),write:OJi((0,Gx.promisify)(EA.default.write),NT.isRetriableError),writeFile:OJi((0,Gx.promisify)(EA.default.writeFile),NT.isRetriableError),closeSync:mJi(EA.default.closeSync,NT.isRetriableError),fsyncSync:mJi(EA.default.fsyncSync,NT.isRetriableError),openSync:mJi(EA.default.openSync,NT.isRetriableError),readFileSync:mJi(EA.default.readFileSync,NT.isRetriableError),renameSync:mJi(EA.default.renameSync,NT.isRetriableError),statSync:mJi(EA.default.statSync,NT.isRetriableError),writeSync:mJi(EA.default.writeSync,NT.isRetriableError),writeFileSync:mJi(EA.default.writeFileSync,NT.isRetriableError)}},spS=v85;var hyc=ce(require("fs"),1),rxo=ce(require("path"),1);var tQp=()=>{};var g85=()=>{let e=tQp,t=tQp,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}},cpS=g85;var O85=()=>{let{promise:e,resolve:t,isPending:r}=cpS(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return n(),queueMicrotask(a),{promise:e,isPending:r,increment:n,decrement:a}},lpS=O85;var fpS={then:e=>{e()}};var dpS=e=>Array.isArray(e)?e:[e],ppS=e=>typeof e=="function";var m85=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=dpS(a).map(L=>ppS(L)?L:Q=>L.test(Q)),c=L=>o.some(Q=>Q(L)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],f=new Set,p={},h=[],_=new Set,y={},b=[],v=new Set,O={},m={},g=new Set,A={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:f,directoriesNamesToPaths:p,files:h,filesNames:_,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:m},{promise:S,increment:w,decrement:E}=lpS(),I=0,q=(L,Q,se,ae)=>{g.has(Q)||I>=n||(I+=1,L.directories.push(Q),L.directoriesNames.add(se),u.push(Q),f.add(se),p.propertyIsEnumerable(se)||(p[se]=[]),p[se].push(Q),g.add(Q),!(ae>=i)&&(I>=n||W(Q,ae+1)))},R=(L,Q,se)=>{g.has(Q)||I>=n||(I+=1,L.files.push(Q),L.filesNames.add(se),h.push(Q),_.add(se),y.propertyIsEnumerable(se)||(y[se]=[]),y[se].push(Q),g.add(Q))},T=(L,Q,se,ae)=>{g.has(Q)||I>=n||(I+=1,L.symlinks.push(Q),L.symlinksNames.add(se),b.push(Q),v.add(se),O.propertyIsEnumerable(se)||(O[se]=[]),O[se].push(Q),g.add(Q),r&&(ae>=i||I>=n||Oe(Q,ae+1)))},K=(L,Q,se,ae,de)=>{d.aborted||c(Q)||(ae.isDirectory()?q(L,Q,se,de):ae.isFile()?R(L,Q,se):ae.isSymbolicLink()&&T(L,Q,se,de))},G=(L,Q,se,ae)=>{if(d.aborted)return;let de=Q===rxo.default.sep?"":rxo.default.sep,ge=se.name,re=`${Q}${de}${ge}`;c(re)||(se.isDirectory()?q(L,re,ge,ae):se.isFile()?R(L,re,ge):se.isSymbolicLink()&&T(L,re,ge,ae))},z=(L,Q,se,ae)=>{for(let de=0,ge=se.length;de<ge;de++)G(L,Q,se[de],ae)},W=(L,Q)=>{d.aborted||Q>i||I>=n||(w(),hyc.default.readdir(L,{withFileTypes:!0},(se,ae)=>{if(se||d.aborted||!ae.length)return E();(s(ae)||fpS).then(()=>{let ge=m[L]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(ge,L,ae,Q),E()})}))},Oe=(L,Q)=>{w(),hyc.default.realpath(L,(se,ae)=>{if(se||d.aborted)return E();hyc.default.stat(ae,(de,ge)=>{if(de||d.aborted)return E();let re=rxo.default.basename(ae),X=m[L]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};K(X,ae,re,ge,Q),E()})})};return(async(L,Q=1)=>(L=rxo.default.normalize(L),g.add(L),W(L,Q),await S,d.aborted?A:j))(e)},hpS=m85;var o4i={lang:{debounce:pyc,attempt:e=>{try{return e()}catch(t){return o4i.lang.castError(t)}},castArray:e=>o4i.lang.isArray(e)?e:[e],castError:e=>o4i.lang.isError(e)?e:o4i.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(o4i.lang.isNaN(e))return o4i.lang.isNaN(t);if(o4i.lang.isPrimitive(e)||o4i.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(_yc.default.sep).length-1),getRealPath:(e,t)=>{try{return t?rQp.default.realpathSync.native(e):rQp.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===_yc.default.sep&&t.length-e.length>_yc.default.sep.length,poll:(e,t=npS)=>spS.retry.stat(t)(e,{bigint:!0}).catch(o4i.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 hpS(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},M_=o4i;var yyc=ce(require("path"),1);var iQp=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||M_.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=tpS){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]),f=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(f)},o=M_.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===zf.CHANGE&&c===zf.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===zf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===zf.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??tvn:Math.min(1,this.options.depth??tvn),o=this.options.limit??k8o,[c,d]=await M_.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())M_.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(zf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!rvn&&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(zf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(zf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(yyc.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(zf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(yyc.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(zf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===zf.ADD?this.onTargetAdd(i):r===zf.ADD_DIR?this.onTargetAddDir(i):r===zf.CHANGE?this.onTargetChange(i):r===zf.UNLINK?this.onTargetUnlink(i):r===zf.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=Wra.CHANGE,r){if(this.watcher.isClosed())return;let i=yyc.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){XFp&&t.code==="EPERM"?this.onWatcherChange(Wra.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(exo.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(exo.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Wra.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&rvn&&this.options.native!==!1?this.options.depth??tvn:Math.min(1,this.options.depth??tvn),i=this.options.limit??k8o,[n,a]=await M_.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(Wra.CHANGE,c,t)}))}}},_pS=iQp;var hX={interval:100,intervalId:void 0,fns:new Map,init:()=>{hX.intervalId||(hX.intervalId=setInterval(hX.resolve,hX.interval))},reset:()=>{hX.intervalId&&(clearInterval(hX.intervalId),delete hX.intervalId)},add:(e,t)=>{hX.fns.set(e,Date.now()+t),hX.init()},remove:e=>{hX.fns.delete(e)},resolve:()=>{if(!hX.fns.size)return hX.reset();let e=Date.now();for(let[t,r]of hX.fns)r>=e||(hX.remove(t),t())}},ixo=hX;var nxo=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=ZFp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let f=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(f&&f!==n){if(M_.fs.getRealPath(n,!0)===f)return;this._watcher.event(a.rename,f,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),ixo.remove(s)},s=()=>{d(),c()};ixo.add(s,r);let u=()=>{let f=o.unlink.get(i);if(!f)return;d();let p=f();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=ZFp){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),ixo.remove(s)},s=()=>{d(),c()};ixo.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,zf.ADD,n4i.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,zf.ADD_DIR,n4i.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,zf.UNLINK,n4i.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,zf.UNLINK_DIR,n4i.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}}};nxo.DIR_EVENTS={add:zf.ADD_DIR,rename:zf.RENAME_DIR,unlink:zf.UNLINK_DIR};nxo.FILE_EVENTS={add:zf.ADD,change:zf.CHANGE,rename:zf.RENAME,unlink:zf.UNLINK};var ypS=nxo;var nQp=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(M_.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(M_.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(M_.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(M_.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return M_.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);M_.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},aQp=nQp;var oQp=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}},bpS=oQp;var uQp=class{constructor(){this.inos={},this.paths=new aQp,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 M_.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new bpS(i)}reset(){this.inos={},this.paths=new aQp,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,zf.ADD,n),[zf.ADD];if(n.isDirectory())return this.updateIno(t,zf.ADD_DIR,n),[zf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,zf.UNLINK,i),[zf.UNLINK];if(i.isDirectory())return this.updateIno(t,zf.UNLINK_DIR,i),[zf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,zf.CHANGE,n),[zf.CHANGE]);if(n.isDirectory())return this.updateIno(t,zf.UNLINK,i),this.updateIno(t,zf.ADD_DIR,n),[zf.UNLINK,zf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,zf.UNLINK_DIR,i),this.updateIno(t,zf.ADD,n),[zf.UNLINK_DIR,zf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,zf.UNLINK_DIR,i),this.updateIno(t,zf.ADD_DIR,n),[zf.UNLINK_DIR,zf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?n4i.FILE:n4i.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)}}},sQp=uQp;var cQp=class e extends vpS.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(pX.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(pX.CLOSE,n)),this._readyWait=new Promise(n=>this.on(pX.READY,n)),this._locker=new ypS(this),this._roots=new Set,this._poller=new sQp,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&&(M_.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(pX.CLOSE))}error(t){if(this.isClosed())return!1;let r=M_.lang.castError(t);return this.emit(pX.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(pX.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(pX.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&M_.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&M_.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)M_.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 _pS(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=M_.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=xra.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??tvn))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&rvn&&u.options.native!==!1)))return!0;if(!rvn)break;let s=xra.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=M_.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||rvn&&r.native!==!1?r:{...r,recursive:!1},u={watcher:byc.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},f=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let h={...r,ignoreInitial:!0,recursive:!1},_=xra.default.dirname(c),y=c;await this.watchDirectories([_],h,i,y,f)}}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||rvn&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??tvn,c=r.limit??k8o,[d]=await M_.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=M_.fs.getDepth(t);for(let f of d){let p=M_.fs.getDepth(f),h=Math.max(0,o-(p-u)),_={...r,depth:h};await this.watchDirectories([f],_,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(pX.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(pX.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=xra.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new sQp,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 M_.lang.noop;if(this.pollerExists(t,r))return M_.lang.noop;let n={...r,interval:r.pollingInterval??ipS},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(pX.CLOSE,c),byc.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(pX.CLOSE,c),byc.default.unwatchFile(t,i)};return M_.lang.attempt(o),()=>M_.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=M_.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!M_.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=xra.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await M_.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=xra.default.dirname(t);return(await M_.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=M_.lang.noop){if(M_.lang.isFunction(t))return this.watch([],{},t);if(M_.lang.isUndefined(t))return this.watch([],r,i);if(M_.lang.isFunction(r))return this.watch(t,{},r);if(M_.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=M_.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==M_.lang.noop&&this.on(pX.ALL,i),r.readdirMap=void 0,this.ready())}},vyc=cQp;Zfc();var UGa=require("fs/promises"),gpS=require("os"),OpS=ce(require("path"),1),A85=".fern",P85="logs";function j85(){return"cli@3.64.4"}var axo=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=ut(vr.of((0,gpS.homedir)()),me.of(A85)),r=ut(t,me.of(P85));await ii(r)||await(0,UGa.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ut(r,me.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${OpS.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2512
2512
|
`);await(0,UGa.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)+`
|
|
2513
2513
|
`;try{await(0,UGa.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:j85(),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 IQp=ce(vQp(),1),b_S=ce(zPp(),1),XOe=require("fs/promises"),v_S=require("os"),g_S=ce(GQ(),1),O_S=ce(__S(),1),zyc=process.platform==="win32",DQp=Je.cyan("[docs]:"),J85="etag",Y85=23,y_S=e=>e.padEnd(Y85," "),X85="preview",Z85="app-preview",k85="bundle",ex5=".next",tx5="standalone",rx5=".fern",ix5="packages/fern-docs/bundle/.next/server/instrumentation.js",nx5=".npmrc",ax5=".pnpmfile.cjs",ox5="pnpm-workspace.yaml",ux5='Cannot find matching keyid: {"signatures":';function sx5(){return ut(vr.of((0,v_S.homedir)()),me.of(rx5))}function LGa({app:e=!1}){return ut(sx5(),me.of(e?Z85:X85))}function avn({app:e=!1}){return ut(LGa({app:e}),me.of(e?ex5:k85))}function sxo({app:e=!1}){return ut(avn({app:e}),me.of(tx5))}function cx5({app:e=!1}){return ut(sxo({app:e}),me.of(ix5))}function lx5({app:e=!1}){return ut(sxo({app:e}),me.of(ox5))}function fx5({app:e=!1}){return ut(sxo({app:e}),me.of(ax5))}function dx5({app:e=!1}){return ut(sxo({app:e}),me.of(nx5))}function Kra(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function px5({app:e=!1}){return ut(LGa({app:e}),me.of(J85))}var hx5=`module.exports = {
|
|
2514
2514
|
hooks: {
|