fern-api 4.43.3 → 4.43.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.
Files changed (2) hide show
  1. package/cli.cjs +14 -14
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1659,7 +1659,7 @@ ${P8a.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&K4i(th
1659
1659
  `+nke.default.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?nke.default.cyan(L8a(t,this.opt.mask)):nke.default.italic(nke.default.dim("[hidden]")):this.opt.mask?L8a(t,this.opt.mask):nke.default.italic(nke.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 aPr=Ae(fC(),1);var MVa=Ae(T3i(),1),oPr=require("child_process"),ZKe=require("fs"),iPr=Ae(require("path"),1),LVa=Ae(require("os"),1),UVa=require("crypto"),mzi=Ae(QVa(),1);var tPr=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var dDt=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var rPr=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var nPr=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function sPr(e="",t,r){let n=new hzi(e,r);n.runAsync((i,o)=>{if(i)setImmediate(t,i,void 0);else try{n.cleanup(),setImmediate(t,void 0,o)}catch(s){setImmediate(t,s,void 0)}})}function jVa(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function Vrd(e){let t=[],r="";for(let n=0;n<e.length;n++){let i=e.charAt(n);n>0&&i===" "&&e[n-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${i}`}return r.length>0&&t.push(r),t}var hzi=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=Vrd(t).map(i=>i.replace("\\ "," ")),n=r.shift();this.editor={args:r,bin:n}}createTemporaryFile(){try{let t=this.fileOptions.dir??LVa.default.tmpdir(),r=(0,UVa.randomUUID)(),n=jVa(this.fileOptions.prefix),i=jVa(this.fileOptions.postfix),o=`${n}${r}${i}`,s=iPr.default.resolve(t,o),a=iPr.default.resolve(t)+iPr.default.sep;if(!s.startsWith(a))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=s;let u={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(u.mode=this.fileOptions.mode),(0,ZKe.writeFileSync)(this.tempFile,this.text,u)}catch(t){throw new tPr(t)}}readTemporaryFile(){try{let t=(0,ZKe.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,MVa.detect)(t)??"utf8";mzi.default.encodingExists(r)||(r="utf8"),this.text=mzi.default.decode(t,r)}}catch(t){throw new rPr(t)}}removeTemporaryFile(){try{(0,ZKe.unlinkSync)(this.tempFile)}catch(t){throw new nPr(t)}}launchEditor(){try{let t=(0,oPr.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new dDt(t)}}launchEditorAsync(t){try{(0,oPr.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",n=>{this.lastExitStatus=n,setImmediate(t)})}catch(r){throw new dDt(r)}}};var zVa=Ae(lM(),1);var mDt=class extends dC{_run(t){this.done=t,this.editorResult=new zVa.Subject;let r=q1(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let n=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,i=this.handleSubmitEvents(this.editorResult);return i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,n?this.render():this.startExternalEditor(),this}render(t){let r="",n=this.getQuestion();n+=this.status==="answered"?aPr.default.dim("Received"):aPr.default.dim("Press <enter> to launch your preferred editor."),t&&(r=aPr.default.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),sPr(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 $Va=require("stream");var GVa=Ae(require("readline"),1),WVa=Ae(qVa(),1),ake=class{constructor(t){this.rl||=GVa.default.createInterface(Grd(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 Grd(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let i=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw i.isTtyError=!0,i}let r=new WVa.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var hDt=class extends ake{constructor(t={}){super(t),this.log=new $Va.Writable({write:(r,n,i)=>{this.writeLog(r),i()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return XPt(this.rl,this.bottomBar.split(`
1660
1660
  `).length),this}updateBottomBar(t){return XPt(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+`
1661
1661
  `}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&&OTr(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var Kf=Ae(lM(),1),JVa=Ae(OPt(),1);var uPr=Ae(lM(),1),HVa=Ae(OPt(),1),cPr=function(e,t,r){return typeof e[t]!="function"?(0,uPr.of)(e):(0,uPr.from)((0,HVa.default)(e[t])(r).then(n=>(e[t]=n,e)))};var KVa={set:(e,t="",r)=>{let n=e;t.split(".").forEach((i,o,s)=>{i==="__proto__"||i==="constructor"||(o===s.length-1?n[i]=r:(!(i in n)||typeof n[i]!="object")&&(n[i]={}),n=n[i])})},get:(e,t="",r)=>{let n=o=>String.prototype.split.call(t,o).filter(Boolean).reduce((s,a)=>s!=null?s[a]:s,e),i=n(/[,[\]]+?/)||n(/[,.[\]]+?/);return i===void 0||i===e?r:i}},eJe=class extends ake{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let n;return Array.isArray(t)?n=(0,Kf.from)(t):(0,Kf.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,Kf.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,Kf.from)([t]),this.process=n.pipe((0,Kf.concatMap)(this.processQuestion.bind(this)),(0,Kf.publish)()),this.process.connect(),this.process.pipe((0,Kf.reduce)((i,o)=>(KVa.set(i,o.name,o.answer),i),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,Kf.defer)(()=>(0,Kf.of)(t).pipe((0,Kf.concatMap)(this.setDefaultType.bind(this)),(0,Kf.concatMap)(this.filterIfRunnable.bind(this)),(0,Kf.concatMap)(()=>cPr(t,"message",this.answers)),(0,Kf.concatMap)(()=>cPr(t,"default",this.answers)),(0,Kf.concatMap)(()=>cPr(t,"choices",this.answers)),(0,Kf.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,Kf.defer)(()=>(0,Kf.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,Kf.defer)(()=>(0,Kf.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&KVa.get(this.answers,t.name)!==void 0)return Kf.EMPTY;if(t.when===!1)return Kf.EMPTY;if(typeof t.when!="function")return(0,Kf.of)(t);let{answers:r}=this;return(0,Kf.defer)(()=>(0,Kf.from)((0,JVa.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,Kf.filter)(n=>n!=null)))}};function YVa(e){let t=function(r,n){let i;try{i=new eJe(t.prompts,e)}catch(s){return Promise.reject(s)}let o=i.run(r,n);return o.ui=i,o};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",eDt),this.registerPrompt("input",rke),this.registerPrompt("number",tDt),this.registerPrompt("confirm",rDt),this.registerPrompt("rawlist",nDt),this.registerPrompt("expand",iDt),this.registerPrompt("checkbox",oDt),this.registerPrompt("password",sDt),this.registerPrompt("editor",mDt)},t.restoreDefaultPrompts(),t}var Azi=YVa();function $rd(e,t){Azi.registerPrompt(e,t)}function Hrd(){Azi.restoreDefaultPrompts()}var Krd={prompt:Azi,ui:{BottomBar:hDt,Prompt:eJe},createPromptModule:YVa,registerPrompt:$rd,restoreDefaultPrompts:Hrd,Separator:Sk},Dp=Krd;var tJe=require("path");function ZVa(){let e=Jrd();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function Jrd(e=process.argv[1]?(0,tJe.dirname)(process.argv[1]):process.cwd(),t=tJe.sep==="\\"){let r=t?XVa(e):e;return n=>{if(!n)return;let i=t?XVa(n):n,{dir:o,base:s,ext:a}=tJe.posix.parse(i);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let u=decodeURIComponent(s);o||(o=".");let c=o.lastIndexOf("/node_modules");if(c>-1)return`${o.slice(c+14).replace(/\//g,".")}:${u}`;if(o.startsWith(r)){let l=o.slice(r.length+1).replace(/\//g,".");return l?`${l}:${u}`:u}return u}}function XVa(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var yzi=e=>{if("flags"in e){let t=e6a(e.flags),r=t6a(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,bzi(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,Yrd(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function Yrd(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 e6a=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,gDt(r)]).filter(([,t])=>t!==void 0)),t6a=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let n=t[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=t[r].metadata?.payload;return[r,n?bzi(n):void 0]}))};var gDt=e=>e===void 0?void 0:e.variant??e.enabled,bzi=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var lPr="0123456789abcdef",pPr=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,n,i){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(i)||t<0||r<0||n<0||i<0||t>0xffffffffffff||r>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");let o=new Uint8Array(16);return o[0]=t/2**40,o[1]=t/2**32,o[2]=t/2**24,o[3]=t/2**16,o[4]=t/256,o[5]=t,o[6]=112|r>>>8,o[7]=r,o[8]=128|n>>>24,o[9]=n>>>16,o[10]=n>>>8,o[11]=n,o[12]=i>>>24,o[13]=i>>>16,o[14]=i>>>8,o[15]=i,new e(o)}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 n=new Uint8Array(16);for(let i=0;i<16;i+=4){let o=parseInt(r.substring(2*i,2*i+8),16);n[i+0]=o>>>24,n[i+1]=o>>>16,n[i+2]=o>>>8,n[i+3]=o}return new e(n)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=lPr.charAt(this.bytes[r]>>>4),t+=lPr.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+=lPr.charAt(this.bytes[r]>>>4),t+=lPr.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 n=this.bytes[r]-t.bytes[r];if(n!==0)return Math.sign(n)}return 0}},Ezi=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??Xrd()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let n=this.generateOrAbortCore(t,r);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(t,r)),n}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else{if(!(t+r>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return pPr.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,pPr.ofInner(t)}},Xrd=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),r6a,xX=()=>Zrd().toString(),Zrd=()=>(r6a||(r6a=new Ezi)).generate();var Ok=(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 end=["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"],n6a=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return end.concat(t).some(n=>{let i=n.toLowerCase();return r.indexOf(i)!==-1})};var rnd=Array.isArray,i6a=Object.prototype,OVb=i6a.hasOwnProperty,vzi=i6a.toString,Izi=rnd||function(e){return vzi.call(e)==="[object Array]"};var wzi=e=>e===Object(e)&&!Izi(e);var rJe=e=>e===void 0,ADt=e=>vzi.call(e)=="[object String]",o6a=e=>ADt(e)&&e.trim().length===0;var s6a=e=>vzi.call(e)=="[object Number]"&&e===e;var Czi=e=>e instanceof Error;function yDt(e){return e===null||typeof e!="object"}function uke(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function a6a(e){return uke(e,"ErrorEvent")}function fPr(e){return!rJe(Event)&&nnd(e,Event)}function u6a(e){return uke(e,"Object")}function nnd(e,t){try{return e instanceof t}catch{return!1}}function bDt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),s6a(e)?e>r?(n.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(n.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+i),bDt(i||r,t,r,n))}var ind=864e5,dPr=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=bDt(t.bucketSize,0,100,t._logger),this._refillRate=bDt(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=bDt(t.refillInterval,0,ind,t._logger)}_applyRefill(t,r){let n=r-t.lastAccess,i=Math.floor(n/this._refillInterval);if(i>0){let o=i*this._refillRate;t.tokens=Math.min(t.tokens+o,this._bucketSize),t.lastAccess=t.lastAccess+i*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),n=String(t),i=this._buckets[n];return i?this._applyRefill(i,r):(i={tokens:this._bucketSize,lastAccess:r},this._buckets[n]=i),i.tokens===0?!0:(i.tokens--,i.tokens===0&&this._onBucketRateLimited?.(t),i.tokens===0)}stop(){this._buckets={}}};var mPr=class{add(t){let r=xX();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 ond(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var c6a=(e,t,r)=>{function n(o,...s){t(()=>{let a=r[o];a(e,...s)})}return{info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{r.error(e,...o)},createLogger:o=>c6a(`${e} ${o}`,t,r)}},snd=e=>e();function l6a(e,t=snd){return c6a(e,t,ond())}var iJe="Mobile",gPr="iOS",nJe="Android",p6a="Tablet",UVb=nJe+" "+p6a;var and="Apple",zVb=and+" Watch",f6a="Safari",APr="BlackBerry",d6a="Samsung",und=d6a+"Browser",cnd=d6a+" Internet",yPr="Chrome",lnd=yPr+" OS",pnd=yPr+" "+gPr,m6a="Internet Explorer",fnd=m6a+" "+iJe,_zi="Opera",VVb=_zi+" Mini",h6a="Edge",dnd="Microsoft "+h6a,Szi="Firefox",mnd=Szi+" "+gPr,Bzi="Nintendo",Ozi="PlayStation",hPr="Xbox",hnd=nJe+" "+iJe,gnd=iJe+" "+f6a,EDt="Windows",And=EDt+" Phone";var g6a="Generic",qVb=g6a+" "+iJe.toLowerCase(),GVb=g6a+" "+p6a.toLowerCase(),ynd="Konqueror",OD="(\\d+(\\.\\d+)?)",xzi=new RegExp("Version/"+OD),WVb=new RegExp(hPr,"i"),$Vb=new RegExp(Ozi+" \\w+","i"),HVb=new RegExp(Bzi+" \\w+","i"),bnd=new RegExp(APr+"|PlayBook|BB10","i"),End={"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 KVb={[fnd]:[new RegExp("rv:"+OD)],[dnd]:[new RegExp(h6a+"?\\/"+OD)],[yPr]:[new RegExp("("+yPr+"|CrMo)\\/"+OD)],[pnd]:[new RegExp("CriOS\\/"+OD)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+OD)],[f6a]:[xzi],[gnd]:[xzi],[_zi]:[new RegExp("("+_zi+"|OPR)\\/"+OD)],[Szi]:[new RegExp(Szi+"\\/"+OD)],[mnd]:[new RegExp("FxiOS\\/"+OD)],[ynd]:[new RegExp("Konqueror[:/]?"+OD,"i")],[APr]:[new RegExp(APr+" "+OD),xzi],[hnd]:[new RegExp("android\\s"+OD,"i")],[cnd]:[new RegExp(und+"\\/"+OD)],[m6a]:[new RegExp("(rv:|MSIE )"+OD)],Mozilla:[new RegExp("rv:"+OD)]};var JVb=[[new RegExp(hPr+"; "+hPr+" (.*?)[);]","i"),e=>[hPr,e&&e[1]||""]],[new RegExp(Bzi,"i"),[Bzi,""]],[new RegExp(Ozi,"i"),[Ozi,""]],[bnd,[APr,""]],[new RegExp(EDt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[And,""];if(new RegExp(iJe).test(t)&&!/IEMobile\b/.test(t))return[EDt+" "+iJe,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=End[n]||"";return/arm/i.test(t)&&(i="RT"),[EDt,i]}return[EDt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[gPr,t.join(".")]}return[gPr,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=rJe(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+nJe+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+nJe+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[nJe,t.join(".")]}return[nJe,""]}],[/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/,[lnd,""]],[/Linux|debian/i,["Linux",""]]];var A6a="utf8";function y6a(e,t){if(!e||typeof e!="string"||vnd(e))throw new Error(t)}function vnd(e){return e.trim().length===0}function b6a(e){return e?.replace(/\/+$/,"")}async function E6a(e,t){let r=null;for(let n=0;n<t.retryCount+1;n++){n>0&&await new Promise(i=>setTimeout(i,t.retryDelay));try{return await e()}catch(i){if(r=i,!t.retryCheck(i))throw i}}throw r}function bPr(){return new Date().toISOString()}function cke(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var v6a=e=>e instanceof Error;function Tzi(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var EPr=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(n=>n!==r)}}emit(t,r){for(let n of this.events[t]||[])n(r);for(let n of this.events["*"]||[])n(t,r)}};function I6a(){return"CompressionStream"in globalThis}async function Pzi(e,t=!0){try{let n=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(n).blob()}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var lke=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()}},oJe=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function w6a(e){if(e instanceof lke){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 Dzi(e){return typeof e=="object"&&(e instanceof lke||e instanceof oJe)}function C6a(e){return typeof e=="object"&&e instanceof lke&&e.status===413}var vDt=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new mPr,this._events=new EPr,this._isInitialized=!1,y6a(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=b6a(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:Dzi},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=l6a("[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=!I6a()||(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(Ok.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Ok.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Ok.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>this._logger.info(n,i));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",o,i)})}async captureStatelessImmediate(t,r,n,i){let o=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",o,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",o,i)})}async aliasStatelessImmediate(t,r,n,i){let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",o,i)}groupIdentifyStateless(t,r,n,i,o,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});this.enqueue("capture",a,i)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(i=>i.json()).catch(i=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(t,r={},n={},i={},o={},s=!0){await this._initPromise;let a=s?"&config=true":"",u=`${this.host}/flags/?v=2${a}`,c={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};this.evaluationContexts&&this.evaluationContexts.length>0&&(c.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(c)};return this._logger.info("Flags URL",u),this.fetchWithRetry(u,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(p=>p.json()).then(p=>({success:!0,response:yzi(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(t){if(t instanceof lke)return{type:"api_error",statusCode:t.status};if(t instanceof oJe){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,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(t,r,n,i,o,s);if(a===void 0)return{response:void 0,requestId:void 0};let u=gDt(a.response);return u===void 0&&(u=!1),{response:u,requestId:a.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(r,n,i,o,s,[t]);return a===void 0?void 0:{response:a.flags[t],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(r,n,i,o,s,[t]);if(!a)return;let u=a[t];return u===void 0?null:u}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},o,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},o,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,n,i,o,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a={};(o??this.disableGeoip)&&(a.geoip_disable=!0),s&&(a.flag_keys_to_evaluate=s);let u=await this.getFlags(t,r,n,i,a);if(!u.success)return;let c=u.response;return c.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"),c.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:c?.requestId,quotaLimited:c.quotaLimited}):c}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"}},i=(await this.fetchWithRetry(t,r).then(o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);this._logger.error(a),this._events.emit("error",new Error(s));return}return o.json()}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(Ok.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(Ok.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(Ok.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}enqueue(t,r,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o=this.getPersistedProperty(Ok.Queue)||[];o.length>=this.maxQueueSize&&(o.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),o.push({message:i}),this.setPersistedProperty(Ok.Queue,o),this._events.emit(t,i),o.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=cke(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n){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 i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o={api_key:this.apiKey,batch:[i],sent_at:bPr()};this.historicalMigration&&(o.historical_migration=!0);let s=JSON.stringify(o),a=`${this.host}/batch/`,u=this.disableCompression?null:await Pzi(s,this.isDebug),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||s};try{await this.fetchWithRetry(a,c)}catch(l){this._events.emit("error",l)}}prepareMessage(t,r,n){let i={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:bPr(),uuid:n?.uuid?n.uuid:xX()};return(n?.disableGeoip??this.disableGeoip)&&(i.properties||(i.properties={}),i.properties.$geoip_disable=!0),i.distinctId&&(i.distinct_id=i.distinctId,delete i.distinctId),i}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await w6a(t)})}async flush(){let t=Tzi([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),Tzi([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(Ok.Queue)||[];if(!t.length)return;let r=[],n=t.length;for(;t.length>0&&r.length<n;){let i=t.slice(0,this.maxBatchSize),o=i.map(f=>f.message),s=async()=>{let m=(this.getPersistedProperty(Ok.Queue)||[]).slice(i.length);this.setPersistedProperty(Ok.Queue,m),t=m,await this.flushStorage()},a={api_key:this.apiKey,batch:o,sent_at:bPr()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),c=`${this.host}/batch/`,l=this.disableCompression?null:await Pzi(u,this.isDebug),p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...l!==null&&{"Content-Encoding":"gzip"}},body:l||u},d={retryCheck:f=>C6a(f)?!1:Dzi(f)};try{await this.fetchWithRetry(c,p,d)}catch(f){if(C6a(f)&&o.length>1){this.maxBatchSize=Math.max(1,Math.floor(o.length/2)),this._logger.warn(`Received 413 when sending batch of size ${o.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw f instanceof oJe||await s(),this._events.emit("error",f),f}await s(),r.push(...o)}this._events.emit("flush",r)}async fetchWithRetry(t,r,n,i){AbortSignal.timeout??=function(a){let u=new AbortController;return setTimeout(()=>u.abort(),a),u.signal};let o=r.body?r.body:"",s=-1;try{s=o instanceof Blob?o.size:Buffer.byteLength(o,A6a)}catch{o instanceof Blob?s=o.size:s=new TextEncoder().encode(o).length}return await E6a(async()=>{let a=null;try{a=await this.fetch(t,{signal:AbortSignal.timeout(i??this.requestTimeout),...r})}catch(c){throw new oJe(c)}if(!(r.mode==="no-cors")&&(a.status<200||a.status>=400))throw new lke(a,s);return a},{...this._retryOptions,...n})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let n=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(Ok.Queue)||[]).length===0||(await this.flush(),r)););}catch(i){if(!Dzi(i))throw i;await w6a(i)}};return Promise.race([new Promise((i,o)=>{cke(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,o("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),n()])}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 Tk={};Z(Tk,{DOMExceptionCoercer:()=>kzi,ErrorCoercer:()=>Qzi,ErrorEventCoercer:()=>jzi,ErrorPropertiesBuilder:()=>Rzi,EventCoercer:()=>Uzi,ObjectCoercer:()=>Lzi,PrimitiveCoercer:()=>zzi,PromiseRejectionEventCoercer:()=>Vzi,ReduceableCache:()=>qzi,StringCoercer:()=>Mzi,chromeStackLineParser:()=>Fzi,createDefaultStackParser:()=>knd,createStackParser:()=>N6a,geckoStackLineParser:()=>Nzi,nodeStackLineParser:()=>P6a,opera10StackLineParser:()=>B6a,opera11StackLineParser:()=>O6a,reverseAndStripFrames:()=>F6a,winjsStackLineParser:()=>S6a});var vPr,x6a,IPr;function _6a(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return IPr&&r.length===x6a||(x6a=r.length,IPr=r.reduce((n,i)=>{vPr||(vPr={});let o=vPr[i];if(o)n[o[0]]=o[1];else{let s=e(i);for(let a=s.length-1;a>=0;a--){let c=s[a]?.filename,l=t[i];if(c&&l){n[c]=l,vPr[i]=[c,l];break}}}return n},{})),IPr}var wnd=4,Rzi=class{constructor(t,r,n=[]){this.coercers=t,this.stackParser=r,this.modifiers=n}buildFromUnknown(t,r={}){let i=r&&r.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,r,0).apply(t),a=this.buildParsingContext(r),u=this.parseStacktrace(s,a);return{$exception_list:this.convertToExceptionList(u,i),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&Izi(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 n;t.cause!=null&&(n=this.parseStacktrace(t.cause,r));let i;return t.stack!=""&&t.stack!=null&&(i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?r.skipFirstLines:0),r.chunkIdMap)),{...t,cause:n,stack:i}}applyChunkIds(t,r){return t.map(n=>(n.filename&&r&&(n.chunk_id=r[n.filename]),n))}applyCoercers(t,r){for(let n of this.coercers)if(n.match(t))return n.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let n of this.modifiers)r=await n(r);return r}convertToExceptionList(t,r){let n={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(n.stacktrace={type:"raw",frames:t.stack});let i=[n];return t.cause!=null&&i.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),i}buildParsingContext(t){return{chunkIdMap:_6a(this.stackParser),skipFirstLines:t.skipFirstLines??1}}buildCoercingContext(t,r,n=0){let i=(s,a)=>{if(a<=wnd){let u=this.buildCoercingContext(t,r,a);return this.applyCoercers(s,u)}};return{...r,syntheticException:n==0?r.syntheticException:void 0,mechanism:t,apply:s=>i(s,n),next:s=>i(s,n+1)}}};var W1="?";function _X(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?W1:r,in_app:!0};return rJe(n)||(o.lineno=n),rJe(i)||(o.colno=i),o}var wPr=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return r||n?[e.indexOf("@")!==-1?e.split("@")[0]:W1,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var Cnd=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,xnd=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,_nd=/\((\S*)(?::(\d+))(?::(\d+))\)/,Fzi=(e,t)=>{let r=Cnd.exec(e);if(r){let[,i,o,s]=r;return _X(t,i,W1,+o,+s)}let n=xnd.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=_nd.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=wPr(n[1]||W1,n[2]);return _X(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var Snd=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Bnd=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Nzi=(e,t)=>{let r=Snd.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=Bnd.exec(r[3]);s&&(r[1]=r[1]||"eval",r[3]=s[1],r[4]=s[2],r[5]="")}let i=r[3],o=r[1]||W1;return[o,i]=wPr(o,i),_X(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var Ond=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,S6a=(e,t)=>{let r=Ond.exec(e);return r?_X(t,r[2],r[1]||W1,+r[3],r[4]?+r[4]:void 0):void 0};var Tnd=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,B6a=(e,t)=>{let r=Tnd.exec(e);return r?_X(t,r[2],r[3]||W1,+r[1]):void 0},Pnd=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,O6a=(e,t)=>{let r=Pnd.exec(e);return r?_X(t,r[5],r[3]||r[4]||W1,+r[1],+r[2]):void 0};var Dnd=/^\s*[-]{4,}$/,Rnd=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,P6a=(e,t)=>{let r=e.match(Rnd);if(r){let n,i,o,s,a;if(r[1]){o=r[1];let l=o.lastIndexOf(".");if(o[l-1]==="."&&l--,l>0){n=o.slice(0,l),i=o.slice(l+1);let p=n.indexOf(".Module");p>0&&(o=o.slice(p+1),n=n.slice(0,p))}s=void 0}i&&(s=n,a=i),i==="<anonymous>"&&(a=void 0,o=void 0),o===void 0&&(a=a||W1,o=s?`${s}.${a}`:a);let u=r[2]?.startsWith("file://")?r[2].slice(7):r[2],c=r[5]==="native";return u?.match(/\/[A-Z]:/)&&(u=u.slice(1)),!u&&r[5]&&!c&&(u=r[5]),{filename:u?decodeURI(u):void 0,module:void 0,function:o,lineno:T6a(r[3]),colno:T6a(r[4]),in_app:Fnd(u||"",c),platform:t}}if(e.match(Dnd))return{filename:e,platform:t}};function Fnd(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 T6a(e){return parseInt(e||"",10)||void 0}var D6a=/\(error: (.*)\)/,R6a=50;function F6a(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,R6a).map(r=>({...r,filename:r.filename||Nnd(t).filename,function:r.function||W1}))}function Nnd(e){return e[e.length-1]||{}}function knd(){return N6a("web:javascript",Fzi,Nzi)}function N6a(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
1662
- `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let u=D6a.test(a)?a.replace(D6a,"$1"):a;if(!u.match(/\S*Error: /)){for(let c of t){let l=c(u,e);if(l){i.push(l);break}}if(i.length>=R6a)break}}return F6a(i)}}var kzi=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=ADt(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:n?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 uke(t,"DOMException")}isDOMError(t){return uke(t,"DOMError")}};var Qzi=class{match(t){return Czi(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 n=t.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(t){return t.stacktrace||t.stack||void 0}};var jzi=class{constructor(){}match(t){return a6a(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var Qnd=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Mzi=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match(Qnd);return i&&(r=i[1],n=i[2]),[r,n]}};var k6a=["fatal","error","warning","log","info","debug"];function CPr(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var Lzi=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{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 fPr(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=CPr(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return ADt(t)&&!o6a(t)&&k6a.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(v6a(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var Uzi=class{match(t){return fPr(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${CPr(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var zzi=class{match(t){return yDt(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Vzi=class{match(t){return uke(t,"PromiseRejectionEvent")}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return yDt(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){if(yDt(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 qzi=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 M6a=require("fs"),L6a=require("readline"),xPr=new Tk.ReduceableCache(25),U6a=new Tk.ReduceableCache(20),Gzi=7,jnd=1e3,Mnd=1e4;async function z6a(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||Vnd(s)||qnd(o))continue;t[s]||(t[s]=[]),t[s].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(U6a.get(i))continue;let o=t[i];if(!o)continue;o.sort((u,c)=>u-c);let s=Wnd(o);if(s.every(u=>Gnd(i,u)))continue;let a=$nd(xPr,i,{});n.push(Lnd(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&Und(e,xPr),xPr.reduce(),e}function Lnd(e,t,r){return new Promise(n=>{let i=(0,M6a.createReadStream)(e),o=(0,L6a.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,u=0,c=t[u];if(c===void 0)return void s();let l=c[0],p=c[1];function d(){U6a.set(e,1),o.close(),o.removeAllListeners(),s()}i.on("error",d),o.on("error",d),o.on("close",s),o.on("line",f=>{if(a++,!(a<l)&&(r[a]=Hnd(f,0),a>=p)){if(u===t.length-1){o.close(),o.removeAllListeners();return}u++;let m=t[u];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function Und(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;znd(r.lineno,r,n)}}function znd(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=V6a(e);i<e;i++){let o=r[i];if(o===void 0)return void Q6a(t);t.pre_context.push(o)}if(r[e]===void 0)return void Q6a(t);t.context_line=r[e];let n=q6a(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function Q6a(e){delete e.pre_context,delete e.context_line,delete e.post_context}function Vnd(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function qnd(e){return e.lineno!==void 0&&e.lineno>Mnd||e.colno!==void 0&&e.colno>jnd}function Gnd(e,t){let r=xPr.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function Wnd(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=j6a(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+Gzi:(i.push(n),n=j6a(o)),t++}return i}function j6a(e){return[V6a(e),q6a(e)]}function V6a(e){return Math.max(1,e-Gzi)}function q6a(e){return e+Gzi}function $nd(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function Hnd(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}function Knd(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function G6a(e,t){globalThis.process?.on("uncaughtException",Knd(e,t))}function W6a(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var Jnd=2e3,a9=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new dPr({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return wzi(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i};n||(o.$process_person_profile=!1);let s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n||xX(),properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(G6a(this.onException.bind(this),this.onFatalError.bind(this)),W6a(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(Jnd),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var $6a="5.26.2";var IDt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function H6a(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(i=>i.toString(16).padStart(2,"0")).join("")}var Ynd=6e4,Xnd=1152921504606847e3,Znd=["is_not"],sJe=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Vh=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},SX=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},_Pr=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let u=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,u)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(c){c instanceof SX||c instanceof Vh?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${t}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${c}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(u=>this.featureFlagsByKey[u]).filter(Boolean):this.featureFlags,a={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async u=>{try{let{value:c,payload:l}=await this.computeFlagAndPayloadLocally(u,a);n[u.key]=c,l&&(i[u.key]=l)}catch(c){c instanceof SX||c instanceof Vh?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${u.key}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${u.key}: ${c}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(t.ensure_experience_continuity)throw new Vh("Flag has experience continuity enabled");if(!t.active)return!1;let u=(t.filters||{}).aggregation_group_type_index;if(u!=null){let c=this.groupTypeMapping[String(u)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${u} for feature flag ${t.key}`)),new Vh("Flag has unknown group type index");if(!(c in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let l=s[c];return await this.matchFeatureFlagProperties(t,i[c],l,r)}{let c=this.getBucketingValueForFlag(t,n,o);if(c===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new Vh(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,c,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new Vh("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Vh(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Vh(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Vh(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let u of s){if(!(u in i)){let l=this.featureFlagsByKey[u];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[u]=p}catch(p){throw new Vh(`Error evaluating flag dependency '${u}' for flag '${o}': ${p}`)}else i[u]=!1;else throw new Vh(`Missing flag dependency '${u}' for flag '${o}'`)}if(i[u]==null)throw new Vh(`Dependency '${u}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}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,n,i){let o=t.filters||{},s=o.groups||[],a=!1,u;for(let c of s)try{if(await this.isConditionMatch(t,r,c,n,i)){let l=c.variant,p=o.multivariate?.variants||[];u=l&&p.some(d=>d.key===l)?l:await this.getMatchingVariant(t,r)||!0;break}}catch(l){if(l instanceof SX)throw l;if(l instanceof Vh)a=!0;else throw l}if(u!==void 0)return u;if(a)throw new Vh("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let c=u.type,l=!1;if(l=c==="cohort"?Z6a(u,i,this.cohorts,this.debugMode):c==="flag"?await this.evaluateFlagDependency(u,i,o):X6a(u,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await K6a(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await K6a(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(a=>{i=n+a.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:a.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.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(n=>n.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}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(Ynd,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(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}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 sJe(`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 sJe(`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 sJe(`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 n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof sJe&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=cke(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}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((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function K6a(e,t,r=""){let n=await H6a(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/Xnd}function X6a(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")throw new Vh("Operator is_not_set is not supported")}else throw new Vh(`Property ${n} not found in propertyValues`);let s=t[n];if(s==null&&!Znd.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(c,l){return Array.isArray(c)?c.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(c).toLowerCase()===String(l).toLowerCase()}function u(c,l,p){if(p==="gt")return c>l;if(p==="gte")return c>=l;if(p==="lt")return c<l;if(p==="lte")return c<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return J6a(String(i))&&String(s).match(String(i))!==null;case"not_regex":return J6a(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let c=typeof i=="number"?i:null;if(typeof i=="string")try{c=parseFloat(i)}catch{}return c==null||s==null?u(String(s),String(i),o):typeof s=="string"?u(s,String(i),o):u(s,c,o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Vh("Date operations cannot be performed on boolean values");let c=tid(String(i));if(c==null&&(c=Y6a(i)),c==null)throw new Vh(`Invalid date: ${i}`);let l=Y6a(s);return["is_date_before"].includes(o)?l<c:l>c}default:throw new Vh(`Unknown operator: ${o}`)}}function eid(e,t){if(!(e in t))throw new SX(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function Z6a(e,t,r,n=!1){let i=String(e.value);eid(i,r);let o=r[i];return eqa(o,t,r,n)}function eqa(e,t,r,n=!1){if(!e)return!0;let i=e.type,o=e.values;if(!o||o.length===0)return!0;let s=!1;if("values"in o[0]){for(let a of o)try{let u=eqa(a,t,r,n);if(i==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof SX)throw u;if(u instanceof Vh)n&&console.debug(`Failed to compute property ${a} locally: ${u}`),s=!0;else throw u}if(s)throw new Vh("Can't match cohort without a given cohort property value");return i==="AND"}for(let a of o)try{let u;if(a.type==="cohort")u=Z6a(a,t,r,n);else if(a.type==="flag"){n&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${a.key||"unknown"}'`);continue}else u=X6a(a,t);let c=a.negation||!1;if(i==="AND"){if(!u&&!c||u&&c)return!1}else if(u&&!c||!u&&c)return!0}catch(u){if(u instanceof SX)throw u;if(u instanceof Vh)n&&console.debug(`Failed to compute property ${a} locally: ${u}`),s=!0;else throw u}if(s)throw new Vh("can't match cohort without a given cohort property value");return i==="AND"}function J6a(e){try{return new RegExp(e),!0}catch{return!1}}function Y6a(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 Vh(`${e} is in an invalid date format`)}throw new Vh(`The date provided ${e} must be a string, number, or date object`)}function tid(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-i);else if(o=="d")n.setUTCDate(n.getUTCDate()-i);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}}var SPr=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var rid=100,tqa=3e4,nid=5e4,BPr=class extends vDt{constructor(t,r={}){if(super(t,r),this._memoryStorage=new SPr,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,rid):tqa,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 _Pr({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new a9(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||nid}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 $6a}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."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.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."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStateless(t,l,{disableGeoip:n})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStatelessImmediate(t,l,{disableGeoip:n})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=tqa){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let w=this._flagOverrides[t];if(w===void 0)return;let x=this._payloadOverrides?.[t];return{key:t,enabled:w!==!1,variant:typeof w=="string"?w:void 0,payload:x}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,c,l);u==null&&(u=this.options.strictLocalEvaluation??!1);let f,m=!1,h,g,A,b,v,E;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let w=this.featureFlagsPoller?.featureFlagsByKey[t];if(w)try{let x=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(w,d,{matchValue:i});if(x){m=!0;let C=x.value;b=w.id,E="Evaluated locally",f={key:t,enabled:C!==!1,variant:typeof C=="string"?C:void 0,payload:x.payload??void 0}}}catch(x){if(x instanceof SX||x instanceof Vh)this._logger?.info(`${x.name} when computing flag locally: ${t}: ${x.message}`);else throw x}}if(!m&&!u){let w=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(w===void 0)A=IDt.UNKNOWN_ERROR;else{h=w.requestId,g=w.evaluatedAt;let x=[];w.errorsWhileComputingFlags&&x.push(IDt.ERRORS_WHILE_COMPUTING),w.quotaLimited?.includes("feature_flags")&&x.push(IDt.QUOTA_LIMITED);let C=w.flags[t];if(C===void 0)x.push(IDt.FLAG_MISSING);else{b=C.metadata?.id,v=C.metadata?.version,E=C.reason?.description??C.reason?.code;let _;if(C.metadata?.payload!==void 0)try{_=JSON.parse(C.metadata.payload)}catch{_=C.metadata.payload}f={key:t,enabled:C.enabled,variant:C.variant,payload:_}}x.length>0&&(A=x.join(","))}}if(o){let w=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,x=`${t}_${w}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(x)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(x):this.distinctIdHasSentFlagCalls[r]=[x];let C={$feature_flag:t,$feature_flag_response:w,$feature_flag_id:b,$feature_flag_version:v,$feature_flag_reason:E,locally_evaluated:m,[`$feature/${t}`]:w,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():g};if(m&&this.featureFlagsPoller){let _=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();_!==void 0&&(C.$feature_flag_definitions_loaded_at=_)}A&&(C.$feature_flag_error=A),this.capture({distinctId:r,event:"$feature_flag_called",properties:C,groups:s,disableGeoip:a})}}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}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 n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){let i=await this.getFeatureFlag(t,r,n);if(i!==void 0)return!!i||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,c,l);u==null&&(u=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},h={},g=!0;if(f&&(m=f.response,h=f.payloads,g=f.fallbackToFlags),g&&!u){let A=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);m={...m,...A.flags||{}},h={...h,...A.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(h={...h,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:h}}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!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 n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}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)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=cke(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,s]of Object.entries(t))if(u6a(s)&&r&&o in r){let a={};for(let[u,c]of Object.entries(s))a[String(u)]=String(c);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,p]of Object.entries(r||{}))c[l]=String(p);return await this.getAllFlags(t,{groups:c,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,p]of Object.entries(r||{}))c[l]=String(p);return await this.getAllFlags(t,{groups:c,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i){if(!a9.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");this.addPendingPromise(a9.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.capture({...s,uuid:i})))}}async captureExceptionImmediate(t,r,n){if(!a9.isPreviouslyCapturedError(t)){let i=new Error("PostHog syntheticException");this.addPendingPromise(a9.buildEventMessage(t,{syntheticException:i},r,n).then(o=>this.captureImmediate(o)))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:u,uuid:c}=t,l=this.context?.get(),p=r||l?.distinctId,d={...this.props,...l?.properties||{},...i||{}};p||(p=xX(),d.$process_person_profile=!1),l?.sessionId&&!d.$session_id&&(d.$session_id=l.sessionId);let f=this._runBeforeSend({distinctId:p,event:n,properties:d,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:u,uuid:c});if(!f)return Promise.reject(null);let m=await Promise.resolve().then(async()=>{if(s){let h=typeof s=="object"?s:void 0;return await this.getFeatureFlagsForEvent(f.distinctId,o,u,h)}return f.event,{}}).then(h=>{let g={};if(h)for(let[b,v]of Object.entries(h))g[`$feature/${b}`]=v;let A=Object.keys(h||{}).filter(b=>h?.[b]!==!1).sort();return A.length>0&&(g.$active_feature_flags=A),g}).catch(()=>({})).then(h=>({...h,...f.properties||{},$groups:f.groups||o}));return f.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof m.$raw_user_agent=="string"&&n6a(m.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(f.event="$bot_pageview",m.$browser_type="bot"),{distinctId:f.distinctId,event:f.event,properties:m,options:{timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n){if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}};var rqa=require("async_hooks"),OPr=class{constructor(){this.storage=new rqa.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){return this.storage.run(this.resolve(t,n),r)}enter(t,r){this.storage.enterWith(this.resolve(t,r))}resolve(t,r){if(r?.fresh===!0)return t;let n=this.get()||{};return{distinctId:t.distinctId??n.distinctId,sessionId:t.sessionId??n.sessionId,properties:{...n.properties||{},...t.properties||{}}}}};var nqa="posthog-node";function iid(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let u=s.tags[Wzi.POSTHOG_ID_TAG];if(u===void 0)return s;let c=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${u}`,c).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],d=p.map(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(h=>({...h,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags};return t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:u,properties:f}),s}}var Wzi=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=nqa,this.name=nqa,this.setupOnce=function(s,a){let u=a()?.getClient()?.getDsn()?.projectId;s(iid(t,{organization:r,projectId:u,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};a9.errorPropertiesBuilder=new Tk.ErrorPropertiesBuilder([new Tk.EventCoercer,new Tk.ErrorCoercer,new Tk.ObjectCoercer,new Tk.StringCoercer,new Tk.PrimitiveCoercer],Tk.createStackParser("node:javascript",Tk.nodeStackLineParser),[ZVa(),z6a]);var aJe=class extends BPr{getLibraryId(){return"posthog-node"}initializeContext(){return new OPr}};var TPr=class{posthog;constructor({posthogApiKey:t}){this.posthog=new aJe(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"4.43.3",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var wDt=class{async sendEvent(){}async identify(){}async flush(){}};qt();var uJe=require("fs/promises"),iqa=require("os"),oqa=require("path");var oid="id",sid=".fern",CDt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new aJe(r),this.userId=t==null?void 0:cji(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:"4.43.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 wy({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=Ge(Ut.of((0,iqa.homedir)()),Se.of(sid),Se.of(oid));await er(t)||(await(0,uJe.mkdir)((0,oqa.dirname)(t),{recursive:!0}),await(0,uJe.writeFile)(t,Kx())),this.persistedDistinctId=(await(0,uJe.readFile)(t)).toString()}return this.persistedDistinctId}};var $zi;async function cJe(){return $zi==null&&($zi=await aid()),$zi}async function aid(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new wDt;let r=await Vxr();return r!=null?new CDt({token:r,posthogApiKey:e}):await uX()!=null?new TPr({posthogApiKey:e}):new CDt({token:void 0,posthogApiKey:e})}catch{return new wDt}}St();var xDt=Ae(require("process"),1);T3e();var uqa=Ae(sPi(),1),cqa=Ae(aqa(),1);function f_(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=E6(e),e.length===0))return 0;e=e.replace((0,cqa.default)()," ");let r=t.ambiguousIsNarrow?1:2,n=0;for(let i of e){let o=i.codePointAt(0);if(o<=31||o>=127&&o<=159||o>=768&&o<=879)continue;switch(uqa.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}function PPr(e){let t=0;for(let r of e.split(`
1662
+ `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let u=D6a.test(a)?a.replace(D6a,"$1"):a;if(!u.match(/\S*Error: /)){for(let c of t){let l=c(u,e);if(l){i.push(l);break}}if(i.length>=R6a)break}}return F6a(i)}}var kzi=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=ADt(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:n?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 uke(t,"DOMException")}isDOMError(t){return uke(t,"DOMError")}};var Qzi=class{match(t){return Czi(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 n=t.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(t){return t.stacktrace||t.stack||void 0}};var jzi=class{constructor(){}match(t){return a6a(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var Qnd=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Mzi=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match(Qnd);return i&&(r=i[1],n=i[2]),[r,n]}};var k6a=["fatal","error","warning","log","info","debug"];function CPr(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var Lzi=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{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 fPr(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=CPr(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return ADt(t)&&!o6a(t)&&k6a.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(v6a(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var Uzi=class{match(t){return fPr(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${CPr(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var zzi=class{match(t){return yDt(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Vzi=class{match(t){return uke(t,"PromiseRejectionEvent")}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return yDt(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){if(yDt(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 qzi=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 M6a=require("fs"),L6a=require("readline"),xPr=new Tk.ReduceableCache(25),U6a=new Tk.ReduceableCache(20),Gzi=7,jnd=1e3,Mnd=1e4;async function z6a(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||Vnd(s)||qnd(o))continue;t[s]||(t[s]=[]),t[s].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(U6a.get(i))continue;let o=t[i];if(!o)continue;o.sort((u,c)=>u-c);let s=Wnd(o);if(s.every(u=>Gnd(i,u)))continue;let a=$nd(xPr,i,{});n.push(Lnd(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&Und(e,xPr),xPr.reduce(),e}function Lnd(e,t,r){return new Promise(n=>{let i=(0,M6a.createReadStream)(e),o=(0,L6a.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,u=0,c=t[u];if(c===void 0)return void s();let l=c[0],p=c[1];function d(){U6a.set(e,1),o.close(),o.removeAllListeners(),s()}i.on("error",d),o.on("error",d),o.on("close",s),o.on("line",f=>{if(a++,!(a<l)&&(r[a]=Hnd(f,0),a>=p)){if(u===t.length-1){o.close(),o.removeAllListeners();return}u++;let m=t[u];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function Und(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;znd(r.lineno,r,n)}}function znd(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=V6a(e);i<e;i++){let o=r[i];if(o===void 0)return void Q6a(t);t.pre_context.push(o)}if(r[e]===void 0)return void Q6a(t);t.context_line=r[e];let n=q6a(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function Q6a(e){delete e.pre_context,delete e.context_line,delete e.post_context}function Vnd(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function qnd(e){return e.lineno!==void 0&&e.lineno>Mnd||e.colno!==void 0&&e.colno>jnd}function Gnd(e,t){let r=xPr.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function Wnd(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=j6a(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+Gzi:(i.push(n),n=j6a(o)),t++}return i}function j6a(e){return[V6a(e),q6a(e)]}function V6a(e){return Math.max(1,e-Gzi)}function q6a(e){return e+Gzi}function $nd(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function Hnd(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}function Knd(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function G6a(e,t){globalThis.process?.on("uncaughtException",Knd(e,t))}function W6a(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var Jnd=2e3,a9=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new dPr({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return wzi(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i};n||(o.$process_person_profile=!1);let s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n||xX(),properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(G6a(this.onException.bind(this),this.onFatalError.bind(this)),W6a(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(Jnd),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var $6a="5.26.2";var IDt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function H6a(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(i=>i.toString(16).padStart(2,"0")).join("")}var Ynd=6e4,Xnd=1152921504606847e3,Znd=["is_not"],sJe=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Vh=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},SX=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},_Pr=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let u=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,u)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(c){c instanceof SX||c instanceof Vh?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${t}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${c}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(u=>this.featureFlagsByKey[u]).filter(Boolean):this.featureFlags,a={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async u=>{try{let{value:c,payload:l}=await this.computeFlagAndPayloadLocally(u,a);n[u.key]=c,l&&(i[u.key]=l)}catch(c){c instanceof SX||c instanceof Vh?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${u.key}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${u.key}: ${c}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(t.ensure_experience_continuity)throw new Vh("Flag has experience continuity enabled");if(!t.active)return!1;let u=(t.filters||{}).aggregation_group_type_index;if(u!=null){let c=this.groupTypeMapping[String(u)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${u} for feature flag ${t.key}`)),new Vh("Flag has unknown group type index");if(!(c in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let l=s[c];return await this.matchFeatureFlagProperties(t,i[c],l,r)}{let c=this.getBucketingValueForFlag(t,n,o);if(c===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new Vh(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,c,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new Vh("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Vh(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Vh(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Vh(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let u of s){if(!(u in i)){let l=this.featureFlagsByKey[u];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[u]=p}catch(p){throw new Vh(`Error evaluating flag dependency '${u}' for flag '${o}': ${p}`)}else i[u]=!1;else throw new Vh(`Missing flag dependency '${u}' for flag '${o}'`)}if(i[u]==null)throw new Vh(`Dependency '${u}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}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,n,i){let o=t.filters||{},s=o.groups||[],a=!1,u;for(let c of s)try{if(await this.isConditionMatch(t,r,c,n,i)){let l=c.variant,p=o.multivariate?.variants||[];u=l&&p.some(d=>d.key===l)?l:await this.getMatchingVariant(t,r)||!0;break}}catch(l){if(l instanceof SX)throw l;if(l instanceof Vh)a=!0;else throw l}if(u!==void 0)return u;if(a)throw new Vh("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let c=u.type,l=!1;if(l=c==="cohort"?Z6a(u,i,this.cohorts,this.debugMode):c==="flag"?await this.evaluateFlagDependency(u,i,o):X6a(u,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await K6a(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await K6a(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(a=>{i=n+a.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:a.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.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(n=>n.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}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(Ynd,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(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}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 sJe(`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 sJe(`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 sJe(`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 n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof sJe&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=cke(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}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((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function K6a(e,t,r=""){let n=await H6a(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/Xnd}function X6a(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")throw new Vh("Operator is_not_set is not supported")}else throw new Vh(`Property ${n} not found in propertyValues`);let s=t[n];if(s==null&&!Znd.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(c,l){return Array.isArray(c)?c.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(c).toLowerCase()===String(l).toLowerCase()}function u(c,l,p){if(p==="gt")return c>l;if(p==="gte")return c>=l;if(p==="lt")return c<l;if(p==="lte")return c<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return J6a(String(i))&&String(s).match(String(i))!==null;case"not_regex":return J6a(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let c=typeof i=="number"?i:null;if(typeof i=="string")try{c=parseFloat(i)}catch{}return c==null||s==null?u(String(s),String(i),o):typeof s=="string"?u(s,String(i),o):u(s,c,o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Vh("Date operations cannot be performed on boolean values");let c=tid(String(i));if(c==null&&(c=Y6a(i)),c==null)throw new Vh(`Invalid date: ${i}`);let l=Y6a(s);return["is_date_before"].includes(o)?l<c:l>c}default:throw new Vh(`Unknown operator: ${o}`)}}function eid(e,t){if(!(e in t))throw new SX(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function Z6a(e,t,r,n=!1){let i=String(e.value);eid(i,r);let o=r[i];return eqa(o,t,r,n)}function eqa(e,t,r,n=!1){if(!e)return!0;let i=e.type,o=e.values;if(!o||o.length===0)return!0;let s=!1;if("values"in o[0]){for(let a of o)try{let u=eqa(a,t,r,n);if(i==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof SX)throw u;if(u instanceof Vh)n&&console.debug(`Failed to compute property ${a} locally: ${u}`),s=!0;else throw u}if(s)throw new Vh("Can't match cohort without a given cohort property value");return i==="AND"}for(let a of o)try{let u;if(a.type==="cohort")u=Z6a(a,t,r,n);else if(a.type==="flag"){n&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${a.key||"unknown"}'`);continue}else u=X6a(a,t);let c=a.negation||!1;if(i==="AND"){if(!u&&!c||u&&c)return!1}else if(u&&!c||!u&&c)return!0}catch(u){if(u instanceof SX)throw u;if(u instanceof Vh)n&&console.debug(`Failed to compute property ${a} locally: ${u}`),s=!0;else throw u}if(s)throw new Vh("can't match cohort without a given cohort property value");return i==="AND"}function J6a(e){try{return new RegExp(e),!0}catch{return!1}}function Y6a(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 Vh(`${e} is in an invalid date format`)}throw new Vh(`The date provided ${e} must be a string, number, or date object`)}function tid(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-i);else if(o=="d")n.setUTCDate(n.getUTCDate()-i);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}}var SPr=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var rid=100,tqa=3e4,nid=5e4,BPr=class extends vDt{constructor(t,r={}){if(super(t,r),this._memoryStorage=new SPr,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,rid):tqa,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 _Pr({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new a9(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||nid}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 $6a}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."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.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."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStateless(t,l,{disableGeoip:n})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};super.identifyStatelessImmediate(t,l,{disableGeoip:n})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=tqa){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let w=this._flagOverrides[t];if(w===void 0)return;let x=this._payloadOverrides?.[t];return{key:t,enabled:w!==!1,variant:typeof w=="string"?w:void 0,payload:x}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,c,l);u==null&&(u=this.options.strictLocalEvaluation??!1);let f,m=!1,h,g,A,b,v,E;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let w=this.featureFlagsPoller?.featureFlagsByKey[t];if(w)try{let x=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(w,d,{matchValue:i});if(x){m=!0;let C=x.value;b=w.id,E="Evaluated locally",f={key:t,enabled:C!==!1,variant:typeof C=="string"?C:void 0,payload:x.payload??void 0}}}catch(x){if(x instanceof SX||x instanceof Vh)this._logger?.info(`${x.name} when computing flag locally: ${t}: ${x.message}`);else throw x}}if(!m&&!u){let w=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(w===void 0)A=IDt.UNKNOWN_ERROR;else{h=w.requestId,g=w.evaluatedAt;let x=[];w.errorsWhileComputingFlags&&x.push(IDt.ERRORS_WHILE_COMPUTING),w.quotaLimited?.includes("feature_flags")&&x.push(IDt.QUOTA_LIMITED);let C=w.flags[t];if(C===void 0)x.push(IDt.FLAG_MISSING);else{b=C.metadata?.id,v=C.metadata?.version,E=C.reason?.description??C.reason?.code;let _;if(C.metadata?.payload!==void 0)try{_=JSON.parse(C.metadata.payload)}catch{_=C.metadata.payload}f={key:t,enabled:C.enabled,variant:C.variant,payload:_}}x.length>0&&(A=x.join(","))}}if(o){let w=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,x=`${t}_${w}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(x)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(x):this.distinctIdHasSentFlagCalls[r]=[x];let C={$feature_flag:t,$feature_flag_response:w,$feature_flag_id:b,$feature_flag_version:v,$feature_flag_reason:E,locally_evaluated:m,[`$feature/${t}`]:w,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():g};if(m&&this.featureFlagsPoller){let _=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();_!==void 0&&(C.$feature_flag_definitions_loaded_at=_)}A&&(C.$feature_flag_error=A),this.capture({distinctId:r,event:"$feature_flag_called",properties:C,groups:s,disableGeoip:a})}}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}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 n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){let i=await this.getFeatureFlag(t,r,n);if(i!==void 0)return!!i||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,c,l);u==null&&(u=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},h={},g=!0;if(f&&(m=f.response,h=f.payloads,g=f.fallbackToFlags),g&&!u){let A=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);m={...m,...A.flags||{}},h={...h,...A.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(h={...h,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:h}}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!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 n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}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)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=cke(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,s]of Object.entries(t))if(u6a(s)&&r&&o in r){let a={};for(let[u,c]of Object.entries(s))a[String(u)]=String(c);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,p]of Object.entries(r||{}))c[l]=String(p);return await this.getAllFlags(t,{groups:c,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,p]of Object.entries(r||{}))c[l]=String(p);return await this.getAllFlags(t,{groups:c,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i){if(!a9.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");this.addPendingPromise(a9.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.capture({...s,uuid:i})))}}async captureExceptionImmediate(t,r,n){if(!a9.isPreviouslyCapturedError(t)){let i=new Error("PostHog syntheticException");this.addPendingPromise(a9.buildEventMessage(t,{syntheticException:i},r,n).then(o=>this.captureImmediate(o)))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:u,uuid:c}=t,l=this.context?.get(),p=r||l?.distinctId,d={...this.props,...l?.properties||{},...i||{}};p||(p=xX(),d.$process_person_profile=!1),l?.sessionId&&!d.$session_id&&(d.$session_id=l.sessionId);let f=this._runBeforeSend({distinctId:p,event:n,properties:d,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:u,uuid:c});if(!f)return Promise.reject(null);let m=await Promise.resolve().then(async()=>{if(s){let h=typeof s=="object"?s:void 0;return await this.getFeatureFlagsForEvent(f.distinctId,o,u,h)}return f.event,{}}).then(h=>{let g={};if(h)for(let[b,v]of Object.entries(h))g[`$feature/${b}`]=v;let A=Object.keys(h||{}).filter(b=>h?.[b]!==!1).sort();return A.length>0&&(g.$active_feature_flags=A),g}).catch(()=>({})).then(h=>({...h,...f.properties||{},$groups:f.groups||o}));return f.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof m.$raw_user_agent=="string"&&n6a(m.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(f.event="$bot_pageview",m.$browser_type="bot"),{distinctId:f.distinctId,event:f.event,properties:m,options:{timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n){if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}};var rqa=require("async_hooks"),OPr=class{constructor(){this.storage=new rqa.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){return this.storage.run(this.resolve(t,n),r)}enter(t,r){this.storage.enterWith(this.resolve(t,r))}resolve(t,r){if(r?.fresh===!0)return t;let n=this.get()||{};return{distinctId:t.distinctId??n.distinctId,sessionId:t.sessionId??n.sessionId,properties:{...n.properties||{},...t.properties||{}}}}};var nqa="posthog-node";function iid(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let u=s.tags[Wzi.POSTHOG_ID_TAG];if(u===void 0)return s;let c=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${u}`,c).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],d=p.map(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(h=>({...h,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags};return t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:u,properties:f}),s}}var Wzi=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=nqa,this.name=nqa,this.setupOnce=function(s,a){let u=a()?.getClient()?.getDsn()?.projectId;s(iid(t,{organization:r,projectId:u,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};a9.errorPropertiesBuilder=new Tk.ErrorPropertiesBuilder([new Tk.EventCoercer,new Tk.ErrorCoercer,new Tk.ObjectCoercer,new Tk.StringCoercer,new Tk.PrimitiveCoercer],Tk.createStackParser("node:javascript",Tk.nodeStackLineParser),[ZVa(),z6a]);var aJe=class extends BPr{getLibraryId(){return"posthog-node"}initializeContext(){return new OPr}};var TPr=class{posthog;constructor({posthogApiKey:t}){this.posthog=new aJe(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"4.43.4",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var wDt=class{async sendEvent(){}async identify(){}async flush(){}};qt();var uJe=require("fs/promises"),iqa=require("os"),oqa=require("path");var oid="id",sid=".fern",CDt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new aJe(r),this.userId=t==null?void 0:cji(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:"4.43.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 wy({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=Ge(Ut.of((0,iqa.homedir)()),Se.of(sid),Se.of(oid));await er(t)||(await(0,uJe.mkdir)((0,oqa.dirname)(t),{recursive:!0}),await(0,uJe.writeFile)(t,Kx())),this.persistedDistinctId=(await(0,uJe.readFile)(t)).toString()}return this.persistedDistinctId}};var $zi;async function cJe(){return $zi==null&&($zi=await aid()),$zi}async function aid(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new wDt;let r=await Vxr();return r!=null?new CDt({token:r,posthogApiKey:e}):await uX()!=null?new TPr({posthogApiKey:e}):new CDt({token:void 0,posthogApiKey:e})}catch{return new wDt}}St();var xDt=Ae(require("process"),1);T3e();var uqa=Ae(sPi(),1),cqa=Ae(aqa(),1);function f_(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=E6(e),e.length===0))return 0;e=e.replace((0,cqa.default)()," ");let r=t.ambiguousIsNarrow?1:2,n=0;for(let i of e){let o=i.codePointAt(0);if(o<=31||o>=127&&o<=159||o>=768&&o<=879)continue;switch(uqa.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}function PPr(e){let t=0;for(let r of e.split(`
1663
1663
  `))t=Math.max(t,f_(r));return t}var Oqa=Ae(Kzi(),1);var cid=/[\p{Lu}]/u,lid=/[\p{Ll}]/u,fqa=/^[\p{Lu}](?![\p{Lu}])/gu,hqa=/([\p{Alpha}\p{N}_]|$)/u,Jzi=/[_.\- ]+/,pid=new RegExp("^"+Jzi.source),dqa=new RegExp(Jzi.source+hqa.source,"gu"),mqa=new RegExp("\\d+"+hqa.source,"gu"),fid=(e,t,r,n)=>{let i=!1,o=!1,s=!1,a=!1;for(let u=0;u<e.length;u++){let c=e[u];a=u>2?e[u-3]==="-":!0,i&&cid.test(c)?(e=e.slice(0,u)+"-"+e.slice(u),i=!1,s=o,o=!0,u++):o&&s&&lid.test(c)&&(!a||n)?(e=e.slice(0,u-1)+"-"+e.slice(u-1),s=o,o=!1,i=!0):(i=t(c)===c&&r(c)!==c,s=o,o=r(c)===c&&t(c)!==c)}return e},did=(e,t)=>(fqa.lastIndex=0,e.replace(fqa,r=>t(r))),mid=(e,t)=>(dqa.lastIndex=0,mqa.lastIndex=0,e.replace(dqa,(r,n)=>t(n)).replace(mqa,r=>t(r)));function Yzi(e,t){if(!(typeof e=="string"||Array.isArray(e)))throw new TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},Array.isArray(e)?e=e.map(o=>o.trim()).filter(o=>o.length).join("-"):e=e.trim(),e.length===0)return"";let r=t.locale===!1?o=>o.toLowerCase():o=>o.toLocaleLowerCase(t.locale),n=t.locale===!1?o=>o.toUpperCase():o=>o.toLocaleUpperCase(t.locale);return e.length===1?Jzi.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=fid(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(pid,""),e=t.preserveConsecutiveUppercase?did(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),mid(e,n))}var t5i=Ae(Aqa(),1);T3e();var yqa=(e=0)=>t=>`\x1B[${t+e}m`,bqa=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,Eqa=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,bb={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]}},i9b=Object.keys(bb.modifier),yid=Object.keys(bb.color),bid=Object.keys(bb.bgColor),o9b=[...yid,...bid];function Eid(){let e=new Map;for(let[t,r]of Object.entries(bb)){for(let[n,i]of Object.entries(r))bb[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=bb[n],e.set(i[0],i[1]);Object.defineProperty(bb,t,{value:r,enumerable:!1})}return Object.defineProperty(bb,"codes",{value:e,enumerable:!1}),bb.color.close="\x1B[39m",bb.bgColor.close="\x1B[49m",bb.color.ansi=yqa(),bb.color.ansi256=bqa(),bb.color.ansi16m=Eqa(),bb.bgColor.ansi=yqa(10),bb.bgColor.ansi256=bqa(10),bb.bgColor.ansi16m=Eqa(10),Object.defineProperties(bb,{rgbToAnsi256:{value(t,r,n){return t===r&&r===n?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(n/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[n]=r;n.length===3&&(n=[...n].map(o=>o+o).join(""));let i=Number.parseInt(n,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:t=>bb.rgbToAnsi256(...bb.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,n,i;if(t>=232)r=((t-232)*10+8)/255,n=r,i=r;else{t-=16;let a=t%36;r=Math.floor(t/36)/5,n=Math.floor(a/6)/5,i=a%6/5}let o=Math.max(r,n,i)*2;if(o===0)return 30;let s=30+(Math.round(i)<<2|Math.round(n)<<1|Math.round(r));return o===2&&(s+=60),s},enumerable:!1},rgbToAnsi:{value:(t,r,n)=>bb.ansi256ToAnsi(bb.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>bb.ansi256ToAnsi(bb.hexToAnsi256(t)),enumerable:!1}}),bb}var vid=Eid(),vqa=vid;var DPr=new Set(["\x1B","\x9B"]),Iid=39,Zzi="\x07",Cqa="[",wid="]",xqa="m",e5i=`${wid}8;;`,Iqa=e=>`${DPr.values().next().value}${Cqa}${e}${xqa}`,wqa=e=>`${DPr.values().next().value}${e5i}${e}${Zzi}`,Cid=e=>e.split(" ").map(t=>f_(t)),Xzi=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=f_(E6(e[e.length-1]));for(let[a,u]of n.entries()){let c=f_(u);if(s+c<=r?e[e.length-1]+=u:(e.push(u),s=0),DPr.has(u)&&(i=!0,o=n.slice(a+1).join("").startsWith(e5i)),i){o?u===Zzi&&(i=!1,o=!1):u===xqa&&(i=!1);continue}s+=c,s===r&&a<n.length-1&&(e.push(""),s=0)}!s&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},xid=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(f_(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},_id=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=Cid(e),a=[""];for(let[c,l]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=f_(a[a.length-1]);if(c!==0&&(p>=t&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),p=0),(p>0||r.trim===!1)&&(a[a.length-1]+=" ",p++)),r.hard&&s[c]>t){let d=t-p,f=1+Math.floor((s[c]-d-1)/t);Math.floor((s[c]-1)/t)<f&&a.push(""),Xzi(a,l,t);continue}if(p+s[c]>t&&p>0&&s[c]>0){if(r.wordWrap===!1&&p<t){Xzi(a,l,t);continue}a.push("")}if(p+s[c]>t&&r.wordWrap===!1){Xzi(a,l,t);continue}a[a.length-1]+=l}r.trim!==!1&&(a=a.map(c=>xid(c)));let u=[...a.join(`
1664
1664
  `)];for(let[c,l]of u.entries()){if(n+=l,DPr.has(l)){let{groups:d}=new RegExp(`(?:\\${Cqa}(?<code>\\d+)m|\\${e5i}(?<uri>.*)${Zzi})`).exec(u.slice(c).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===Iid?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=vqa.codes.get(Number(i));u[c+1]===`
1665
1665
  `?(o&&(n+=wqa("")),i&&p&&(n+=Iqa(p))):l===`
@@ -2199,7 +2199,7 @@ Hint: Values starting with "@" (such as scoped npm packages) must be wrapped in
2199
2199
  Example: package-name: "@scope/package"`)}return{success:!1,warnings:[{type:"conflict",message:`Failed to parse generators.yml: ${o}`}]}}}checkDeprecatedFields(t,r){t.openapi!=null&&r.push({type:"deprecated",message:"The 'openapi' field is deprecated",suggestion:"Use 'api.specs' instead"}),t["openapi-overrides"]!=null&&r.push({type:"deprecated",message:"The 'openapi-overrides' field is deprecated",suggestion:"Use 'api.specs.[].overrides' instead"}),t["spec-origin"]!=null&&r.push({type:"deprecated",message:"The 'spec-origin' field is deprecated",suggestion:"Use 'api.specs.[].origin' instead"}),t["async-api"]!=null&&r.push({type:"deprecated",message:"The 'async-api' field is deprecated",suggestion:"Use 'api.specs' with asyncapi instead"}),t["api-settings"]!=null&&r.push({type:"deprecated",message:"The 'api-settings' field is deprecated",suggestion:"Use 'api.specs.[].settings' instead"}),t.whitelabel!=null&&r.push({type:"unsupported",message:"Whitelabel configuration is not yet supported in fern.yml"}),t.metadata!=null&&r.push({type:"unsupported",message:"Metadata configuration is not yet supported in fern.yml"}),t.reviewers!=null&&r.push({type:"unsupported",message:"Reviewers configuration is not yet supported in fern.yml"}),t.aliases!=null&&r.push({type:"unsupported",message:"Group aliases are not yet supported in fern.yml",suggestion:"Use multiple group names in target.group array instead"}),t["auth-schemes"]!=null&&r.push({type:"info",message:"Auth schemes configuration detected but not yet migrated",suggestion:"Auth schemes will be supported in a future version"})}async getAbsoluteFilePath(){let t=Ge(this.cwd,Se.of(Cm)),r=Ge(this.cwd,Se.of(Q8e));if(await er(t,"file"))return t;if(await er(r,"file"))return r}};var jQt=class{cwd;logger;deleteOriginals;constructor(t){this.cwd=t.cwd,this.logger=t.logger,this.deleteOriginals=t.deleteOriginals??!0}async migrate(){let t=[],r=[],n=await this.findFernDirectory();if(n==null)return{success:!1,warnings:[{type:"conflict",message:"Could not find fern directory",suggestion:"Run this command from a directory containing a 'fern' folder"}],migratedFiles:r};let o=await new QQt({cwd:n}).migrate();if(t.push(...o.warnings),!o.success||o.org==null)return{success:!1,warnings:[...t,{type:"conflict",message:"Failed to migrate fern.config.json - organization is required"}],migratedFiles:r};o.absoluteFilePath!=null&&r.push(o.absoluteFilePath);let s=Ge(n,Se.of(VP)),a=await er(s,"directory"),u;if(a){let p=await this.migrateMultiApi({fernDir:n,apisDir:s,org:o.org,warnings:t,migratedFiles:r});if(!p.success)return{success:!1,warnings:t,migratedFiles:r};u=p.fernYml}else{let p=await this.migrateSingleApi({fernDir:n,org:o.org,warnings:t,migratedFiles:r});if(!p.success)return{success:!1,warnings:t,migratedFiles:r};u=p.fernYml}let c=Ge(this.cwd,Se.of(Nv)),l=this.serializeFernYml(u);if(await(0,Rlt.writeFile)(c,l,"utf-8"),this.deleteOriginals)for(let p of r)try{await(0,Rlt.rm)(p),this.logger.debug(`Deleted ${p}`)}catch{t.push({type:"info",message:`Could not delete ${p}`})}return this.logger.info(`Created ${c}`),{success:!0,warnings:t,migratedFiles:r,outputPath:c}}async migrateSingleApi(t){let{fernDir:r,org:n,warnings:i,migratedFiles:o}=t,a=await new XQe({cwd:r}).migrate();i.push(...a.warnings),a.absoluteFilePath!=null&&o.push(a.absoluteFilePath);let u=await Yso({fernDir:r,generatorsYmlApi:a.rawApi});i.push(...u.warnings);let c={org:n};return u.api!=null&&(c.api=u.api),a.sdks!=null&&(c.sdks=a.sdks),{success:!0,fernYml:c}}async migrateMultiApi(t){let{fernDir:r,apisDir:n,org:i,warnings:o,migratedFiles:s}=t,u=(await(0,Rlt.readdir)(n,{withFileTypes:!0})).filter(A=>A.isDirectory()).map(A=>A.name);if(u.length===0)return o.push({type:"conflict",message:"No API directories found in fern/apis/"}),{success:!1,fernYml:{org:i}};let c={},l={targets:{}},p,d;for(let A of u){let b=Ge(n,Se.of(A)),E=await new XQe({cwd:b,apiName:A}).migrate();if(o.push(...E.warnings),E.absoluteFilePath!=null&&s.push(E.absoluteFilePath),c[A]=E.rawApi,E.sdks!=null){for(let[I,w]of Object.entries(E.sdks.targets))l.targets[I]=w;E.sdks.defaultGroup!=null&&p==null&&(p=E.sdks.defaultGroup),E.sdks.autorelease!=null&&d==null&&(d=E.sdks.autorelease)}}let f=await Xso({fernDir:r,apisDir:n,generatorsYmlApis:c});o.push(...f.warnings);let m={org:i,apis:f.apis};Object.keys(l.targets).length>0&&(p!=null&&(l.defaultGroup=p),d!=null&&(l.autorelease=d),m.sdks=l);let g=await new XQe({cwd:r}).detect();return g.found&&g.absoluteFilePath!=null&&(o.push({type:"info",message:"Found generators.yml in fern root alongside apis/ directory",suggestion:"Review the migrated configuration to ensure it's correct"}),s.push(g.absoluteFilePath)),{success:!0,fernYml:m}}async findFernDirectory(){if(this.cwd.split("/").pop()===Ng)return this.cwd;let r=Ge(this.cwd,Se.of(Ng));if(await er(r,"directory"))return r}serializeFernYml(t){let r={edition:t.edition,org:t.org};return t.api!=null&&(r.api=t.api),t.apis!=null&&(r.apis=t.apis),t.ai!=null&&(r.ai=t.ai),t.cli!=null&&(r.cli=t.cli),t.sdks!=null&&(r.sdks=this.simplifySdks(t.sdks)),_r.dump(r,{indent:2,lineWidth:120,noRefs:!0,sortKeys:!1,quotingType:'"',forceQuotes:!1})}simplifySdks(t){let r={...t},n={};for(let[i,o]of Object.entries(t.targets)){let s=o.output;if(typeof s=="string"){n[i]=o;continue}if(s.git==null&&s.path!=null){n[i]={...o,output:s.path};continue}n[i]=o}return r.targets=n,r}};var Zso=class{async handle(t,r){let i=await new jQt({cwd:t.cwd,logger:t.stdout,deleteOriginals:r.delete}).migrate();for(let o of i.warnings){switch(o.type){case"deprecated":t.stdout.warn(`Deprecated: ${o.message}`);break;case"unsupported":t.stdout.warn(`Unsupported: ${o.message}`);break;case"conflict":t.stderr.error(`Error: ${o.message}`);break;case"info":t.stdout.info(o.message);break}o.suggestion!=null&&t.stdout.info(` Suggestion: ${o.suggestion}`)}if(i.success){i.outputPath!=null&&t.stdout.debug(`Created: ${i.outputPath}`);return}throw new Yr({message:"Migration failed"})}};function eao(e){let t=new Zso;Ra(e,"migrate","Migrate legacy configuration files to fern.yml",(r,n)=>t.handle(r,n),r=>r.option("delete",{type:"boolean",description:"Keep original files after migration",default:!0}))}function tao(e){QB(e,"config","Configure, edit, and inspect your settings",[eao])}var rao=class{async handle(t,r){let n=await t.loadWorkspaceOrThrow();if(n.docs==null)throw new Yr({message:`No docs configuration found in fern.yml.
2200
2200
 
2201
2201
  Add a 'docs:' section to your fern.yml to get started.`});let o=await new k_e({context:t}).check({workspace:n,strict:r.strict}),s=o.hasErrors||r.strict&&o.hasWarnings;if(r.json){let a=this.buildJsonResponse({result:o,hasErrors:s});if(t.stdout.info(JSON.stringify(a,null,2)),s)throw Yr.exit();return}if(o.violations.length>0)for(let a of o.violations){let u=a.severity==="warning"?be.yellow:be.red;process.stderr.write(`${u(`${a.displayRelativeFilepath}:${a.line}:${a.column}: ${a.message}`)}
2202
- `)}if(s)throw Yr.exit();if(o.warningCount>0){t.stderr.info(`${bo.warning} ${be.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(be.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${bo.success} ${be.green("All checks passed")}`)}buildJsonResponse({result:t,hasErrors:r}){let n={};return t.violations.length>0&&(n.docs=t.violations.map(i=>XX(i))),{success:!r,results:n}}};function nao(e){let t=new rao;Ra(e,"check","Validate docs configuration",(r,n)=>t.handle(r,n),r=>r.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}))}var B2u=Ae(require("net"),1),O2u=Ae(require("os"),1),_Fn=class extends Error{constructor(t){super(`${t} is locked`)}},Flt={old:new Set,young:new Set},Pom=1e3*15;var MQt,Dom=()=>{let e=O2u.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let n of r)t.add(n.address);return t},_2u=e=>new Promise((t,r)=>{let n=B2u.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),S2u=async(e,t)=>{if(e.host||e.port===0)return _2u(e);for(let r of t)try{await _2u({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},Rom=function*(e){e&&(yield*e),yield 0};async function Q_e(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let i=e.exclude;if(typeof i[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let o of i){if(typeof o!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(o))throw new TypeError(`Number ${o} in the exclude option is not a safe integer and can't be used`)}r=new Set(i)}MQt===void 0&&(MQt=setTimeout(()=>{MQt=void 0,Flt.old=Flt.young,Flt.young=new Set},Pom),MQt.unref&&MQt.unref());let n=Dom();for(let i of Rom(t))try{if(r.has(i))continue;let o=await S2u({...e,port:i},n);for(;Flt.old.has(o)||Flt.young.has(o);){if(i!==0)throw new _Fn(i);o=await S2u({...e,port:i},n)}return Flt.young.add(o),o}catch(o){if(!["EADDRINUSE","EACCES"].includes(o.code)&&!(o instanceof _Fn))throw o}throw new Error("No available ports found")}St();qg();qt();var W6u=Ae(sao(),1),$6u=Ae(fNn(),1),Jkn=require("fs/promises"),H6u=Ae(require("http"),1),K6u=Ae(require("path"),1);var SUu=require("events"),ANn=Ae(require("fs"),1),uje=Ae(require("path"),1);var cUu=Ae(require("os"),1),lUu=300,q_e=20,ljt=1e7,pUu=cUu.default.platform();var Hfm=pUu==="darwin",xuo=pUu==="win32",G_e=Hfm||xuo,fUu=3e3,dUu=2e4,_uo=1250;var Ire;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(Ire||(Ire={}));var aje;(function(e){e.CHANGE="change",e.RENAME="rename"})(aje||(aje={}));var pjt;(function(e){e.CHANGE="change",e.ERROR="error"})(pjt||(pjt={}));var gu;(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"})(gu||(gu={}));var $R;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})($R||($R={}));var Kfm=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),s,a,u=0,c=0,l=()=>{let E=Date.now(),I=E-u,w=E-c,x=I>=t||w>=o;return[E,x]},p=E=>{if(c=E,!s)return;let I=s;s=void 0,e.apply(void 0,I)},d=()=>{b(0)},f=()=>{a&&(d(),p(Date.now()))},m=E=>{if(c=E,n)return p(E)},h=E=>{if(i&&s)return p(E);s=void 0},g=()=>{a=void 0;let[E,I]=l();return I?h(E):A(E)},A=E=>{let I=E-u,w=E-c,x=t-I,C=o-w,_=Math.min(x,C);return b(_)},b=E=>{a&&clearTimeout(a),!(E<=0)&&(a=setTimeout(g,E))},v=(...E)=>{let[I,w]=l(),x=!!a;if(s=E,u=I,(w||!a)&&b(t),w)return x?p(I):m(I)};return v.cancel=d,v.flush=f,v},dNn=Kfm;var Tuo=Ae(require("fs"),1),hNn=Ae(require("path"),1);var Yf=Ae(require("fs"),1),mB=require("util");var Ope=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},wre=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var Suo=Ae(require("process"),1),mUu=Suo.default.getuid?!Suo.default.getuid():!1,hUu=1e4,K2=()=>{};var fjt={isChangeErrorOk:e=>{if(!fjt.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!mUu&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!fjt.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(!fjt.isNodeError(e))throw e;if(!fjt.isChangeErrorOk(e))throw e}},Vv=fjt;var Buo=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=hUu,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(n),n=()=>t(r);this.add(n)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},gUu=new Buo;var Tpe=(e,t)=>function(n){return function i(...o){return gUu.schedule().then(s=>{let a=c=>(s(),c),u=c=>{if(s(),Date.now()>=n)throw c;if(t(c)){let l=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,l)).then(()=>i.apply(void 0,o))}throw c};return e.apply(void 0,o).then(a,u)})}},Ppe=(e,t)=>function(n){return function i(...o){try{return e.apply(void 0,o)}catch(s){if(Date.now()>n)throw s;if(t(s))return i.apply(void 0,o);throw s}}};var Jfm={attempt:{chmod:Ope((0,mB.promisify)(Yf.default.chmod),Vv.onChangeError),chown:Ope((0,mB.promisify)(Yf.default.chown),Vv.onChangeError),close:Ope((0,mB.promisify)(Yf.default.close),K2),fsync:Ope((0,mB.promisify)(Yf.default.fsync),K2),mkdir:Ope((0,mB.promisify)(Yf.default.mkdir),K2),realpath:Ope((0,mB.promisify)(Yf.default.realpath),K2),stat:Ope((0,mB.promisify)(Yf.default.stat),K2),unlink:Ope((0,mB.promisify)(Yf.default.unlink),K2),chmodSync:wre(Yf.default.chmodSync,Vv.onChangeError),chownSync:wre(Yf.default.chownSync,Vv.onChangeError),closeSync:wre(Yf.default.closeSync,K2),existsSync:wre(Yf.default.existsSync,K2),fsyncSync:wre(Yf.default.fsync,K2),mkdirSync:wre(Yf.default.mkdirSync,K2),realpathSync:wre(Yf.default.realpathSync,K2),statSync:wre(Yf.default.statSync,K2),unlinkSync:wre(Yf.default.unlinkSync,K2)},retry:{close:Tpe((0,mB.promisify)(Yf.default.close),Vv.isRetriableError),fsync:Tpe((0,mB.promisify)(Yf.default.fsync),Vv.isRetriableError),open:Tpe((0,mB.promisify)(Yf.default.open),Vv.isRetriableError),readFile:Tpe((0,mB.promisify)(Yf.default.readFile),Vv.isRetriableError),rename:Tpe((0,mB.promisify)(Yf.default.rename),Vv.isRetriableError),stat:Tpe((0,mB.promisify)(Yf.default.stat),Vv.isRetriableError),write:Tpe((0,mB.promisify)(Yf.default.write),Vv.isRetriableError),writeFile:Tpe((0,mB.promisify)(Yf.default.writeFile),Vv.isRetriableError),closeSync:Ppe(Yf.default.closeSync,Vv.isRetriableError),fsyncSync:Ppe(Yf.default.fsyncSync,Vv.isRetriableError),openSync:Ppe(Yf.default.openSync,Vv.isRetriableError),readFileSync:Ppe(Yf.default.readFileSync,Vv.isRetriableError),renameSync:Ppe(Yf.default.renameSync,Vv.isRetriableError),statSync:Ppe(Yf.default.statSync,Vv.isRetriableError),writeSync:Ppe(Yf.default.writeSync,Vv.isRetriableError),writeFileSync:Ppe(Yf.default.writeFileSync,Vv.isRetriableError)}},AUu=Jfm;var mNn=Ae(require("fs"),1),djt=Ae(require("path"),1);var Ouo=()=>{};var Yfm=()=>{let e=Ouo,t=Ouo,r=!1,n=!1;return{promise:new Promise((u,c)=>{e=l=>(r=!0,u(l)),t=l=>(n=!0,c(l))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},yUu=Yfm;var Xfm=()=>{let{promise:e,resolve:t,isPending:r}=yUu(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},bUu=Xfm;var EUu={then:e=>{e()}};var vUu=e=>Array.isArray(e)?e:[e],IUu=e=>typeof e=="function";var Zfm=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],s=vUu(o).map(J=>IUu(J)?J:X=>J.test(X)),a=J=>s.some(X=>X(J)),u=t?.signal??{aborted:!1},c=t?.onDirents||(()=>{}),l=[],p=new Set,d={},f=[],m=new Set,h={},g=[],A=new Set,b={},v={},E=new Set,I={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},w={directories:l,directoriesNames:p,directoriesNamesToPaths:d,files:f,filesNames:m,filesNamesToPaths:h,symlinks:g,symlinksNames:A,symlinksNamesToPaths:b,map:v},{promise:x,increment:C,decrement:_}=bUu(),D=0,U=(J,X,ge,he)=>{E.has(X)||D>=i||(D+=1,J.directories.push(X),J.directoriesNames.add(ge),l.push(X),p.add(ge),d.propertyIsEnumerable(ge)||(d[ge]=[]),d[ge].push(X),E.add(X),!(he>=n)&&(D>=i||H(X,he+1)))},q=(J,X,ge)=>{E.has(X)||D>=i||(D+=1,J.files.push(X),J.filesNames.add(ge),f.push(X),m.add(ge),h.propertyIsEnumerable(ge)||(h[ge]=[]),h[ge].push(X),E.add(X))},z=(J,X,ge,he)=>{E.has(X)||D>=i||(D+=1,J.symlinks.push(X),J.symlinksNames.add(ge),g.push(X),A.add(ge),b.propertyIsEnumerable(ge)||(b[ge]=[]),b[ge].push(X),E.add(X),r&&(he>=n||D>=i||Ee(X,he+1)))},Y=(J,X,ge,he,Ce)=>{u.aborted||a(X)||(he.isDirectory()?U(J,X,ge,Ce):he.isFile()?q(J,X,ge):he.isSymbolicLink()&&z(J,X,ge,Ce))},ne=(J,X,ge,he)=>{if(u.aborted)return;let Ce=X===djt.default.sep?"":djt.default.sep,_e=ge.name,ce=`${X}${Ce}${_e}`;a(ce)||(ge.isDirectory()?U(J,ce,_e,he):ge.isFile()?q(J,ce,_e):ge.isSymbolicLink()&&z(J,ce,_e,he))},V=(J,X,ge,he)=>{for(let Ce=0,_e=ge.length;Ce<_e;Ce++)ne(J,X,ge[Ce],he)},H=(J,X)=>{u.aborted||X>n||D>=i||(C(),mNn.default.readdir(J,{withFileTypes:!0},(ge,he)=>{if(ge||u.aborted||!he.length)return _();(c(he)||EUu).then(()=>{let _e=v[J]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};V(_e,J,he,X),_()})}))},Ee=(J,X)=>{C(),mNn.default.realpath(J,(ge,he)=>{if(ge||u.aborted)return _();mNn.default.stat(he,(Ce,_e)=>{if(Ce||u.aborted)return _();let ce=djt.default.basename(he),se=v[J]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Y(se,he,ce,_e,X),_()})})};return(async(J,X=1)=>(J=djt.default.normalize(J),E.add(J),H(J,X),await x,u.aborted?I:w))(e)},wUu=Zfm;var Cre={lang:{debounce:dNn,attempt:e=>{try{return e()}catch(t){return Cre.lang.castError(t)}},castArray:e=>Cre.lang.isArray(e)?e:[e],castError:e=>Cre.lang.isError(e)?e:Cre.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(Cre.lang.isNaN(e))return Cre.lang.isNaN(t);if(Cre.lang.isPrimitive(e)||Cre.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(hNn.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Tuo.default.realpathSync.native(e):Tuo.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===hNn.default.sep&&t.length-e.length>hNn.default.sep.length,poll:(e,t=dUu)=>AUu.retry.stat(t)(e,{bigint:!0}).catch(Cre.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,o)=>{if(o&&r===1&&e in o){let s=o[e];return[s.directories,s.files]}else{let s=await wUu(e,{depth:r,limit:n,ignore:t,signal:i});return[s.directories,s.files]}}}},Pl=Cre;var gNn=Ae(require("path"),1);var Puo=class{constructor(t,r,n){this.base=n,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Pl.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=lUu){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(a,u)=>{let c=this.options.ignoreInitial?[]:a,l=await this.eventsPopulate([...u]),p=this.eventsDeduplicate([...c,...l]);this.onTargetEvents(p)},s=Pl.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(a,u="",c=!1)=>{c?await this.eventsPopulate([u],n,!0):i.add(u),r.then(s)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,s]=i,a=r[s];return o===a||o===gu.CHANGE&&a===gu.ADD||(r[s]=o,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let o=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(o.map(async s=>{r.push([s,i]),s===gu.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):s===gu.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let o=this.options.recursive?this.options.depth??q_e:Math.min(1,this.options.depth??q_e),s=this.options.limit??ljt,[a,u]=await Pl.fs.readdir(r,this.options.ignore,o,s,this.watcher._closeSignal),c=[...a,...u];return await Promise.all(c.map(l=>{if(!this.watcher.isIgnored(l,this.options.ignore)&&!t.includes(l))return this.eventsPopulate([l],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())Pl.fs.isSubPath(r,o)&&(t.includes(o)||await this.eventsPopulate([o],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(gu.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!G_e&&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(gu.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(gu.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(gNn.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(gu.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(gNn.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(gu.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===gu.ADD?this.onTargetAdd(n):r===gu.ADD_DIR?this.onTargetAddDir(n):r===gu.CHANGE?this.onTargetChange(n):r===gu.UNLINK?this.onTargetUnlink(n):r===gu.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=aje.CHANGE,r){if(this.watcher.isClosed())return;let n=gNn.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){xuo&&t.code==="EPERM"?this.onWatcherChange(aje.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(pjt.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(pjt.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(aje.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&G_e&&this.options.native!==!1?this.options.depth??q_e:Math.min(1,this.options.depth??q_e),n=this.options.limit??ljt,[i,o]=await Pl.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),s=[this.folderPath,...i,...o];await Promise.all(s.map(a=>{if(!this.watcher._poller.stats.has(a)&&!this.watcher.isIgnored(a,this.options.ignore))return this.onWatcherEvent(aje.CHANGE,a,t)}))}}},CUu=Puo;var HR={interval:100,intervalId:void 0,fns:new Map,init:()=>{HR.intervalId||(HR.intervalId=setInterval(HR.resolve,HR.interval))},reset:()=>{HR.intervalId&&(clearInterval(HR.intervalId),delete HR.intervalId)},add:(e,t)=>{HR.fns.set(e,Date.now()+t),HR.init()},remove:e=>{HR.fns.delete(e)},resolve:()=>{if(!HR.fns.size)return HR.reset();let e=Date.now();for(let[t,r]of HR.fns)r>=e||(HR.remove(t),t())}},mjt=HR;var hjt=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=_uo){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{let p=this._watcher._poller.paths.find(n||-1,d=>d!==i);if(p&&p!==i){if(Pl.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return a();let u=()=>{s.add.delete(n),mjt.remove(c)},c=()=>{u(),a()};mjt.add(c,r);let l=()=>{let p=s.unlink.get(n);if(!p)return;u();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};s.add.set(n,l),l()}getLockUnlink(t,r=_uo){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{this._watcher.event(o.unlink,i)};if(!n)return a();let u=()=>{s.unlink.delete(n),mjt.remove(c)},c=()=>{u(),a()};mjt.add(c,r);let l=()=>(u(),i);s.unlink.set(n,l),s.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,gu.ADD,Ire.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,gu.ADD_DIR,Ire.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,gu.UNLINK,Ire.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,gu.UNLINK_DIR,Ire.DIR);return this.getLockUnlink({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};hjt.DIR_EVENTS={add:gu.ADD_DIR,rename:gu.RENAME_DIR,unlink:gu.UNLINK_DIR};hjt.FILE_EVENTS={add:gu.ADD,change:gu.CHANGE,rename:gu.RENAME,unlink:gu.UNLINK};var xUu=hjt;var Duo=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Pl.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(Pl.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(Pl.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(Pl.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return Pl.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);Pl.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},Ruo=Duo;var Fuo=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}},_Uu=Fuo;var Nuo=class{constructor(){this.inos={},this.paths=new Ruo,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let o=i[t];if(o&&!(n&&o[1]!==n))return o[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await Pl.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new _Uu(n)}reset(){this.inos={},this.paths=new Ruo,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,gu.ADD,i),[gu.ADD];if(i.isDirectory())return this.updateIno(t,gu.ADD_DIR,i),[gu.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,gu.UNLINK,n),[gu.UNLINK];if(n.isDirectory())return this.updateIno(t,gu.UNLINK_DIR,n),[gu.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,gu.CHANGE,i),[gu.CHANGE]);if(i.isDirectory())return this.updateIno(t,gu.UNLINK,n),this.updateIno(t,gu.ADD_DIR,i),[gu.UNLINK,gu.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,gu.UNLINK_DIR,n),this.updateIno(t,gu.ADD,i),[gu.UNLINK_DIR,gu.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,gu.UNLINK_DIR,n),this.updateIno(t,gu.ADD_DIR,i),[gu.UNLINK_DIR,gu.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?Ire.FILE:Ire.DIR;i[t]=[n.ino,o]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},kuo=Nuo;var Quo=class e extends SUu.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on($R.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on($R.CLOSE,i)),this._readyWait=new Promise(i=>this.on($R.READY,i)),this._locker=new xUu(this),this._roots=new Set,this._poller=new kuo,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Pl.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($R.CLOSE))}error(t){if(this.isClosed())return!1;let r=Pl.lang.castError(t);return this.emit($R.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit($R.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit($R.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&Pl.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&Pl.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let o of[...i])r&&o.filePath!==r||this.watcherClose(o);if(n)for(let o in this._watchers)Pl.fs.isSubPath(t,o)&&this.watchersClose(o,r,!1)}else for(let i in this._watchers)this.watchersClose(i,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let o=new CUu(this,t,r);return await o.init(),o}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let o=r.indexOf(t);r.splice(o,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Pl.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(a=>a.handler===n&&(!a.filePath||a.filePath===i)&&a.options.ignore===r.ignore&&!!a.options.native==!!r.native&&(!r.recursive||a.options.recursive)))return!0;let s=uje.default.dirname(t);for(let a=1;a<1/0;a++){if(this._watchers[s]?.find(l=>(a===1||l.options.recursive&&a<=(l.options.depth??q_e))&&l.handler===n&&(!l.filePath||l.filePath===i)&&l.options.ignore===r.ignore&&!!l.options.native==!!r.native&&(!r.recursive||l.options.recursive&&G_e&&l.options.native!==!1)))return!0;if(!G_e)break;let c=uje.default.dirname(t);if(s===c)break;s=c}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=Pl.lang.uniq(t).sort();let s;for(let a of t)if(!this.isIgnored(a,r.ignore)&&!this.watcherExists(a,r,n,i))try{let u=!r.recursive||G_e&&r.native!==!1?r:{...r,recursive:!1},l={watcher:ANn.default.watch(a,u),handler:n,options:r,folderPath:a,filePath:i},p=s=await this.watcherAdd(l,o);if(this._roots.has(i||a)){let f={...r,ignoreInitial:!0,recursive:!1},m=uje.default.dirname(a),h=a;await this.watchDirectories([m],f,n,h,p)}}catch(u){this.error(u)}return s}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||G_e&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let s=r.depth??q_e,a=r.limit??ljt,[u]=await Pl.fs.readdir(t,r.ignore,s,a,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let c=await this.watchDirectories([t],r,n,i,o);if(u.length){let l=Pl.fs.getDepth(t);for(let p of u){let d=Pl.fs.getDepth(p),f=Math.max(0,s-(d-l)),m={...r,depth:f};await this.watchDirectories([p],m,n,i,o||c)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(c,l)=>{l===t&&(u(),n())},s=new e(o),a=()=>{this._subwatchers.add(i),this.on($R.CLOSE,u),s.watchFile(t,r,o)},u=()=>{this._subwatchers.delete(i),this.removeListener($R.CLOSE,u),s.close()};return a()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=uje.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new kuo,s=await this.watchPolling(t,r,async()=>{i||!(await o.update(t,r.pollingTimeout)).length||i||(i=!0,s(),n())})}async watchPolling(t,r,n){if(this.isClosed())return Pl.lang.noop;if(this.pollerExists(t,r))return Pl.lang.noop;let i={...r,interval:r.pollingInterval??fUu},o={targetPath:t,options:r},s=()=>{this._pollers.add(o),this.on($R.CLOSE,a),ANn.default.watchFile(t,i,n)},a=()=>{this._pollers.delete(o),this.removeListener($R.CLOSE,a),ANn.default.unwatchFile(t,n)};return Pl.lang.attempt(s),()=>Pl.lang.attempt(a)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=Pl.lang.uniq(t).sort(),t.every((o,s)=>t.every((a,u)=>u===s||!Pl.fs.isSubPath(o,a))))await Promise.all(t.map(o=>this.watchPath(o,r,n)));else for(let o of t)await this.watchPath(o,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=uje.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await Pl.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let o=uje.default.dirname(t);return(await Pl.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=Pl.lang.noop){if(Pl.lang.isFunction(t))return this.watch([],{},t);if(Pl.lang.isUndefined(t))return this.watch([],r,n);if(Pl.lang.isFunction(r))return this.watch(t,{},r);if(Pl.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=Pl.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==Pl.lang.noop&&this.on($R.ALL,n),r.readdirMap=void 0,this.ready())}},yNn=Quo;DNn();qt();var ipt=require("fs/promises"),R4u=require("os"),F4u=Ae(require("path"),1),Imm=".fern",wmm="logs";function Cmm(){return"cli@4.43.3"}var mje=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Ge(Ut.of((0,R4u.homedir)()),Se.of(Imm)),r=Ge(t,Se.of(wmm));await er(r)||await(0,ipt.mkdir)(r,{recursive:!0});let i=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Ge(r,Se.of(i));let o=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${F4u.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
2202
+ `)}if(s)throw Yr.exit();if(o.warningCount>0){t.stderr.info(`${bo.warning} ${be.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(be.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${bo.success} ${be.green("All checks passed")}`)}buildJsonResponse({result:t,hasErrors:r}){let n={};return t.violations.length>0&&(n.docs=t.violations.map(i=>XX(i))),{success:!r,results:n}}};function nao(e){let t=new rao;Ra(e,"check","Validate docs configuration",(r,n)=>t.handle(r,n),r=>r.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}))}var B2u=Ae(require("net"),1),O2u=Ae(require("os"),1),_Fn=class extends Error{constructor(t){super(`${t} is locked`)}},Flt={old:new Set,young:new Set},Pom=1e3*15;var MQt,Dom=()=>{let e=O2u.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let n of r)t.add(n.address);return t},_2u=e=>new Promise((t,r)=>{let n=B2u.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),S2u=async(e,t)=>{if(e.host||e.port===0)return _2u(e);for(let r of t)try{await _2u({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},Rom=function*(e){e&&(yield*e),yield 0};async function Q_e(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let i=e.exclude;if(typeof i[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let o of i){if(typeof o!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(o))throw new TypeError(`Number ${o} in the exclude option is not a safe integer and can't be used`)}r=new Set(i)}MQt===void 0&&(MQt=setTimeout(()=>{MQt=void 0,Flt.old=Flt.young,Flt.young=new Set},Pom),MQt.unref&&MQt.unref());let n=Dom();for(let i of Rom(t))try{if(r.has(i))continue;let o=await S2u({...e,port:i},n);for(;Flt.old.has(o)||Flt.young.has(o);){if(i!==0)throw new _Fn(i);o=await S2u({...e,port:i},n)}return Flt.young.add(o),o}catch(o){if(!["EADDRINUSE","EACCES"].includes(o.code)&&!(o instanceof _Fn))throw o}throw new Error("No available ports found")}St();qg();qt();var W6u=Ae(sao(),1),$6u=Ae(fNn(),1),Jkn=require("fs/promises"),H6u=Ae(require("http"),1),K6u=Ae(require("path"),1);var SUu=require("events"),ANn=Ae(require("fs"),1),uje=Ae(require("path"),1);var cUu=Ae(require("os"),1),lUu=300,q_e=20,ljt=1e7,pUu=cUu.default.platform();var Hfm=pUu==="darwin",xuo=pUu==="win32",G_e=Hfm||xuo,fUu=3e3,dUu=2e4,_uo=1250;var Ire;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(Ire||(Ire={}));var aje;(function(e){e.CHANGE="change",e.RENAME="rename"})(aje||(aje={}));var pjt;(function(e){e.CHANGE="change",e.ERROR="error"})(pjt||(pjt={}));var gu;(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"})(gu||(gu={}));var $R;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})($R||($R={}));var Kfm=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),s,a,u=0,c=0,l=()=>{let E=Date.now(),I=E-u,w=E-c,x=I>=t||w>=o;return[E,x]},p=E=>{if(c=E,!s)return;let I=s;s=void 0,e.apply(void 0,I)},d=()=>{b(0)},f=()=>{a&&(d(),p(Date.now()))},m=E=>{if(c=E,n)return p(E)},h=E=>{if(i&&s)return p(E);s=void 0},g=()=>{a=void 0;let[E,I]=l();return I?h(E):A(E)},A=E=>{let I=E-u,w=E-c,x=t-I,C=o-w,_=Math.min(x,C);return b(_)},b=E=>{a&&clearTimeout(a),!(E<=0)&&(a=setTimeout(g,E))},v=(...E)=>{let[I,w]=l(),x=!!a;if(s=E,u=I,(w||!a)&&b(t),w)return x?p(I):m(I)};return v.cancel=d,v.flush=f,v},dNn=Kfm;var Tuo=Ae(require("fs"),1),hNn=Ae(require("path"),1);var Yf=Ae(require("fs"),1),mB=require("util");var Ope=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},wre=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var Suo=Ae(require("process"),1),mUu=Suo.default.getuid?!Suo.default.getuid():!1,hUu=1e4,K2=()=>{};var fjt={isChangeErrorOk:e=>{if(!fjt.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!mUu&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!fjt.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(!fjt.isNodeError(e))throw e;if(!fjt.isChangeErrorOk(e))throw e}},Vv=fjt;var Buo=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=hUu,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(n),n=()=>t(r);this.add(n)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},gUu=new Buo;var Tpe=(e,t)=>function(n){return function i(...o){return gUu.schedule().then(s=>{let a=c=>(s(),c),u=c=>{if(s(),Date.now()>=n)throw c;if(t(c)){let l=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,l)).then(()=>i.apply(void 0,o))}throw c};return e.apply(void 0,o).then(a,u)})}},Ppe=(e,t)=>function(n){return function i(...o){try{return e.apply(void 0,o)}catch(s){if(Date.now()>n)throw s;if(t(s))return i.apply(void 0,o);throw s}}};var Jfm={attempt:{chmod:Ope((0,mB.promisify)(Yf.default.chmod),Vv.onChangeError),chown:Ope((0,mB.promisify)(Yf.default.chown),Vv.onChangeError),close:Ope((0,mB.promisify)(Yf.default.close),K2),fsync:Ope((0,mB.promisify)(Yf.default.fsync),K2),mkdir:Ope((0,mB.promisify)(Yf.default.mkdir),K2),realpath:Ope((0,mB.promisify)(Yf.default.realpath),K2),stat:Ope((0,mB.promisify)(Yf.default.stat),K2),unlink:Ope((0,mB.promisify)(Yf.default.unlink),K2),chmodSync:wre(Yf.default.chmodSync,Vv.onChangeError),chownSync:wre(Yf.default.chownSync,Vv.onChangeError),closeSync:wre(Yf.default.closeSync,K2),existsSync:wre(Yf.default.existsSync,K2),fsyncSync:wre(Yf.default.fsync,K2),mkdirSync:wre(Yf.default.mkdirSync,K2),realpathSync:wre(Yf.default.realpathSync,K2),statSync:wre(Yf.default.statSync,K2),unlinkSync:wre(Yf.default.unlinkSync,K2)},retry:{close:Tpe((0,mB.promisify)(Yf.default.close),Vv.isRetriableError),fsync:Tpe((0,mB.promisify)(Yf.default.fsync),Vv.isRetriableError),open:Tpe((0,mB.promisify)(Yf.default.open),Vv.isRetriableError),readFile:Tpe((0,mB.promisify)(Yf.default.readFile),Vv.isRetriableError),rename:Tpe((0,mB.promisify)(Yf.default.rename),Vv.isRetriableError),stat:Tpe((0,mB.promisify)(Yf.default.stat),Vv.isRetriableError),write:Tpe((0,mB.promisify)(Yf.default.write),Vv.isRetriableError),writeFile:Tpe((0,mB.promisify)(Yf.default.writeFile),Vv.isRetriableError),closeSync:Ppe(Yf.default.closeSync,Vv.isRetriableError),fsyncSync:Ppe(Yf.default.fsyncSync,Vv.isRetriableError),openSync:Ppe(Yf.default.openSync,Vv.isRetriableError),readFileSync:Ppe(Yf.default.readFileSync,Vv.isRetriableError),renameSync:Ppe(Yf.default.renameSync,Vv.isRetriableError),statSync:Ppe(Yf.default.statSync,Vv.isRetriableError),writeSync:Ppe(Yf.default.writeSync,Vv.isRetriableError),writeFileSync:Ppe(Yf.default.writeFileSync,Vv.isRetriableError)}},AUu=Jfm;var mNn=Ae(require("fs"),1),djt=Ae(require("path"),1);var Ouo=()=>{};var Yfm=()=>{let e=Ouo,t=Ouo,r=!1,n=!1;return{promise:new Promise((u,c)=>{e=l=>(r=!0,u(l)),t=l=>(n=!0,c(l))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},yUu=Yfm;var Xfm=()=>{let{promise:e,resolve:t,isPending:r}=yUu(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},bUu=Xfm;var EUu={then:e=>{e()}};var vUu=e=>Array.isArray(e)?e:[e],IUu=e=>typeof e=="function";var Zfm=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],s=vUu(o).map(J=>IUu(J)?J:X=>J.test(X)),a=J=>s.some(X=>X(J)),u=t?.signal??{aborted:!1},c=t?.onDirents||(()=>{}),l=[],p=new Set,d={},f=[],m=new Set,h={},g=[],A=new Set,b={},v={},E=new Set,I={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},w={directories:l,directoriesNames:p,directoriesNamesToPaths:d,files:f,filesNames:m,filesNamesToPaths:h,symlinks:g,symlinksNames:A,symlinksNamesToPaths:b,map:v},{promise:x,increment:C,decrement:_}=bUu(),D=0,U=(J,X,ge,he)=>{E.has(X)||D>=i||(D+=1,J.directories.push(X),J.directoriesNames.add(ge),l.push(X),p.add(ge),d.propertyIsEnumerable(ge)||(d[ge]=[]),d[ge].push(X),E.add(X),!(he>=n)&&(D>=i||H(X,he+1)))},q=(J,X,ge)=>{E.has(X)||D>=i||(D+=1,J.files.push(X),J.filesNames.add(ge),f.push(X),m.add(ge),h.propertyIsEnumerable(ge)||(h[ge]=[]),h[ge].push(X),E.add(X))},z=(J,X,ge,he)=>{E.has(X)||D>=i||(D+=1,J.symlinks.push(X),J.symlinksNames.add(ge),g.push(X),A.add(ge),b.propertyIsEnumerable(ge)||(b[ge]=[]),b[ge].push(X),E.add(X),r&&(he>=n||D>=i||Ee(X,he+1)))},Y=(J,X,ge,he,Ce)=>{u.aborted||a(X)||(he.isDirectory()?U(J,X,ge,Ce):he.isFile()?q(J,X,ge):he.isSymbolicLink()&&z(J,X,ge,Ce))},ne=(J,X,ge,he)=>{if(u.aborted)return;let Ce=X===djt.default.sep?"":djt.default.sep,_e=ge.name,ce=`${X}${Ce}${_e}`;a(ce)||(ge.isDirectory()?U(J,ce,_e,he):ge.isFile()?q(J,ce,_e):ge.isSymbolicLink()&&z(J,ce,_e,he))},V=(J,X,ge,he)=>{for(let Ce=0,_e=ge.length;Ce<_e;Ce++)ne(J,X,ge[Ce],he)},H=(J,X)=>{u.aborted||X>n||D>=i||(C(),mNn.default.readdir(J,{withFileTypes:!0},(ge,he)=>{if(ge||u.aborted||!he.length)return _();(c(he)||EUu).then(()=>{let _e=v[J]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};V(_e,J,he,X),_()})}))},Ee=(J,X)=>{C(),mNn.default.realpath(J,(ge,he)=>{if(ge||u.aborted)return _();mNn.default.stat(he,(Ce,_e)=>{if(Ce||u.aborted)return _();let ce=djt.default.basename(he),se=v[J]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};Y(se,he,ce,_e,X),_()})})};return(async(J,X=1)=>(J=djt.default.normalize(J),E.add(J),H(J,X),await x,u.aborted?I:w))(e)},wUu=Zfm;var Cre={lang:{debounce:dNn,attempt:e=>{try{return e()}catch(t){return Cre.lang.castError(t)}},castArray:e=>Cre.lang.isArray(e)?e:[e],castError:e=>Cre.lang.isError(e)?e:Cre.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(Cre.lang.isNaN(e))return Cre.lang.isNaN(t);if(Cre.lang.isPrimitive(e)||Cre.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(hNn.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Tuo.default.realpathSync.native(e):Tuo.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===hNn.default.sep&&t.length-e.length>hNn.default.sep.length,poll:(e,t=dUu)=>AUu.retry.stat(t)(e,{bigint:!0}).catch(Cre.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,o)=>{if(o&&r===1&&e in o){let s=o[e];return[s.directories,s.files]}else{let s=await wUu(e,{depth:r,limit:n,ignore:t,signal:i});return[s.directories,s.files]}}}},Pl=Cre;var gNn=Ae(require("path"),1);var Puo=class{constructor(t,r,n){this.base=n,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Pl.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=lUu){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(a,u)=>{let c=this.options.ignoreInitial?[]:a,l=await this.eventsPopulate([...u]),p=this.eventsDeduplicate([...c,...l]);this.onTargetEvents(p)},s=Pl.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(a,u="",c=!1)=>{c?await this.eventsPopulate([u],n,!0):i.add(u),r.then(s)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,s]=i,a=r[s];return o===a||o===gu.CHANGE&&a===gu.ADD||(r[s]=o,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let o=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(o.map(async s=>{r.push([s,i]),s===gu.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):s===gu.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let o=this.options.recursive?this.options.depth??q_e:Math.min(1,this.options.depth??q_e),s=this.options.limit??ljt,[a,u]=await Pl.fs.readdir(r,this.options.ignore,o,s,this.watcher._closeSignal),c=[...a,...u];return await Promise.all(c.map(l=>{if(!this.watcher.isIgnored(l,this.options.ignore)&&!t.includes(l))return this.eventsPopulate([l],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())Pl.fs.isSubPath(r,o)&&(t.includes(o)||await this.eventsPopulate([o],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(gu.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!G_e&&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(gu.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(gu.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(gNn.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(gu.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(gNn.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(gu.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===gu.ADD?this.onTargetAdd(n):r===gu.ADD_DIR?this.onTargetAddDir(n):r===gu.CHANGE?this.onTargetChange(n):r===gu.UNLINK?this.onTargetUnlink(n):r===gu.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=aje.CHANGE,r){if(this.watcher.isClosed())return;let n=gNn.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){xuo&&t.code==="EPERM"?this.onWatcherChange(aje.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(pjt.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(pjt.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(aje.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&G_e&&this.options.native!==!1?this.options.depth??q_e:Math.min(1,this.options.depth??q_e),n=this.options.limit??ljt,[i,o]=await Pl.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),s=[this.folderPath,...i,...o];await Promise.all(s.map(a=>{if(!this.watcher._poller.stats.has(a)&&!this.watcher.isIgnored(a,this.options.ignore))return this.onWatcherEvent(aje.CHANGE,a,t)}))}}},CUu=Puo;var HR={interval:100,intervalId:void 0,fns:new Map,init:()=>{HR.intervalId||(HR.intervalId=setInterval(HR.resolve,HR.interval))},reset:()=>{HR.intervalId&&(clearInterval(HR.intervalId),delete HR.intervalId)},add:(e,t)=>{HR.fns.set(e,Date.now()+t),HR.init()},remove:e=>{HR.fns.delete(e)},resolve:()=>{if(!HR.fns.size)return HR.reset();let e=Date.now();for(let[t,r]of HR.fns)r>=e||(HR.remove(t),t())}},mjt=HR;var hjt=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=_uo){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{let p=this._watcher._poller.paths.find(n||-1,d=>d!==i);if(p&&p!==i){if(Pl.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return a();let u=()=>{s.add.delete(n),mjt.remove(c)},c=()=>{u(),a()};mjt.add(c,r);let l=()=>{let p=s.unlink.get(n);if(!p)return;u();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};s.add.set(n,l),l()}getLockUnlink(t,r=_uo){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{this._watcher.event(o.unlink,i)};if(!n)return a();let u=()=>{s.unlink.delete(n),mjt.remove(c)},c=()=>{u(),a()};mjt.add(c,r);let l=()=>(u(),i);s.unlink.set(n,l),s.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,gu.ADD,Ire.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,gu.ADD_DIR,Ire.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,gu.UNLINK,Ire.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,gu.UNLINK_DIR,Ire.DIR);return this.getLockUnlink({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};hjt.DIR_EVENTS={add:gu.ADD_DIR,rename:gu.RENAME_DIR,unlink:gu.UNLINK_DIR};hjt.FILE_EVENTS={add:gu.ADD,change:gu.CHANGE,rename:gu.RENAME,unlink:gu.UNLINK};var xUu=hjt;var Duo=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Pl.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(Pl.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(Pl.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(Pl.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return Pl.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);Pl.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},Ruo=Duo;var Fuo=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}},_Uu=Fuo;var Nuo=class{constructor(){this.inos={},this.paths=new Ruo,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let o=i[t];if(o&&!(n&&o[1]!==n))return o[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await Pl.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new _Uu(n)}reset(){this.inos={},this.paths=new Ruo,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,gu.ADD,i),[gu.ADD];if(i.isDirectory())return this.updateIno(t,gu.ADD_DIR,i),[gu.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,gu.UNLINK,n),[gu.UNLINK];if(n.isDirectory())return this.updateIno(t,gu.UNLINK_DIR,n),[gu.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,gu.CHANGE,i),[gu.CHANGE]);if(i.isDirectory())return this.updateIno(t,gu.UNLINK,n),this.updateIno(t,gu.ADD_DIR,i),[gu.UNLINK,gu.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,gu.UNLINK_DIR,n),this.updateIno(t,gu.ADD,i),[gu.UNLINK_DIR,gu.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,gu.UNLINK_DIR,n),this.updateIno(t,gu.ADD_DIR,i),[gu.UNLINK_DIR,gu.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?Ire.FILE:Ire.DIR;i[t]=[n.ino,o]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},kuo=Nuo;var Quo=class e extends SUu.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on($R.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on($R.CLOSE,i)),this._readyWait=new Promise(i=>this.on($R.READY,i)),this._locker=new xUu(this),this._roots=new Set,this._poller=new kuo,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Pl.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($R.CLOSE))}error(t){if(this.isClosed())return!1;let r=Pl.lang.castError(t);return this.emit($R.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit($R.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit($R.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&Pl.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&Pl.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let o of[...i])r&&o.filePath!==r||this.watcherClose(o);if(n)for(let o in this._watchers)Pl.fs.isSubPath(t,o)&&this.watchersClose(o,r,!1)}else for(let i in this._watchers)this.watchersClose(i,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let o=new CUu(this,t,r);return await o.init(),o}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let o=r.indexOf(t);r.splice(o,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Pl.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(a=>a.handler===n&&(!a.filePath||a.filePath===i)&&a.options.ignore===r.ignore&&!!a.options.native==!!r.native&&(!r.recursive||a.options.recursive)))return!0;let s=uje.default.dirname(t);for(let a=1;a<1/0;a++){if(this._watchers[s]?.find(l=>(a===1||l.options.recursive&&a<=(l.options.depth??q_e))&&l.handler===n&&(!l.filePath||l.filePath===i)&&l.options.ignore===r.ignore&&!!l.options.native==!!r.native&&(!r.recursive||l.options.recursive&&G_e&&l.options.native!==!1)))return!0;if(!G_e)break;let c=uje.default.dirname(t);if(s===c)break;s=c}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=Pl.lang.uniq(t).sort();let s;for(let a of t)if(!this.isIgnored(a,r.ignore)&&!this.watcherExists(a,r,n,i))try{let u=!r.recursive||G_e&&r.native!==!1?r:{...r,recursive:!1},l={watcher:ANn.default.watch(a,u),handler:n,options:r,folderPath:a,filePath:i},p=s=await this.watcherAdd(l,o);if(this._roots.has(i||a)){let f={...r,ignoreInitial:!0,recursive:!1},m=uje.default.dirname(a),h=a;await this.watchDirectories([m],f,n,h,p)}}catch(u){this.error(u)}return s}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||G_e&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let s=r.depth??q_e,a=r.limit??ljt,[u]=await Pl.fs.readdir(t,r.ignore,s,a,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let c=await this.watchDirectories([t],r,n,i,o);if(u.length){let l=Pl.fs.getDepth(t);for(let p of u){let d=Pl.fs.getDepth(p),f=Math.max(0,s-(d-l)),m={...r,depth:f};await this.watchDirectories([p],m,n,i,o||c)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(c,l)=>{l===t&&(u(),n())},s=new e(o),a=()=>{this._subwatchers.add(i),this.on($R.CLOSE,u),s.watchFile(t,r,o)},u=()=>{this._subwatchers.delete(i),this.removeListener($R.CLOSE,u),s.close()};return a()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=uje.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new kuo,s=await this.watchPolling(t,r,async()=>{i||!(await o.update(t,r.pollingTimeout)).length||i||(i=!0,s(),n())})}async watchPolling(t,r,n){if(this.isClosed())return Pl.lang.noop;if(this.pollerExists(t,r))return Pl.lang.noop;let i={...r,interval:r.pollingInterval??fUu},o={targetPath:t,options:r},s=()=>{this._pollers.add(o),this.on($R.CLOSE,a),ANn.default.watchFile(t,i,n)},a=()=>{this._pollers.delete(o),this.removeListener($R.CLOSE,a),ANn.default.unwatchFile(t,n)};return Pl.lang.attempt(s),()=>Pl.lang.attempt(a)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=Pl.lang.uniq(t).sort(),t.every((o,s)=>t.every((a,u)=>u===s||!Pl.fs.isSubPath(o,a))))await Promise.all(t.map(o=>this.watchPath(o,r,n)));else for(let o of t)await this.watchPath(o,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=uje.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await Pl.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let o=uje.default.dirname(t);return(await Pl.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=Pl.lang.noop){if(Pl.lang.isFunction(t))return this.watch([],{},t);if(Pl.lang.isUndefined(t))return this.watch([],r,n);if(Pl.lang.isFunction(r))return this.watch(t,{},r);if(Pl.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=Pl.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==Pl.lang.noop&&this.on($R.ALL,n),r.readdirMap=void 0,this.ready())}},yNn=Quo;DNn();qt();var ipt=require("fs/promises"),R4u=require("os"),F4u=Ae(require("path"),1),Imm=".fern",wmm="logs";function Cmm(){return"cli@4.43.4"}var mje=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=Ge(Ut.of((0,R4u.homedir)()),Se.of(Imm)),r=Ge(t,Se.of(wmm));await er(r)||await(0,ipt.mkdir)(r,{recursive:!0});let i=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Ge(r,Se.of(i));let o=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${F4u.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
2203
2203
  `);await(0,ipt.writeFile)(this.logFilePath,o,"utf-8"),this.initialized=!0}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
2204
2204
  `;try{await(0,ipt.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 n={timestamp:t.timestamp,source:Cmm(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(n)}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 n={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliDocsGeneration(t,r){let n={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliValidation(t,r){let n={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(n)}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 oco={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function N4u(e){let t=xmm();if(t==null)return;let{port:r,debugLogger:n,getDocsLoadResponse:i}=e,o=new Map;function s(u){let c=JSON.stringify(u),l=[];for(let[p]of o)try{p.send(c)}catch{l.push(p)}for(let p of l){let d=o.get(p);d&&(clearInterval(d.pingInterval),o.delete(p))}}let a=t.serve({port:r,fetch(u,c){if(u.method==="OPTIONS")return new Response(null,{status:204,headers:oco});let l=new URL(u.url);if(u.headers.get("upgrade")?.toLowerCase()==="websocket"){c.upgrade(u,{data:{connectionId:`${Date.now()}`}});return}if(u.method==="POST"&&l.pathname==="/v2/registry/docs/load-with-url")return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...oco}});let p=/^\/_local\/(.*)/.exec(l.pathname);return u.method==="GET"&&p!=null?new Response(t.file(`/${p[1]}`),{headers:oco}):new Response("Not Found",{status:404})},websocket:{open(u){let{connectionId:c}=u.data,l=setInterval(()=>{let p=o.get(u);if(!p)return;let d=Date.now();if(d-p.lastPong>9e4){u.close();return}try{u.send(JSON.stringify({type:"ping",timestamp:d}))}catch{u.close()}},3e4);o.set(u,{pingInterval:l,lastPong:Date.now()});try{u.send(JSON.stringify({type:"connected",connectionId:c}))}catch{}},message(u,c){try{let l=JSON.parse(c.toString());if(l.type==="pong"){let p=o.get(u);p&&(p.lastPong=Date.now())}else mje.isMetricsMessage(l)&&n.logFrontendMetrics(l)}catch{}},close(u){let c=o.get(u);c&&(clearInterval(c.pingInterval),o.delete(u))}}});return{sendData:s,stop:u=>a.stop(u)}}function xmm(){return globalThis.Bun}qt();var Mlo=Ae(mco(),1),j6u=Ae(Slo(),1),J2=require("fs/promises"),M6u=require("os"),L6u=Ae(YC(),1),U6u=Ae(k6u(),1),qkn=process.platform==="win32",jlo=be.cyan("[docs]:"),tbm="etag",rbm=23,Q6u=e=>e.padEnd(rbm," "),nbm="preview",ibm="app-preview",obm="bundle",sbm=".next",abm="standalone",ubm=".fern",cbm="packages/fern-docs/bundle/.next/server/instrumentation.js",lbm=".npmrc",pbm=".pnpmfile.cjs",fbm="pnpm-workspace.yaml",dbm='Cannot find matching keyid: {"signatures":';function mbm(){return Ge(Ut.of((0,M6u.homedir)()),Se.of(ubm))}function Ipt({app:e=!1}){return Ge(mbm(),Se.of(e?ibm:nbm))}function rSe({app:e=!1}){return Ge(Ipt({app:e}),Se.of(e?sbm:obm))}function Hjt({app:e=!1}){return Ge(rSe({app:e}),Se.of(abm))}function hbm({app:e=!1}){return Ge(Hjt({app:e}),Se.of(cbm))}function gbm({app:e=!1}){return Ge(Hjt({app:e}),Se.of(fbm))}function Abm({app:e=!1}){return Ge(Hjt({app:e}),Se.of(pbm))}function ybm({app:e=!1}){return Ge(Hjt({app:e}),Se.of(lbm))}function wje(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function bbm({app:e=!1}){return Ge(Ipt({app:e}),Se.of(tbm))}var Ebm=`module.exports = {
2205
2205
  hooks: {
@@ -2240,7 +2240,7 @@ Please ensure you have membership at https://dashboard.buildwithfern.com, and as
2240
2240
 
2241
2241
  Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`);case"UnavailableError":return t.failAndThrow("Failed to publish docs. Please try again later or reach out to Fern support at support@buildwithfern.com.");default:return t.failAndThrow("Failed to publish docs.",e)}}function fvm(e,t){let n=e?.content;if(n?.reason==="status-code"){let i=n.statusCode;if(i===401||i===403)return`${`You do not have permission to publish docs to organization '${t}'. Please run 'fern login' to ensure you are logged in with the correct account.`}
2242
2242
 
2243
- Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`}}function dvm(e){try{return new URL(LR(e)).pathname}catch{return}}async function mvm({fdr:e,workspace:t,organization:r,context:n,snippetsConfig:i}){if(!t)return;let o=await hvm({fdr:e,workspace:t,snippetsConfig:i,context:n});if(Object.keys(o).length===0){n.logger.debug("[SDK Dynamic IR] No snippet configs found, skipping S3 check");return}try{let s=await e.api.v1.register.checkSdkDynamicIrExists({orgId:Sr.OrgId(r),snippetConfiguration:o});if(!s.ok||!s.body){n.logger.debug("[SDK Dynamic IR] API call failed or returned empty body");return}let a=s.body.existingDynamicIrs;if(Object.keys(a).length===0){n.logger.debug("[SDK Dynamic IR] No existing SDK dynamic IRs found in S3");return}let u={};for(let[c,l]of Object.entries(a))try{n.logger.debug(`Downloading existing SDK dynamic IR for ${c}...`);let p=await fetch(l.downloadUrl);if(p.ok){let d=await p.json();u[c]={dynamicIR:d},n.logger.debug(`Successfully downloaded SDK dynamic IR for ${c}`)}else n.logger.warn(`Failed to download SDK dynamic IR for ${c}: ${p.status}`)}catch(p){n.logger.warn(`Error downloading SDK dynamic IR for ${c}: ${p}`)}return Object.keys(u).length>0?u:void 0}catch(s){n.logger.debug(`Error checking for existing SDK dynamic IRs: ${s}`);return}}function SGu(e){return e.replace(/^https:\/\//,"")}async function hvm({fdr:e,workspace:t,snippetsConfig:r,context:n}){let i={},o=[{language:"typescript",snippetName:r.typescriptSdk?.package,explicitVersion:r.typescriptSdk?.version},{language:"python",snippetName:r.pythonSdk?.package,explicitVersion:r.pythonSdk?.version},{language:"java",snippetName:r.javaSdk?.coordinate,explicitVersion:r.javaSdk?.version},{language:"go",snippetName:r.goSdk?.githubRepo&&SGu(r.goSdk?.githubRepo),explicitVersion:r.goSdk?.version},{language:"csharp",snippetName:r.csharpSdk?.package,explicitVersion:r.csharpSdk?.version},{language:"ruby",snippetName:r.rubySdk?.gem,explicitVersion:r.rubySdk?.version},{language:"php",snippetName:r.phpSdk?.package,explicitVersion:r.phpSdk?.version},{language:"swift",snippetName:r.swiftSdk?.package,explicitVersion:r.swiftSdk?.version},{language:"rust",snippetName:r.rustSdk?.package,explicitVersion:r.rustSdk?.version}];for(let s of o){if(!s.snippetName)continue;let a=s.explicitVersion;a||(a=(await gvm({fdr:e,workspace:t,language:s.language,snippetName:s.snippetName,context:n}))?.version),i[s.language]={packageName:s.snippetName,version:a},a||n.logger.debug(`[SDK Dynamic IR] ${s.language}: no version specified, will use latest`)}return i}async function gvm({fdr:e,workspace:t,language:r,snippetName:n,context:i}){let o;switch(r){case"csharp":o="Csharp";break;case"go":o="Go";break;case"java":o="Java";break;case"python":o="Python";break;case"ruby":o="Ruby";break;case"typescript":o="TypeScript";break;case"php":o="Php";break;case"swift":o="Swift";break;default:return}let s,a,u;if(t.generatorsConfiguration?.groups){let c=[];for(let l of t.generatorsConfiguration.groups)for(let p of l.generators)if(p.language===r){let d=vn.getPackageName({generatorInvocation:p});d&&c.push(d),!a&&d&&(a=d,u=p.name,p.outputMode.type==="githubV2"&&(s=`${p.outputMode.githubV2.owner}/${p.outputMode.githubV2.repo}`))}}if(!a){i.logger.debug(`[SDK Dynamic IR] ${r}: no generator found with a package name`);return}try{let c=await e.sdks.versions.computeSemanticVersion({githubRepository:s,language:o,package:a});if(!c.ok){i.logger.debug(`[SDK Dynamic IR] ${r}: version computation failed for package "${a}"`);return}return i.logger.debug(`[SDK Dynamic IR] ${r}: computed version ${c.body.version} for package "${a}"`),{version:c.body.version,generatorPackage:a}}catch(c){i.logger.debug(`[SDK Dynamic IR] ${r}: error computing version: ${c}`);return}}async function Avm({workspace:e,organization:t,context:r,snippetsConfig:n,skipLanguages:i=new Set}){let o={};if(!e)return;let s={typescript:n.typescriptSdk?.package,python:n.pythonSdk?.package,java:n.javaSdk?.coordinate,go:n.goSdk?.githubRepo&&SGu(n.goSdk?.githubRepo),csharp:n.csharpSdk?.package,ruby:n.rubySdk?.gem,php:n.phpSdk?.package,swift:n.swiftSdk?.package,rust:n.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let a of e.generatorsConfiguration.groups)for(let u of a.generators){let c=Cje({apiName:e.workspaceName??"",organization:t,generatorInvocation:u}),l="";if(c?.outputConfig.type==="publish")switch(c.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":l=c.outputConfig.value.packageName;break;case"maven":l=c.outputConfig.value.coordinate;break;case"go":l=c.outputConfig.value.repoUrl;break;case"swift":l=c.outputConfig.value.repoUrl;break;case"crates":l=c.outputConfig.value.packageName;break}if(u.language==="php"&&u.config&&typeof u.config=="object"&&"packageName"in u.config&&(l=u.config.packageName??""),!!u.language){if(i.has(u.language)){r.logger.debug(`Skipping dynamic IR generation for ${u.language} (using existing SDK dynamic IR)`);continue}if(u.language&&s[u.language]===l){let p=Nh({workspace:e,generationLanguage:u.language,keywords:void 0,smartCasing:u.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:l,version:void 0,context:r,sourceResolver:new Rm(r,e),dynamicGeneratorConfig:c}),d=gFe({ir:p,disableExamples:!0,smartCasing:u.smartCasing,generationLanguage:u.language,generatorConfig:c});d?o[u.language]={dynamicIR:d}:r.logger.debug(`Failed to create dynamic IR for ${u.language}`)}}}for(let[a,u]of Object.entries(s))a&&u&&!Object.keys(o).includes(a)&&!i.has(a)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${a} SDK snippets because of unknown package \`${u}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${u} package.`),r.logger.warn());if(Object.keys(o).length>0)return o}async function yvm({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:n}){if(Object.keys(t).length>0)for(let[i,o]of Object.entries(t)){let s=e[i]?.dynamicIR;if(s){let a=JSON.stringify(s);(await fetch(o.uploadUrl,{method:"PUT",body:a,headers:{"Content-Type":"application/octet-stream","Content-Length":Buffer.byteLength(a,"utf8").toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${n}:${i}`):r.logger.warn(`Failed to upload dynamic IR for ${n}:${i}`)}else r.logger.warn(`Could not find matching dynamic IR to upload for ${n}:${i}`)}}async function bvm({docsDefinition:e,isPreview:t,context:r}){e.config.aiChatConfig==null||t||r.logger.warn(be.yellow("Enabling Ask Fern from docs.yml is deprecated. Please enable it from the Fern dashboard instead."))}function Evm(e,t){if(e)return{enabled:!0,model:process.env.FERN_AI_MODEL||"gpt-4o-mini",maxRetries:parseInt(process.env.FERN_AI_MAX_RETRIES||"3"),requestTimeoutMs:parseInt(process.env.FERN_AI_TIMEOUT_MS||"25000"),styleInstructions:t}}function vvm(e){let t=e,r=t?.content;return{errorType:t?.error,statusCode:t?.statusCode??r?.statusCode,reason:r?.reason,errorMessage:r?.errorMessage??r?.message,body:r?.body,cause:r?.cause,rawError:e}}var rMt=[60*1e3,300*1e3,300*1e3];async function nMt({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:n,context:i,token:o,instanceUrl:s,preview:a,previewId:u,disableTemplates:c,skipUpload:l,cliVersion:p,ciSource:d}){let f=a&&!n.config.settings?.substituteEnvVars;n.config=Zy(n.config,{onError:b=>i.failAndThrow(b)},{substituteAsEmpty:f});let m=n.config.instances;if(m.length===0){i.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(m.length>1&&s==null){i.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${m[0]?.url})`);return}let h=m.find(b=>b.url===s)??m[0];if(h==null){i.failAndThrow(`No docs instance with url ${s}. Failed to register.`);return}let g=[];h.customDomain!=null&&(typeof h.customDomain=="string"?g.push(h.customDomain):Array.isArray(h.customDomain)&&g.push(...h.customDomain)),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${h.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let A;return await i.runInteractiveTask({name:h.url},async()=>{let b=performance.now(),v=()=>_Gu({docsWorkspace:n,customDomains:g,domain:h.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,previewId:u,editThisPage:h.editThisPage,isPrivate:h.private,disableTemplates:c,skipUpload:l,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:h.audiences?Array.isArray(h.audiences)?h.audiences:[h.audiences]:void 0,docsUrl:h.url,cliVersion:p,ciSource:d});for(let I=0;;I++)try{A=await v();break}catch(w){if(!(w instanceof _pt)||I>=rMt.length){if(w instanceof _pt)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.");throw w}let x=rMt[I]??rMt[rMt.length-1]??6e4,C=x/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${C} minute${C===1?"":"s"} (attempt ${I+1}/${rMt.length})...`),await new Promise(_=>setTimeout(_,x))}let E=performance.now()-b;i.logger.debug(`Docs publishing completed in ${E.toFixed(0)}ms`)}),A}var L2n=class{context;task;project;docsWorkspace;ossWorkspaces;token;constructor({context:t,task:r,project:n,docsWorkspace:i,ossWorkspaces:o,token:s}){this.context=t,this.task=r,this.project=n,this.docsWorkspace=i,this.ossWorkspaces=o,this.token=s}async publish({instanceUrl:t,preview:r,skipUpload:n}){let i=new Lh({context:this.context,task:this.task});try{let o=await nMt({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:i,token:this.token,instanceUrl:t,preview:r,previewId:void 0,disableTemplates:void 0,skipUpload:n,cliVersion:"4.43.3"});return i.getResult()===ef.Failure?{success:!1}:{success:!0,url:o}}catch(o){return{success:!1,error:Oi(o)}}}};St();var Spt=class e{static MAX_DISPLAYED_LOGS_TTY=10;static URL_PATTERN=/https?:\/\/[^\s]+/;context;stream;tasks={};taskOrder=[];startTime;isRegistered=!1;constructor(t){this.context=t.context,this.stream=t.stream??process.stderr}addTask(t){let r={...t,status:t.status??"pending"};return this.tasks[t.id]=r,this.taskOrder.push(t.id),this}async start(t){return this.startTime=Date.now(),t!=null&&await this.context.ttyAwareLogger.takeOverTerminal(()=>{this.stream.write(`
2243
+ Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`}}function dvm(e){try{return new URL(LR(e)).pathname}catch{return}}async function mvm({fdr:e,workspace:t,organization:r,context:n,snippetsConfig:i}){if(!t)return;let o=await hvm({fdr:e,workspace:t,snippetsConfig:i,context:n});if(Object.keys(o).length===0){n.logger.debug("[SDK Dynamic IR] No snippet configs found, skipping S3 check");return}try{let s=await e.api.v1.register.checkSdkDynamicIrExists({orgId:Sr.OrgId(r),snippetConfiguration:o});if(!s.ok||!s.body){n.logger.debug("[SDK Dynamic IR] API call failed or returned empty body");return}let a=s.body.existingDynamicIrs;if(Object.keys(a).length===0){n.logger.debug("[SDK Dynamic IR] No existing SDK dynamic IRs found in S3");return}let u={};for(let[c,l]of Object.entries(a))try{n.logger.debug(`Downloading existing SDK dynamic IR for ${c}...`);let p=await fetch(l.downloadUrl);if(p.ok){let d=await p.json();u[c]={dynamicIR:d},n.logger.debug(`Successfully downloaded SDK dynamic IR for ${c}`)}else n.logger.warn(`Failed to download SDK dynamic IR for ${c}: ${p.status}`)}catch(p){n.logger.warn(`Error downloading SDK dynamic IR for ${c}: ${p}`)}return Object.keys(u).length>0?u:void 0}catch(s){n.logger.debug(`Error checking for existing SDK dynamic IRs: ${s}`);return}}function SGu(e){return e.replace(/^https:\/\//,"")}async function hvm({fdr:e,workspace:t,snippetsConfig:r,context:n}){let i={},o=[{language:"typescript",snippetName:r.typescriptSdk?.package,explicitVersion:r.typescriptSdk?.version},{language:"python",snippetName:r.pythonSdk?.package,explicitVersion:r.pythonSdk?.version},{language:"java",snippetName:r.javaSdk?.coordinate,explicitVersion:r.javaSdk?.version},{language:"go",snippetName:r.goSdk?.githubRepo&&SGu(r.goSdk?.githubRepo),explicitVersion:r.goSdk?.version},{language:"csharp",snippetName:r.csharpSdk?.package,explicitVersion:r.csharpSdk?.version},{language:"ruby",snippetName:r.rubySdk?.gem,explicitVersion:r.rubySdk?.version},{language:"php",snippetName:r.phpSdk?.package,explicitVersion:r.phpSdk?.version},{language:"swift",snippetName:r.swiftSdk?.package,explicitVersion:r.swiftSdk?.version},{language:"rust",snippetName:r.rustSdk?.package,explicitVersion:r.rustSdk?.version}];for(let s of o){if(!s.snippetName)continue;let a=s.explicitVersion;a||(a=(await gvm({fdr:e,workspace:t,language:s.language,snippetName:s.snippetName,context:n}))?.version),i[s.language]={packageName:s.snippetName,version:a},a||n.logger.debug(`[SDK Dynamic IR] ${s.language}: no version specified, will use latest`)}return i}async function gvm({fdr:e,workspace:t,language:r,snippetName:n,context:i}){let o;switch(r){case"csharp":o="Csharp";break;case"go":o="Go";break;case"java":o="Java";break;case"python":o="Python";break;case"ruby":o="Ruby";break;case"typescript":o="TypeScript";break;case"php":o="Php";break;case"swift":o="Swift";break;default:return}let s,a,u;if(t.generatorsConfiguration?.groups){let c=[];for(let l of t.generatorsConfiguration.groups)for(let p of l.generators)if(p.language===r){let d=vn.getPackageName({generatorInvocation:p});d&&c.push(d),!a&&d&&(a=d,u=p.name,p.outputMode.type==="githubV2"&&(s=`${p.outputMode.githubV2.owner}/${p.outputMode.githubV2.repo}`))}}if(!a){i.logger.debug(`[SDK Dynamic IR] ${r}: no generator found with a package name`);return}try{let c=await e.sdks.versions.computeSemanticVersion({githubRepository:s,language:o,package:a});if(!c.ok){i.logger.debug(`[SDK Dynamic IR] ${r}: version computation failed for package "${a}"`);return}return i.logger.debug(`[SDK Dynamic IR] ${r}: computed version ${c.body.version} for package "${a}"`),{version:c.body.version,generatorPackage:a}}catch(c){i.logger.debug(`[SDK Dynamic IR] ${r}: error computing version: ${c}`);return}}async function Avm({workspace:e,organization:t,context:r,snippetsConfig:n,skipLanguages:i=new Set}){let o={};if(!e)return;let s={typescript:n.typescriptSdk?.package,python:n.pythonSdk?.package,java:n.javaSdk?.coordinate,go:n.goSdk?.githubRepo&&SGu(n.goSdk?.githubRepo),csharp:n.csharpSdk?.package,ruby:n.rubySdk?.gem,php:n.phpSdk?.package,swift:n.swiftSdk?.package,rust:n.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let a of e.generatorsConfiguration.groups)for(let u of a.generators){let c=Cje({apiName:e.workspaceName??"",organization:t,generatorInvocation:u}),l="";if(c?.outputConfig.type==="publish")switch(c.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":l=c.outputConfig.value.packageName;break;case"maven":l=c.outputConfig.value.coordinate;break;case"go":l=c.outputConfig.value.repoUrl;break;case"swift":l=c.outputConfig.value.repoUrl;break;case"crates":l=c.outputConfig.value.packageName;break}if(u.language==="php"&&u.config&&typeof u.config=="object"&&"packageName"in u.config&&(l=u.config.packageName??""),!!u.language){if(i.has(u.language)){r.logger.debug(`Skipping dynamic IR generation for ${u.language} (using existing SDK dynamic IR)`);continue}if(u.language&&s[u.language]===l){let p=Nh({workspace:e,generationLanguage:u.language,keywords:void 0,smartCasing:u.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:l,version:void 0,context:r,sourceResolver:new Rm(r,e),dynamicGeneratorConfig:c}),d=gFe({ir:p,disableExamples:!0,smartCasing:u.smartCasing,generationLanguage:u.language,generatorConfig:c});d?o[u.language]={dynamicIR:d}:r.logger.debug(`Failed to create dynamic IR for ${u.language}`)}}}for(let[a,u]of Object.entries(s))a&&u&&!Object.keys(o).includes(a)&&!i.has(a)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${a} SDK snippets because of unknown package \`${u}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${u} package.`),r.logger.warn());if(Object.keys(o).length>0)return o}async function yvm({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:n}){if(Object.keys(t).length>0)for(let[i,o]of Object.entries(t)){let s=e[i]?.dynamicIR;if(s){let a=JSON.stringify(s);(await fetch(o.uploadUrl,{method:"PUT",body:a,headers:{"Content-Type":"application/octet-stream","Content-Length":Buffer.byteLength(a,"utf8").toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${n}:${i}`):r.logger.warn(`Failed to upload dynamic IR for ${n}:${i}`)}else r.logger.warn(`Could not find matching dynamic IR to upload for ${n}:${i}`)}}async function bvm({docsDefinition:e,isPreview:t,context:r}){e.config.aiChatConfig==null||t||r.logger.warn(be.yellow("Enabling Ask Fern from docs.yml is deprecated. Please enable it from the Fern dashboard instead."))}function Evm(e,t){if(e)return{enabled:!0,model:process.env.FERN_AI_MODEL||"gpt-4o-mini",maxRetries:parseInt(process.env.FERN_AI_MAX_RETRIES||"3"),requestTimeoutMs:parseInt(process.env.FERN_AI_TIMEOUT_MS||"25000"),styleInstructions:t}}function vvm(e){let t=e,r=t?.content;return{errorType:t?.error,statusCode:t?.statusCode??r?.statusCode,reason:r?.reason,errorMessage:r?.errorMessage??r?.message,body:r?.body,cause:r?.cause,rawError:e}}var rMt=[60*1e3,300*1e3,300*1e3];async function nMt({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:n,context:i,token:o,instanceUrl:s,preview:a,previewId:u,disableTemplates:c,skipUpload:l,cliVersion:p,ciSource:d}){let f=a&&!n.config.settings?.substituteEnvVars;n.config=Zy(n.config,{onError:b=>i.failAndThrow(b)},{substituteAsEmpty:f});let m=n.config.instances;if(m.length===0){i.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(m.length>1&&s==null){i.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${m[0]?.url})`);return}let h=m.find(b=>b.url===s)??m[0];if(h==null){i.failAndThrow(`No docs instance with url ${s}. Failed to register.`);return}let g=[];h.customDomain!=null&&(typeof h.customDomain=="string"?g.push(h.customDomain):Array.isArray(h.customDomain)&&g.push(...h.customDomain)),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${h.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let A;return await i.runInteractiveTask({name:h.url},async()=>{let b=performance.now(),v=()=>_Gu({docsWorkspace:n,customDomains:g,domain:h.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,previewId:u,editThisPage:h.editThisPage,isPrivate:h.private,disableTemplates:c,skipUpload:l,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:h.audiences?Array.isArray(h.audiences)?h.audiences:[h.audiences]:void 0,docsUrl:h.url,cliVersion:p,ciSource:d});for(let I=0;;I++)try{A=await v();break}catch(w){if(!(w instanceof _pt)||I>=rMt.length){if(w instanceof _pt)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.");throw w}let x=rMt[I]??rMt[rMt.length-1]??6e4,C=x/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${C} minute${C===1?"":"s"} (attempt ${I+1}/${rMt.length})...`),await new Promise(_=>setTimeout(_,x))}let E=performance.now()-b;i.logger.debug(`Docs publishing completed in ${E.toFixed(0)}ms`)}),A}var L2n=class{context;task;project;docsWorkspace;ossWorkspaces;token;constructor({context:t,task:r,project:n,docsWorkspace:i,ossWorkspaces:o,token:s}){this.context=t,this.task=r,this.project=n,this.docsWorkspace=i,this.ossWorkspaces=o,this.token=s}async publish({instanceUrl:t,preview:r,skipUpload:n}){let i=new Lh({context:this.context,task:this.task});try{let o=await nMt({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:i,token:this.token,instanceUrl:t,preview:r,previewId:void 0,disableTemplates:void 0,skipUpload:n,cliVersion:"4.43.4"});return i.getResult()===ef.Failure?{success:!1}:{success:!0,url:o}}catch(o){return{success:!1,error:Oi(o)}}}};St();var Spt=class e{static MAX_DISPLAYED_LOGS_TTY=10;static URL_PATTERN=/https?:\/\/[^\s]+/;context;stream;tasks={};taskOrder=[];startTime;isRegistered=!1;constructor(t){this.context=t.context,this.stream=t.stream??process.stderr}addTask(t){let r={...t,status:t.status??"pending"};return this.tasks[t.id]=r,this.taskOrder.push(t.id),this}async start(t){return this.startTime=Date.now(),t!=null&&await this.context.ttyAwareLogger.takeOverTerminal(()=>{this.stream.write(`
2244
2244
  `),this.stream.write(`${be.cyan("\u25C6")} ${be.bold(t.title)}
2245
2245
  `),t.subtitle!=null&&this.stream.write(` ${be.dim(t.subtitle)}
2246
2246
  `),this.stream.write(`
@@ -2490,7 +2490,7 @@ ${QMt(this).map(t=>` ${t.fn} - ${t.path}:${t.position}`).join(`
2490
2490
  `),this.hasSameAccess(this.init)||t.write(`${this.init} `),t.writeTextStatement("init"),t.writeNoIndent(`#else
2491
2491
  `),t.writeTextStatement("set"),t.writeNoIndent(`#endif
2492
2492
  `)):(this.hasSameAccess(this.init)||t.write(`${this.init} `),this.accessors?.init?(t.write("init"),t.write(" => "),this.accessors.init(t),t.writeTextStatement("")):t.write("init; "))),this.set&&(this.hasSameAccess(this.set)||t.write(`${this.set} `),this.accessors?.set?(t.write("set"),t.write(" => "),this.accessors.set(t),t.writeTextStatement("")):t.write("set; ")),t.write("}")),this.initializer!=null?(i?t.write(" => "):t.write(" = "),this.initializer.write(t),t.writeLine(";")):!this.skipDefaultInitializer&&!r&&n?$a.Type(this.type)&&this.type.writeEmptyCollectionInitializer(t):!this.get&&!this.init&&t.writeLine(";")}hasSameAccess(t){return t===!0||t===this.access}};St();var P7;(function(e){e[e.INSTANCE=0]="INSTANCE",e[e.STATIC=1]="STATIC"})(P7||(P7={}));var QSe=class e extends wSe{name;isAsync;access;return;noBody;body;bodyType;summary;doc;type;reference;override;parameters;typeParameters;annotations;interfaceReference;constructor({name:t,isAsync:r,override:n,access:i,return_:o,body:s,noBody:a,bodyType:u,summary:c,doc:l,type:p,classReference:d,parameters:f,typeParameters:m,annotations:h,codeExample:g,interfaceReference:A,origin:b,enclosingType:v},E){super({enclosingType:v},b,E),this.name=t,this.isAsync=r??!1,this.override=n??!1,this.access=i,this.return=o,this.noBody=a??!1,this.body=s,this.bodyType=u??e.BodyType.Statement,this.summary=c,this.doc=this.csharp.xmlDocBlockOf(l??{summary:c,codeExample:g}),this.type=p??P7.INSTANCE,this.reference=d,this.parameters=f??[],this.typeParameters=m??[],this.annotations=(h??[]).map(I=>I instanceof aP?this.csharp.annotation({reference:I}):I),this.interfaceReference=A}get isAsyncEnumerable(){return $a.AsyncEnumerable(this.return)}addParameter(t){return t instanceof T7||(t=new T7(t,this.generation)),this.parameters.push(t),t}write(t){if(t.writeNode(this.doc),this.annotations.forEach(r=>{r.write(t)}),t.writeNewLineIfLastLineNot(),this.access&&t.write(`${this.access} `),this.type===P7.STATIC&&t.write("static "),this.isAsync&&t.write("async "),this.override&&t.write("override "),this.return==null?this.isAsync?(t.writeNode(this.System.Threading.Tasks.Task()),t.write(" ")):t.write("void "):(this.isAsync&&!this.isAsyncEnumerable?t.writeNode(this.System.Threading.Tasks.Task(this.return)):this.return.write(t),t.write(" ")),this.interfaceReference&&t.write(`${this.interfaceReference.name}.`),t.write(this.name),this.typeParameters.length>0&&(t.write("<"),this.typeParameters.forEach((r,n)=>{r.write(t),n<this.typeParameters.length-1&&t.write(", ")}),t.write(">")),t.write("("),this.parameters.forEach((r,n)=>{r.write(t),n<this.parameters.length-1&&t.write(", ")}),t.write(")"),this.noBody)t.writeLine(";");else switch(this.bodyType){case e.BodyType.Statement:t.write(" "),t.pushScope(),this.body?.write(t),t.popScope();break;case e.BodyType.Expression:t.write(" => "),this.body?.write(t),t.writeSemicolonIfLastCharacterIsNot();break;default:Be(this.bodyType)}}getParameters(){return this.parameters}};(function(e){e.BodyType={Statement:"statement",Expression:"expression"}})(QSe||(QSe={}));var Vft=class extends iL{access;partial;reference;interfaceReferences;fields=[];methods=[];constructor({name:t,namespace:r,access:n,partial:i,interfaceReferences:o,enclosingType:s,origin:a},u){super(a,u),t=t||(a?this.model.getClassNameFor(a):Uy("Class/Interface name or origin is required")),this.reference=s?this.csharp.classReference({name:t,enclosingType:s}):this.csharp.classReference({name:t,namespace:r||Uy("Class/Interface: Namespace or enclosingType is required ")}),this.access=n,this.partial=i??!1,this.interfaceReferences=o??[]}get name(){return this.reference.name}get namespace(){return this.reference.namespace}get enclosingType(){return this.reference.enclosingType}get isNested(){return this.enclosingType!=null}explicit(t){return this.origin?this.model.explicit($a.Provenance(this.origin)?this.origin.node:this.origin,t):Uy(`Cannot create explicit named member '${t}' on '${this.name}' because the class is not bound to an origin.`)}getField(t){return this.fields.find(r=>this.model.provenance(r.origin)?.jsonPath===t.jsonPath)}addField(t){t.enclosingType=this.reference;let r=new zft(t,this.generation);return this.fields.push(r),r}addMethod(t){t.enclosingType=this.reference;let r=new QSe(t,this.generation);return this.methods.push(r),r}get multipartMethodName(){return"AddJsonPart"}get multipartMethodNameForCollection(){return"AddJsonParts"}get isOptional(){return!1}get isCollection(){return!1}get isReferenceType(){}asOptional(){return new _V(this,this.generation)}asNullable(){return new uMe(this,this.generation)}asNonOptional(){return this}get defaultValue(){return this.csharp.Literal.null()}get fullyQualifiedName(){return this.reference.fullyQualifiedName}};var One=class e extends Vft{static ClassType={Class:"class",Record:"record",Struct:"struct",RecordStruct:"record struct"};static Access=_w;static_;abstract_;sealed;readonly;parentClassReference;type;summary;doc;annotations=[];primaryConstructor;namespaceReferences=[];constructors=[];operators=[];nestedClasses=[];nestedInterfaces=[];rawBodyBlocks=[];constructor({name:t,namespace:r,access:n,static_:i,abstract_:o,sealed:s,partial:a,readonly:u,parentClassReference:c,interfaceReferences:l,enclosingType:p,type:d,summary:f,doc:m,annotations:h,primaryConstructor:g,origin:A},b){super({name:t,namespace:r,access:n,partial:a,interfaceReferences:l,enclosingType:p,origin:A},b),this.static_=i??!1,this.abstract_=o??!1,this.sealed=s??!1,this.readonly=u??!1,this.type=d??e.ClassType.Class,this.summary=f,this.doc=this.csharp.xmlDocBlockOf(m??{summary:f}),this.parentClassReference=c,this.annotations=(h??[]).map(v=>v instanceof aP?this.csharp.annotation({reference:v}):v),this.primaryConstructor=g}addConstructor(t){let r=new e.Constructor(t,this.generation);return this.constructors.push(r),r}addNestedClass(t){if(t instanceof e||(t.enclosingType=this.reference,t=new e(t,this.generation)),!t.isNested)throw new Error(`Set the enclosingType of the class ${this.name} to add the nested class ${t.name}.`);return this.nestedClasses.push(t),t}addNestedClasses(t){t.forEach(r=>{r instanceof e?this.addNestedClass(r):this.addNestedClass(r)})}addAnnotation(t){return t instanceof afe||(t=new afe(t,this.generation)),this.annotations.push(t),t}addOperator(t){this.operators.push(t)}addOperators(t){t.forEach(r=>this.addOperator(r))}addRawBodyContent(t){this.rawBodyBlocks.push(t)}write(t){if(this.namespaceReferences.forEach(r=>{t.addNamespace(r)}),this.isNested||(t.writeLine(`namespace ${this.namespace};`),t.newLine()),t.writeNode(this.doc),this.annotations.forEach(r=>{r.write(t)}),t.writeNewLineIfLastLineNot(),t.write(`${this.access}`),this.static_&&t.write(" static"),this.abstract_&&t.write(" abstract"),this.sealed&&t.write(" sealed"),this.readonly&&t.write(" readonly"),this.partial&&t.write(" partial"),t.write(` ${this.type}`),t.write(` ${this.name}`),this.primaryConstructor!=null&&this.primaryConstructor.parameters.length>0){let r=this.primaryConstructor;t.write("("),r.parameters.forEach((n,i)=>{i>0&&t.write(","),n.write(t)}),t.write(")")}if(this.parentClassReference!=null||this.interfaceReferences.length>0){if(t.write(" : "),this.parentClassReference!=null&&(this.parentClassReference.write(t),this.interfaceReferences.length>0&&t.write(", ")),this.primaryConstructor!=null&&this.primaryConstructor.superClassArguments.length>0){let r=this.primaryConstructor;t.write("("),this.primaryConstructor.superClassArguments.forEach((n,i)=>{n.write(t),i<r.superClassArguments.length-1&&t.write(", ")}),t.write(")")}this.interfaceReferences.forEach((r,n)=>{r.write(t),n<this.interfaceReferences.length-1&&t.write(", ")})}if(!this.hasBody()){t.write(";");return}t.writeNewLineIfLastLineNot(),t.pushScope(),this.writeConsts(t),this.writeFieldFields(t),this.writeConstructors(t),this.writeProperties(t),this.writeMethods(t),this.writeOperators(t),this.writeRawBodyBlocks(t),this.writeNestedClasses(t),this.writeNestedInterfaces(t),t.popScope()}hasBody(){return this.fields.length>0||this.constructors.length>0||this.nestedClasses.length>0||this.nestedInterfaces.length>0||this.methods.length>0||this.operators.length>0||this.rawBodyBlocks.length>0}writeConstructors(t){this.constructors.forEach(r=>{t.writeNode(this.csharp.xmlDocBlockOf(r.doc)),r.annotations.forEach(n=>{n.write(t),t.writeNewLineIfLastLineNot()}),t.write(`${r.access} ${this.name} (`),r.parameters.forEach((n,i)=>{n.write(t),i<r.parameters.length-1&&t.write(", ")}),t.write(")"),r.baseConstructorCall!=null&&(t.write(" : "),r.baseConstructorCall.write(t)),t.pushScope(),r.body.write(t),t.popScope(),t.newLine()})}writeFields({writer:t,fields:r}){r.forEach((n,i)=>{n.write(t),t.writeNewLineIfLastLineNot(),i<this.fields.length-1&&t.newLine()})}writeConsts(t){this.writeFields({writer:t,fields:this.getFields().sort(qft).sort(rmo).filter(this.fieldConstFilter())})}writeFieldFields(t){this.writeFields({writer:t,fields:this.getFields().sort(qft).sort(rmo).filter(this.fieldFieldFilter())})}writeProperties(t){this.writeFields({writer:t,fields:this.getFields().sort(qft).sort(rmo).filter(this.fieldPropertyFilter())})}writeMethods(t){this.methods.sort(qft).sort(bTm).sort(yTm).forEach(r=>{r.write(t),t.writeNewLineIfLastLineNot(),t.newLine()})}writeOperators(t){this.operators.forEach(r=>{this.writeOperator({writer:t,operator:r}),t.newLine()})}writeRawBodyBlocks(t){this.rawBodyBlocks.forEach(r=>{r.write(t),t.writeNewLineIfLastLineNot()})}writeNestedClasses(t){this.nestedClasses.sort(qft).forEach((r,n)=>{r.write(t),t.writeNewLineIfLastLineNot(),n<this.fields.length-1&&t.newLine()})}writeNestedInterfaces(t){this.nestedInterfaces.sort(qft).forEach((r,n)=>{r.write(t),t.writeNewLineIfLastLineNot(),n<this.fields.length-1&&t.newLine()})}fieldConstFilter(){return t=>t.isConst}fieldFieldFilter(){return t=>t.isField}fieldPropertyFilter(){return t=>t.isProperty}getFields(){return this.fields}get isReferenceType(){return this.type===e.ClassType.Class||this.type===e.ClassType.Record}writeOperator({writer:t,operator:r}){if(t.write("public static "),r.type===e.CastOperator.Type.Explicit||r.type===e.CastOperator.Type.Implicit){t.write(`${r.type} `),t.write("operator ");let n=r.to??this.reference;t.writeNode(n),t.write("("),r.parameter.write(t)}else{let n=r;n.return.write(t),t.write(" operator "),t.write(`${r.type}(`),n.parameters.forEach((i,o)=>{i.write(t),o<n.parameters.length-1&&t.write(", ")})}r.useExpressionBody?(t.write(") => "),t.writeNodeStatement(r.body)):(t.write(") {"),t.writeNode(r.body),t.writeLine("}"))}addNamespaceReference(t){this.namespaceReferences.push(t)}};(function(e){class t{generation;doc;body;parameters;access;baseConstructorCall;annotations;constructor({doc:i,body:o,parameters:s,access:a,baseConstructorCall:u,annotations:c},l){this.generation=l,this.parameters=s??[],this.access=a??_w.Public,this.doc=i,this.annotations=c??[],this.body=new FSe({},this.generation),o!=null&&this.body.append(o),this.baseConstructorCall=u}addParameter(i){let o=new T7(i,this.generation);return this.parameters.push(o),o}}e.Constructor=t;let r;(function(n){n.Type={Implicit:"implicit",Explicit:"explicit"}})(r=e.CastOperator||(e.CastOperator={}))})(One||(One={}));function aYu(e){switch(e){case void 0:return 0;case _w.Private:return 1;case _w.Protected:return 2;case _w.Internal:return 3;case _w.Public:return 4}}function qft(e,t){return aYu(e.access)-aYu(t.access)}function rmo(e,t){return e.isStatic===t.isStatic?0:e.isStatic?-1:1}function yTm(e,t){return e.type===P7.STATIC&&t.type!==P7.STATIC?-1:e.type!==P7.STATIC&&t.type===P7.STATIC?1:0}function bTm(e,t){return e.name==="FromProto"||e.name==="ToProto"?t.name==="Equals"||t.name==="ToString"?-1:1:t.name==="FromProto"||t.name==="ToProto"?e.name==="Equals"||e.name==="ToString"?1:-1:e.name==="ToString"?1:t.name==="ToString"?-1:e.name==="Equals"?t.name==="ToString"?-1:1:t.name==="Equals"?e.name==="ToString"?1:-1:0}var Gft=class extends iL{get name(){return this.reference.name}get namespace(){return this.reference.namespace}access;reference;annotations;fields=[];generateSerializer=!1;serializerClassReference;constructor({name:t,namespace:r,access:n,annotations:i,origin:o},s){super(o,s),this.reference=this.csharp.classReference({name:t,namespace:r,origin:o}),this.access=n,this.annotations=i??[]}getNamespace(){return this.namespace}addAnnotation(t){this.annotations.push(t)}addMember(t){this.fields.push({name:t.name,wireValue:t.value,value:this.csharp.annotation({reference:this.System.Runtime.Serialization.EnumMember,argument:this.csharp.codeblock(r=>{r.write("Value = "),r.writeNode(this.csharp.string_({string:t.value}))})})})}enableSerializerGeneration(){return this.generateSerializer=!0,this.serializerClassReference=this.csharp.classReference({name:`${this.name}Serializer`,namespace:this.namespace}),this.serializerClassReference}write(t){t.writeLine(`namespace ${this.namespace};`),t.newLine();for(let r of this.annotations)r.write(t);t.writeNewLineIfLastLineNot(),t.write(`${this.access} `),t.write("enum "),t.writeLine(`${this.name}`),t.pushScope(),this.fields.forEach((r,n)=>{r.value.write(t),t.write(r.name),n<this.fields.length-1&&(t.writeLine(","),t.newLine())}),t.writeNewLineIfLastLineNot(),t.popScope(),this.generateSerializer&&this.writeSerializerClass(t)}writeSerializerClass(t){t.newLine(),t.writeLine(`internal class ${this.name}Serializer : global::System.Text.Json.Serialization.JsonConverter<${this.name}>`),t.pushScope(),t.writeLine(`private static readonly global::System.Collections.Generic.Dictionary<string, ${this.name}> _stringToEnum = new()`),t.pushScope();for(let r of this.fields)t.writeLine(`{ ${JSON.stringify(r.wireValue)}, ${this.name}.${r.name} },`);t.popScope(!1),t.writeLine(";"),t.newLine(),t.writeLine(`private static readonly global::System.Collections.Generic.Dictionary<${this.name}, string> _enumToString = new()`),t.pushScope();for(let r of this.fields)t.writeLine(`{ ${this.name}.${r.name}, ${JSON.stringify(r.wireValue)} },`);t.popScope(!1),t.writeLine(";"),t.newLine(),t.writeLine(`public override ${this.name} Read(ref global::System.Text.Json.Utf8JsonReader reader, global::System.Type typeToConvert, global::System.Text.Json.JsonSerializerOptions options)`),t.pushScope(),t.writeLine('var stringValue = reader.GetString() ?? throw new global::System.Exception("The JSON value could not be read as a string.");'),t.writeLine("return _stringToEnum.TryGetValue(stringValue, out var enumValue) ? enumValue : default;"),t.popScope(),t.newLine(),t.writeLine(`public override void Write(global::System.Text.Json.Utf8JsonWriter writer, ${this.name} value, global::System.Text.Json.JsonSerializerOptions options)`),t.pushScope(),t.writeLine("writer.WriteStringValue(_enumToString.TryGetValue(value, out var stringValue) ? stringValue : null);"),t.popScope(),t.newLine(),t.writeLine(`public override ${this.name} ReadAsPropertyName(ref global::System.Text.Json.Utf8JsonReader reader, global::System.Type typeToConvert, global::System.Text.Json.JsonSerializerOptions options)`),t.pushScope(),t.writeLine('var stringValue = reader.GetString() ?? throw new global::System.Exception("The JSON property name could not be read as a string.");'),t.writeLine("return _stringToEnum.TryGetValue(stringValue, out var enumValue) ? enumValue : default;"),t.popScope(),t.newLine(),t.writeLine(`public override void WriteAsPropertyName(global::System.Text.Json.Utf8JsonWriter writer, ${this.name} value, global::System.Text.Json.JsonSerializerOptions options)`),t.pushScope(),t.writeLine("writer.WritePropertyName(_enumToString.TryGetValue(value, out var stringValue) ? stringValue : value.ToString());"),t.popScope(),t.popScope()}};var Wft=class extends Vft{constructor({name:t,namespace:r,access:n,partial:i,interfaceReferences:o,enclosingType:s,origin:a},u){super({name:t,namespace:r,access:n,partial:i,interfaceReferences:o,enclosingType:s,origin:a},u)}write(t){this.isNested||(t.writeLine(`namespace ${this.namespace};`),t.newLine()),t.write(`${this.access} `),this.partial&&t.write("partial "),t.write("interface "),t.writeLine(`${this.name}`),this.interfaceReferences.length>0&&(t.write(" : "),this.interfaceReferences.forEach((r,n)=>{r.write(t),n<this.interfaceReferences.length-1&&t.write(", ")})),t.pushScope();for(let r of this.fields)r.write(t),t.writeLine("");t.dedent(),t.indent();for(let r of this.methods)r.write(t),t.writeLine("");t.popScope()}};var $ft=class extends iL{get name(){return this.reference.name}get namespace(){return this.reference.namespace}reference;parentClassReference;testMethods=[];constructor({name:t,namespace:r,parentClassReference:n,origin:i},o){super(i,o),this.reference=this.csharp.classReference({name:t,namespace:r,origin:i}),this.parentClassReference=n}write(t){t.writeNode(this.getClass())}getClass(){let t=[this.NUnit.Framework.TestFixture,this.csharp.annotation({reference:this.NUnit.Framework.Parallelizable,argument:"ParallelScope.Self"})],r=new One({access:_w.Public,name:this.name,namespace:this.namespace,annotations:t,parentClassReference:this.parentClassReference,origin:this.origin},this.generation);for(let n of this.testMethods)r.addMethod({access:_w.Public,isAsync:n.isAsync,name:n.name,parameters:[],body:n.body,annotations:[this.NUnit.Framework.Test]});return r}addTestMethod(t){this.testMethods.push(t)}};var nmo={System:["AccessViolationException","Action","Activator","AggregateException","AppContext","AppDomain","AppDomainSetup","AppDomainUnloadedException","ApplicationException","ApplicationId","ArgIterator","ArgumentException","ArgumentNullException","ArgumentOutOfRangeException","ArithmeticException","Array","ArrayTypeMismatchException","AssemblyLoadEventArgs","AssemblyLoadEventHandler","AsyncCallback","Attribute","AttributeTargets","AttributeUsageAttribute","BadImageFormatException","Base64FormattingOptions","BitConverter","Boolean","Buffer","Byte","CannotUnloadAppDomainException","Char","CharEnumerator","CLSCompliantAttribute","Console","ConsoleCancelEventArgs","ConsoleCancelEventHandler","ConsoleColor","ConsoleKey","ConsoleKeyInfo","ConsoleModifiers","ConsoleSpecialKey","ContextBoundObject","ContextMarshalException","ContextStaticAttribute","Convert","CultureAwareComparer","DataMisalignedException","DateOnly","DateTime","DateTimeKind","DateTimeOffset","DayOfWeek","DBNull","Decimal","Delegate","DivideByZeroException","DllNotFoundException","Double","DuplicateWaitObjectException","EntryPointNotFoundException","Enum","Environment","EnvironmentVariableTarget","EventArgs","EventHandler","Exception","ExecutionEngineException","FieldAccessException","FlagsAttribute","FormatException","FormattableString","GC","GCCollectionMode","GCGenerationInfo","GCKind","GCMemoryInfo","GCNotificationStatus","Guid","Half","HashCode","IAsyncDisposable","IAsyncResult","ICloneable","IComparable","IConvertible","ICustomFormatter","IDisposable","IFormatProvider","IFormattable","Index","IndexOutOfRangeException","InsufficientExecutionStackException","InsufficientMemoryException","Int128","Int16","Int32","Int64","IntPtr","InvalidCastException","InvalidOperationException","InvalidProgramException","InvalidTimeZoneException","ISpanFormattable","IUtf8SpanFormattable","LoaderOptimization","LoaderOptimizationAttribute","LocalDataStoreSlot","MarshalByRefObject","Math","MathF","MemberAccessException","MemoryExtensions","MethodAccessException","MidpointRounding","MissingFieldException","MissingMemberException","MissingMethodException","ModuleHandle","MTAThreadAttribute","MulticastDelegate","MulticastNotSupportedException","NonSerializedAttribute","NotFiniteNumberException","NotImplementedException","NotSupportedException","Nullable","NullReferenceException","Object","ObjectDisposedException","ObsoleteAttribute","OperatingSystem","OperationCanceledException","OrdinalComparer","OutOfMemoryException","OverflowException","ParamArrayAttribute","PlatformID","PlatformNotSupportedException","Random","Range","RankException","ResolveEventArgs","ResolveEventHandler","RuntimeArgumentHandle","RuntimeFieldHandle","RuntimeMethodHandle","RuntimeTypeHandle","SByte","SerializableAttribute","Single","StackOverflowException","STAThreadAttribute","String","StringComparer","StringComparison","StringNormalizationExtensions","StringSplitOptions","SystemException","ThreadStaticAttribute","TimeOnly","TimeoutException","TimeProvider","TimeSpan","TimeZone","TimeZoneInfo","TimeZoneNotFoundException","Tuple","TupleExtensions","Type","TypeAccessException","TypeCode","TypedReference","TypeInitializationException","TypeLoadException","TypeUnloadedException","UInt128","UInt16","UInt32","UInt64","UIntPtr","UnauthorizedAccessException","UnhandledExceptionEventArgs","UnhandledExceptionEventHandler","UnitySerializationHolder","ValueTuple","ValueType","Version","Void","WeakReference","Buffers","Collections","ComponentModel","Diagnostics","Globalization","IO","Linq","Net","Numerics","Reflection","Resources","Runtime","Security","Text","Threading"],"System.Collections.Generic":["ByteEqualityComparer","CollectionExtensions","IEnumerable","KeyNotFoundException","KeyValuePair","NonRandomizedStringEqualityComparer","ReferenceEqualityComparer"],"System.IO":["BinaryReader","BinaryWriter","BufferedStream","Directory","DirectoryInfo","DirectoryNotFoundException","EndOfStreamException","EnumerationOptions","File","FileAccess","FileAttributes","FileInfo","FileLoadException","FileMode","FileNotFoundException","FileOptions","FileShare","FileStream","FileStreamOptions","FileSystemInfo","HandleInheritability","InvalidDataException","IOException","MatchCasing","MatchType","MemoryStream","Path","PathTooLongException","RandomAccess","SearchOption","SeekOrigin","Stream","StreamReader","StreamWriter","StringReader","StringWriter","TextReader","TextWriter","UnixFileMode","UnmanagedMemoryAccessor","UnmanagedMemoryStream","System.IO.Enumeration"],"System.Linq":["Enumerable"],"System.Net.Http":["HttpClient","HttpMethod"],"System.Threading":["AbandonedMutexException","ApartmentState","AsyncFlowControl","AutoResetEvent","CancellationToken","CancellationTokenRegistration","CancellationTokenSource","CompressedStack","ContextCallback","EventResetMode","EventWaitHandle","ExecutionContext","Interlocked","IOCompletionCallback","IThreadPoolWorkItem","ITimer","LazyInitializer","LazyThreadSafetyMode","Lock","LockRecursionException","LockRecursionPolicy","ManualResetEvent","ManualResetEventSlim","Monitor","Mutex","NativeOverlapped","Overlapped","ParameterizedThreadStart","PeriodicTimer","PreAllocatedOverlapped","ReaderWriterLockSlim","RegisteredWaitHandle","Semaphore","SemaphoreFullException","SemaphoreSlim","SendOrPostCallback","SpinLock","SpinWait","SynchronizationContext","SynchronizationLockException","Thread","ThreadAbortException","ThreadExceptionEventArgs","ThreadExceptionEventHandler","ThreadInterruptedException","ThreadPool","ThreadPoolBoundHandle","ThreadPriority","ThreadStart","ThreadStartException","ThreadState","ThreadStateException","Timeout","Timer","TimerCallback","Volatile","WaitCallback","WaitHandle","WaitHandleCannotBeOpenedException","WaitHandleExtensions","WaitOrTimerCallback","Tasks"],"System.Threading.Tasks":["ConcurrentExclusiveSchedulerPair","ConfigureAwaitOptions","Task","TaskAsyncEnumerableExtensions","TaskCanceledException","TaskCompletionSource","TaskContinuationOptions","TaskCreationOptions","TaskExtensions","TaskFactory","TaskScheduler","TaskSchedulerException","TaskStatus","TaskToAsyncResult","UnobservedTaskExceptionEventArgs","ValueTask","Sources"]};var ETm=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"]);var vTm=new Set(["from","where","select","orderby","groupby","into","let","join","on","equals"]),ITm=new Set(["async","await"]),wTm=new Set(["yield"]),CTm=new Set(["var","dynamic"]),xTm=new Set(["using","alias"]);var _Tm=new Set(["required","scoped","unmanaged","managed"]),STm=new Set(["when","and","or","not"]),BTm=new Set(["Equals","GetHashCode","ToString","GetType","MemberwiseClone","Finalize"]),OTm=new Set([...ETm,...vTm,...ITm,...wTm,...CTm,...xTm,..._Tm,...STm]),qjn=class{registry;name;jsonPath;constructor(t,r,n){this.registry=t,this.name=r,this.jsonPath=n}};var Gjn=class{scope;constructor(t){this.scope=t}byName=new Map;byPath=new Map;redirections=new Map;[Symbol.iterator](){return this.byName.values()}has(t){return this.byName.has(t)}getByJsonPath(t){return this.byPath.get(t)}getByName(t){return this.byName.get(t)}getRedirectedName(t){return this.redirections.get(t)}set(t){this.byName.has(t.name)&&Uy(`set: ${t.name} in ${this.scope.fullyQualifiedName} already exists`),t.jsonPath&&this.byPath.has(t.jsonPath)&&Uy(`set: ${t.name} in ${this.scope.fullyQualifiedName} already exists by jsonPath`),this.byName.set(t.name,t),t.jsonPath&&this.byPath.set(t.jsonPath,t)}redirect(t,r){this.redirections.has(t)&&Uy(`redirect: ${t} in ${this.scope.fullyQualifiedName} already has a redirect`),this.redirections.set(t,r)}},imo=class extends qjn{namespace;fullyQualifiedName;fields;methods;constructor(t,r,n,i){super(t,r),this.namespace=n,this.fullyQualifiedName=i,this.fields=new Gjn(this),this.methods=new Gjn(this)}isKeyword(t){return OTm.has(t)}isBuiltinMemberName(t){return BTm.has(t)}isTypeName(t){return this.name===t}isField(t){return this.fields.has(t)}isMethod(t){return this.methods.has(t)}isMember(t){return this.isField(t)||this.isMethod(t)}nameBlocked(t){if(this.isKeyword(t))return"keyword";if(this.isBuiltinMemberName(t))return"builtin";if(this.isTypeName(t))return"typeName";if(this.isField(t))return"field";if(this.isMethod(t))return"method"}getAlternativeName(t){let r=`${t}_`,n=2;for(;this.nameBlocked(r);)r=`${t}_${n}`,n++;return r}getFieldByJsonPath(t){return t!==void 0?this.fields.getByJsonPath(t):void 0}getFieldByName(t){return this.fields.getByName(t)}getRedirectedFieldName(t){return this.fields.getRedirectedName(t)}registerField(t,r,n){let i=this.registry.model.jsonPath(r);if(i){let a=this.fields.getByJsonPath(i);if(a)return a.name}let o=this.fields.getByName(t);if(o&&i===o.jsonPath)return t;switch(this.nameBlocked(t)){case"field":r&&$a.Provenance(r)&&r.explicit||Uy(`Field ${t} already exists - attempting to add a duplicate field with the same name that is not an explicitly named property`);break;case"keyword":case"builtin":case"typeName":case"method":break;default:return this.fields.set(new Wjn(this.registry,t,this,i,n)),this.registry.setFieldNameShortcut(i,t),t}let s=this.getAlternativeName(t);return this.fields.set(new Wjn(this.registry,s,this,i,n)),this.fields.redirect(t,s),this.registry.setFieldNameShortcut(i,s),s}getFieldName(t,r){let n=this.getFieldByJsonPath(this.registry.model.jsonPath(t))?.name;if(n)return n;if($a.Provenance(t)){let s=this.getRedirectedFieldName(r);if(s)return s;let a=this.getFieldByName(r);return a?this.registry.model.provenance(a.jsonPath)?.explicit?r:`${r}_`:r}let i=this.getFieldByName(r);if(i)return this.registry.model.provenance(i.jsonPath)?.explicit?r:i.name;let o=this.getRedirectedFieldName(r);if(o)return o;this.isMethod(r)}},omo=class extends qjn{scope;constructor(t,r,n,i){super(t,r,i),this.scope=n}},Wjn=class extends omo{field;constructor(t,r,n,i,o){super(t,r,n,i),this.field=o}};var Kft=class e{generation;classReferenceByJsonPath=new Map;typeRegistry=new Map;namespaceRegistry=new Map;typeNames=new Map;namespaceNames=new Map;implicitNamespaces=new Set;shortcuts=new Map;knownBuiltInIdentifiers=new Set(["Text","Json","Xml","Security","Collections","Data","Diagnostics","Globalization","Math","Reflection","Runtime","Security","Serialization","Threading","Xml"]);constructor(t){this.generation=t,this.initializeBuiltIns()}get csharp(){return this.generation.csharp}get model(){return this.generation.model}initializeBuiltIns(){for(let[t,r]of Object.entries(nmo))t.split(".").forEach(n=>this.knownBuiltInIdentifiers.add(n)),r.forEach(n=>this.knownBuiltInIdentifiers.add(n));for(let[t,r]of Object.entries(nmo)){for(let i of r)this.typeNames.set(i,new Set([t]));let n=t.split(".")[0];n&&this.typeNames.set(n,new Set([t]))}this.typeNames.set("System",new Set(["System"])),this.typeNames.set("NUnit",new Set(["NUnit"])),this.typeNames.set("OneOf",new Set(["OneOf"])),this.knownBuiltInIdentifiers.add("NUnit"),this.knownBuiltInIdentifiers.add("OneOf")}setFieldNameShortcut(t,r){if(t){let n=this.shortcuts.get(t);n&&n!==r&&Uy(`BAD_BAD_BAD setFieldNameShortcut: ${t} already has a name: ${n} - while setting to ${r} - if this is happening, then you could be getting back the wrong name later!`),this.shortcuts.set(t,r)}}getFieldNameByOrigin(t){return this.shortcuts.get(this.model.jsonPath(t)??">ignore<")}isKnownBuiltInIdentifier(t){return!t||typeof t!="string"?!1:this.knownBuiltInIdentifiers.has(t)}isKnownNamespace(t){return!t||typeof t!="string"?!1:this.namespaceRegistry.has(t)}isRegisteredTypeName(t){return this.typeRegistry.has(t)}isAmbiguousTypeName(t){return t?(this.typeNames.get(t)?.size??0)>1:!1}isAmbiguousNamespaceName(t){return t?(this.namespaceNames.get(t)?.size??0)>1:!1}hasTypeNamespaceConflict(t){return!t||this.knownBuiltInIdentifiers.has(t)?!1:this.typeNames.has(t)&&(this.namespaceNames.get(t)?.has("")??!1)}static fullyQualifiedNameOf(t){return t.enclosingType?`${t.enclosingType.fullyQualifiedName??`${t.namespace}.${t.enclosingType.name}`}+${t.name}`:`${t.namespace}.${t.name}`}registerNamespace(t,r){this.namespaceRegistry.has(t)&&this.namespaceRegistry.get(t)!==r||this.namespaceRegistry.set(t,r)}trackType(t,r){let{name:n,namespace:i,enclosingType:o,fullyQualifiedName:s,origin:a}=t;if(a){let u=this.model.jsonPath(a)??Uy(`JsonPath not found for origin: ${JSON.stringify(a).substring(0,100)}`);this.classReferenceByJsonPath.set(u,t)}if(r&&r!==s&&!this.typeRegistry.has(r)&&this.typeRegistry.set(r,t),!this.typeRegistry.has(s)){this.typeRegistry.set(s,t);for(let u of this.allNamespacesOf(i))this.registerNamespace(u,u);o||this.trackTypeName(n,i);for(let u of[this.generation.namespaces.root,...this.implicitNamespaces])if(i.startsWith(u)){let c=i.split(".")[u.split(".").length];c&&this.trackTypeName(c,i)}}return t}addImplicitNamespace(t){this.implicitNamespaces.add(t)}isNamespaceImplicit(t){return this.implicitNamespaces.has(t)}get implicitlyImportedNamespaces(){return[...this.implicitNamespaces]}trackTypeName(t,r){this.typeNames.has(t)?this.typeNames.get(t)?.add(r):this.typeNames.set(t,new Set([r]));let n=r.split("."),i="";for(let o of n)this.namespaceNames.has(o)?this.namespaceNames.get(o)?.add(i):this.namespaceNames.set(o,new Set([i])),i=i?`${i}.${o}`:o}allNamespacesOf(t){if(!t||typeof t!="string")return new Set;let r="",n=new Set;for(let i of t.split("."))i.trim()&&(r=r?`${r}.${i}`:`${i}`,n.add(r));return n}registerClassReference(t,r){let{name:n,namespace:i,enclosingType:o,origin:s}=t,a=this.model.jsonPath(s),u=(a?this.classReferenceByJsonPath.get(a):void 0)??this.typeRegistry.get(r),c=this.model.jsonPath(u?.origin),l=c&&a?c===a?"match":"mismatch":"no origin";if(u&&l!=="mismatch")return new aP({name:u.name,namespace:u.namespace,enclosingType:u.enclosingType,fullyQualifiedName:u.fullyQualifiedName,namespaceAlias:t.namespaceAlias,fullyQualified:t.fullyQualified,generics:t.generics,global:t.global,origin:u.origin??s,isCollection:u.isCollection,isReferenceType:u.isReferenceType,multipartMethodName:u.multipartMethodName,multipartMethodNameForCollection:u.multipartMethodNameForCollection},u.scope,this.generation);let p=!1,d=this.resolveNamespace(i);d!==i&&(i=d,p=!0);let f;e:for(;;){f=e.fullyQualifiedNameOf({name:n,namespace:i,enclosingType:o});let m="",h=i.split(".");for(let g=0;g<h.length;g++)if(m=m?`${m}.${h[g]}`:`${h[g]}`,this.typeRegistry.has(m)){h[g]=`${h[g]}_`,i=h.join("."),p=!0;continue e}if(p&&this.registerNamespace(t.namespace,i),l==="mismatch"&&u?.name===n){n=`${n}_`,p=!0;continue e}if(this.namespaceRegistry.has(f)){n=`${n}_`,p=!0;continue e}if(this.typeRegistry.has(f)){n=`${n}_`,p=!0;continue e}if(o){let g=f.replaceAll("+",".");if(this.typeRegistry.has(g)){n=`${n}_`,p=!0;continue e}if(this.namespaceRegistry.has(g)){n=`${n}_`,p=!0;continue e}}else{let g=f.split(".");for(let A=1;A<g.length;A++){let b=g.slice(0,A).join(".")+"+"+g.slice(A).join("+");if(this.typeRegistry.has(b)){n=`${n}_`,p=!0;continue e}}}break}return this.trackType(new aP({name:n,namespace:i,enclosingType:o,namespaceAlias:t.namespaceAlias,fullyQualified:t.fullyQualified,generics:t.generics,global:t.global,fullyQualifiedName:f,origin:s,isCollection:t.isCollection,isReferenceType:t.isReferenceType,multipartMethodName:t.multipartMethodName,multipartMethodNameForCollection:t.multipartMethodNameForCollection},new imo(this,n,i,f),this.generation),r)}resolveNamespace(t){let r=this.namespaceRegistry.get(t);if(r!==void 0)return r;let n=t.split(".");for(let i=n.length-1;i>=0;i--){let o=n.slice(0,i).join(".");if(this.namespaceRegistry.has(o)){let s=this.namespaceRegistry.get(o);if(s!==void 0){let a=n.slice(i).join("."),u=`${s}.${a}`;return this.registerNamespace(t,u),u}}}return t}canonicalizeNamespace(t){let r=this.namespaceRegistry.get(t);if(r!==void 0)return r;let n=!1,i=t;e:for(;;){let o="",s=i.split(".");for(let a=0;a<s.length;a++)if(o=o?`${o}.${s[a]}`:`${s[a]}`,this.typeRegistry.has(o)){s[a]=`${s[a]}_`,i=s.join("."),n=!0;continue e}break}return n&&this.registerNamespace(t,i),i}};var $jn=class{generation;constructor(t){this.generation=t}get model(){return this.generation.model}frozen=!1;extraClassReferences=new Map;classReference(t){return this.classReferenceInternal(t)}classReferenceInternal(t){if(!t.name&&"origin"in t&&t.origin&&(t.name=this.model.getClassNameFor(t.origin)),t.enclosingType){if(t.namespace)throw new Error("ClassReference: Both enclosingType and namespace cannot be provided");t.namespace=t.enclosingType.namespace}let r=Kft.fullyQualifiedNameOf(t);if(this.frozen&&!this.generation.registry.isRegisteredTypeName(r)){let n=this.extraClassReferences.get(r);n||(n=new Set,this.extraClassReferences.set(r,n)),n.add(`${r} -
2493
- ${kMt()}`)}return this.generation.registry.registerClassReference(t,r)}freezeClassReferences(){this.frozen=!0}getPropertyName(t,r){let n=this.model.getPropertyNameFor(r),i=this.model.origin(r)??Uy(`Origin not found for property: ${JSON.stringify(r).substring(0,100)}`),o=t.getFieldName(i,n);return o||n}class_(t){let r=t;return"reference"in t&&(r={...t.reference,...t}),new One(r,this.generation)}testClass(t){return new $ft(t,this.generation)}annotation(t){return new afe(t,this.generation)}annotationGroup(t){return new Qft(t,this.generation)}instantiateClass(t){return new Eft(t,this.generation)}invokeMethod(t){return new Cft(t,this.generation)}codeblock(t){return new RSe(t,this.generation)}code(){return new FSe({},this.generation)}anonymousFunction(t){return new jft(t)}parameter(t){return new T7(t,this.generation)}interface_(t){return new Wft(t,this.generation)}enum_(t){return new Gft(t,this.generation)}dictionary(t){return new vft(t,this.generation)}list(t){return new wft(t,this.generation)}readOnlyMemory(t){return new xft(t,this.generation)}set(t){return new _ft(t,this.generation)}switch_(t){return new Lft(t,this.generation)}ternary(t){return new Uft(t,this.generation)}and(t){return new kft(t,this.generation)}or(t){return new Mft(t,this.generation)}enumInstantiation(t){return new Ift(t,this.generation)}string_(t){return new Sft(t,this.generation)}xmlDocBlock(t){return new kSe(t,this.generation)}InstantiatedPrimitive={string:t=>new IB({type:"string",value:t},this.generation),boolean:t=>new IB({type:"boolean",value:t},this.generation),integer:t=>new IB({type:"integer",value:t},this.generation),long:t=>new IB({type:"long",value:t},this.generation),uint:t=>new IB({type:"uint",value:t},this.generation),ulong:t=>new IB({type:"ulong",value:t},this.generation),float:t=>new IB({type:"float",value:t},this.generation),double:t=>new IB({type:"double",value:t},this.generation),date:t=>new IB({type:"date",value:t},this.generation),dateTime:(t,r=!0)=>new IB({type:"dateTime",value:t,parse:r},this.generation),uuid:t=>new IB({type:"uuid",value:t},this.generation),null:()=>new IB({type:"null"},this.generation)};Literal={class_:({reference:t,fields:r})=>new Zc.Class_(t,r,this.generation),dictionary:({keyType:t,valueType:r,entries:n})=>new Zc.Dictionary(t,r,n,this.generation),list:({valueType:t,values:r})=>new Zc.List(t,r,this.generation),set:({valueType:t,values:r})=>new Zc.Set(t,r,this.generation),boolean:t=>new Zc.Boolean(t,this.generation),float:t=>new Zc.Float(t,this.generation),date:t=>new Zc.Date(t,this.generation),datetime:t=>new Zc.DateTime(t,this.generation),decimal:t=>new Zc.Decimal(t,this.generation),double:t=>new Zc.Double(t,this.generation),integer:t=>new Zc.Integer(t,this.generation),long:t=>new Zc.Long(t,this.generation),uint:t=>new Zc.Uint(t,this.generation),ulong:t=>new Zc.Ulong(t,this.generation),reference:t=>new Zc.Reference(t,this.generation),string:t=>new Zc.String(t,this.generation),null:()=>new Zc.Null(this.generation),nop:()=>new Zc.Nop(this.generation),unknown:t=>new Zc.Unknown(t,this.generation)};xmlDocBlockOf(t){return t instanceof kSe?t:new kSe(t,this.generation)}VALID_READ_ONLY_MEMORY_TYPES=new Set(["int","long","uint","ulong","string","bool","float","double"]);validateReadOnlyMemoryTypes(){for(let t of this.generation.settings.readOnlyMemoryTypes)if(!this.VALID_READ_ONLY_MEMORY_TYPES.has(t))throw new Error(`Type "${t}" is not a valid 'read-only-memory-types' custom config option; expected one of ${JSON.stringify(this.VALID_READ_ONLY_MEMORY_TYPES)}.`)}};function uc(e){let t={},r={};for(let[n,i]of Object.entries(e))i.length===0?Object.defineProperty(r,n,{get(){return n in t||(t[n]=i()),t[n]},enumerable:!0,configurable:!0}):r[n]=i;return r}var Hjn=class{generation;constructor(t){this.generation=t}get csharp(){return this.generation.csharp}System=uc({Action:t=>this.csharp.classReference({name:"Action",namespace:"System",generics:t||void 0,multipartMethodName:null,multipartMethodNameForCollection:null,isReferenceType:!0}),Func:(t,r)=>this.csharp.classReference({name:"Func",namespace:"System",generics:t?r?[...t,r]:t:r?[r]:void 0,multipartMethodName:null,multipartMethodNameForCollection:null,isReferenceType:!0}),DateOnly:()=>this.csharp.classReference({name:"DateOnly",namespace:"System"}),DateTime:()=>this.csharp.classReference({name:"DateTime",namespace:"System"}),Enum:()=>this.csharp.classReference({name:"Enum",namespace:"System"}),Exception:()=>this.csharp.classReference({name:"Exception",namespace:"System"}),ReadOnlyMemory:t=>this.csharp.classReference({name:"ReadOnlyMemory",namespace:"System",generics:[t]}),Serializable:()=>this.csharp.classReference({name:"SerializableAttribute",namespace:"System"}),String:()=>this.csharp.classReference({name:"String",namespace:"System"}),Type:()=>this.csharp.classReference({name:"Type",namespace:"System",isReferenceType:!0,multipartMethodName:null,multipartMethodNameForCollection:null,fullyQualified:!0}),TimeSpan:()=>this.csharp.classReference({name:"TimeSpan",namespace:"System"}),Uri:()=>this.csharp.classReference({name:"Uri",namespace:"System"}),UriBuilder:()=>this.csharp.classReference({name:"UriBuilder",namespace:"System"}),Runtime:()=>uc({Serialization:()=>uc({EnumMember:()=>this.csharp.classReference({name:"EnumMemberAttribute",namespace:"System.Runtime.Serialization"})})}),Collections:()=>uc({Generic:()=>uc({IAsyncEnumerable:t=>this.csharp.classReference({name:"IAsyncEnumerable",namespace:"System.Collections.Generic",generics:t?[t]:void 0}),IEnumerable:t=>this.csharp.classReference({name:"IEnumerable",namespace:"System.Collections.Generic",generics:t?[t]:void 0}),KeyValuePair:(t,r)=>this.csharp.classReference({name:"KeyValuePair",namespace:"System.Collections.Generic",generics:t&&r?[t,r]:void 0}),List:t=>this.csharp.classReference({name:"List",namespace:"System.Collections.Generic",generics:t?[t]:void 0,isCollection:!0}),HashSet:t=>this.csharp.classReference({name:"HashSet",namespace:"System.Collections.Generic",generics:t?[t]:void 0,isCollection:!0}),Dictionary:(t,r)=>this.csharp.classReference({name:"Dictionary",namespace:"System.Collections.Generic",generics:t&&r?[t,r]:void 0,isCollection:!0}),IDictionary:(t,r)=>this.csharp.classReference({name:"IDictionary",namespace:"System.Collections.Generic",generics:[t,r]})}),Linq:()=>uc({Enumerable:()=>this.csharp.classReference({name:"Enumerable",namespace:"System.Linq"})})}),Globalization:()=>uc({DateTimeStyles:()=>this.csharp.classReference({name:"DateTimeStyles",namespace:"System.Globalization"})}),Linq:()=>uc({Enumerable:()=>this.csharp.classReference({name:"Enumerable",namespace:"System.Linq"})}),Net:()=>uc({Http:()=>uc({HttpClient:()=>this.csharp.classReference({name:"HttpClient",namespace:"System.Net.Http"}),HttpMethod:()=>this.csharp.classReference({name:"HttpMethod",namespace:"System.Net.Http"}),HttpResponseHeaders:()=>this.csharp.classReference({name:"HttpResponseHeaders",namespace:"System.Net.Http.Headers"})}),ServerSentEvents:()=>uc({SseEvent:()=>this.csharp.classReference({name:"SseEvent",namespace:"System.Net.ServerSentEvents"}),SseParser:()=>this.csharp.classReference({name:"SseParser",namespace:"System.Net.ServerSentEvents"})}),WebSockets:()=>uc({ClientWebSocketOptions:()=>this.csharp.classReference({name:"ClientWebSocketOptions",namespace:"System.Net.WebSockets"})})}),IO:()=>uc({MemoryStream:()=>this.csharp.classReference({name:"MemoryStream",namespace:"System.IO"}),Stream:()=>this.csharp.classReference({name:"Stream",namespace:"System.IO"}),StreamReader:()=>this.csharp.classReference({name:"StreamReader",namespace:"System.IO"})}),Text:()=>uc({Encoding:()=>this.csharp.classReference({name:"Encoding",namespace:"System.Text"}),Encoding_UTF8:()=>this.csharp.classReference({name:"UTF8",enclosingType:this.csharp.classReference({name:"Encoding",namespace:"System.Text"})}),Json:()=>uc({JsonElement:()=>this.csharp.classReference({name:"JsonElement",namespace:"System.Text.Json"}),JsonDocument:()=>this.csharp.classReference({name:"JsonDocument",namespace:"System.Text.Json"}),JsonException:()=>this.csharp.classReference({name:"JsonException",namespace:"System.Text.Json"}),Utf8JsonReader:()=>this.csharp.classReference({name:"Utf8JsonReader",namespace:"System.Text.Json"}),JsonSerializerOptions:()=>this.csharp.classReference({name:"JsonSerializerOptions",namespace:"System.Text.Json"}),JsonSerializer:()=>this.csharp.classReference({name:"JsonSerializer",namespace:"System.Text.Json"}),Utf8JsonWriter:()=>this.csharp.classReference({name:"Utf8JsonWriter",namespace:"System.Text.Json"}),Nodes:()=>uc({JsonNode:()=>this.csharp.classReference({name:"JsonNode",namespace:"System.Text.Json.Nodes"}),JsonObject:()=>this.csharp.classReference({name:"JsonObject",namespace:"System.Text.Json.Nodes"})}),Serialization:()=>uc({IJsonOnDeserialized:()=>this.csharp.classReference({name:"IJsonOnDeserialized",namespace:"System.Text.Json.Serialization"}),IJsonOnSerializing:()=>this.csharp.classReference({name:"IJsonOnSerializing",namespace:"System.Text.Json.Serialization"}),JsonOnDeserializedAttribute:()=>this.csharp.classReference({name:"JsonOnDeserializedAttribute",namespace:"System.Text.Json.Serialization"}),JsonExtensionData:()=>this.csharp.classReference({name:"JsonExtensionDataAttribute",namespace:"System.Text.Json.Serialization"}),JsonConverter:t=>this.csharp.classReference({name:"JsonConverter",namespace:"System.Text.Json.Serialization",generics:t?[t]:void 0}),JsonIgnore:()=>this.csharp.classReference({name:"JsonIgnoreAttribute",namespace:"System.Text.Json.Serialization"}),JsonPropertyName:()=>this.csharp.classReference({name:"JsonPropertyNameAttribute",namespace:"System.Text.Json.Serialization"})})})}),Threading:()=>uc({CancellationToken:()=>this.csharp.classReference({name:"CancellationToken",namespace:"System.Threading"}),Tasks:()=>uc({Task:t=>this.csharp.classReference({name:"Task",namespace:"System.Threading.Tasks",generics:t?[t]:void 0}),ValueTask:t=>this.csharp.classReference({name:"ValueTask",namespace:"System.Threading.Tasks",generics:t?[t]:void 0})})}),ComponentModel:()=>uc({INotifyPropertyChanged:()=>this.csharp.classReference({name:"INotifyPropertyChanged",namespace:"System.ComponentModel"}),PropertyChangedEventHandler:()=>this.csharp.classReference({name:"PropertyChangedEventHandler",namespace:"System.ComponentModel"})}),IAsyncDisposable:()=>this.csharp.classReference({name:"IAsyncDisposable",namespace:"System"}),IDisposable:()=>this.csharp.classReference({name:"IDisposable",namespace:"System"})});NUnit=uc({Framework:()=>uc({TestFixture:()=>this.csharp.classReference({name:"TestFixture",namespace:"NUnit.Framework"}),Test:()=>this.csharp.classReference({name:"Test",namespace:"NUnit.Framework"}),OneTimeTearDown:()=>this.csharp.classReference({name:"OneTimeTearDown",namespace:"NUnit.Framework"}),OneTimeSetUp:()=>this.csharp.classReference({name:"OneTimeSetUp",namespace:"NUnit.Framework"}),SetUpFixture:()=>this.csharp.classReference({name:"SetUpFixture",namespace:"NUnit.Framework"}),Parallelizable:()=>this.csharp.classReference({name:"Parallelizable",namespace:"NUnit.Framework"})})});OneOf=uc({OneOf:t=>this.csharp.classReference({name:"OneOf",namespace:"OneOf",generics:t}),OneOfBase:t=>this.csharp.classReference({name:"OneOfBase",namespace:"OneOf",generics:t})});Google=uc({Protobuf:()=>uc({ByteString:()=>this.csharp.classReference({name:"ByteString",namespace:"Google.Protobuf"}),WellKnownTypes:()=>uc({Struct:()=>this.csharp.classReference({name:"Struct",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"}),Value:()=>this.csharp.classReference({name:"Value",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"}),ListValue:()=>this.csharp.classReference({name:"ListValue",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"}),Timestamp:()=>this.csharp.classReference({name:"Timestamp",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"})})})});WireMock=uc({Server:()=>this.csharp.classReference({name:"WireMockServer",namespace:"WireMock.Server"}),WireMockServerSettings:()=>this.csharp.classReference({name:"WireMockServerSettings",namespace:"WireMock.Settings"}),WireMockConsoleLogger:()=>this.csharp.classReference({name:"WireMockConsoleLogger",namespace:"WireMock.Logging"})});Grpc=uc({Core:()=>uc({RpcException:()=>this.csharp.classReference({name:"RpcException",namespace:"Grpc.Core"})})})};var smo=new Set(["name","camelCase","snakeCase","screamingSnakeCase","pascalCase"]);function TTm(e,t){return smo.has(t)?e??"":e?`${e}.${t}`:t}var Kjn=class{generation;indexByObject=new Map;indexByPath=new Map;explicitByObject=new Map;explicitByPath=new Map;root;ir;get csharp(){return this.generation.csharp}get registry(){return this.generation.registry}constructor(t,r){this.generation=r,this.root=this.createIndex(t),this.ir=t}createIndex(t,r="",n){let i=TTm(n?.jsonPath,r);if(this.indexByPath.has(i)){n||Uy(`Parent provenance not found for node: ${JSON.stringify(t).substring(0,100)}`),this.indexByObject.set(t,n);let s=smo.has(r);for(let[a,u]of Object.entries(t))typeof u=="object"&&u!==null&&(s&&smo.has(a)?this.indexByObject.set(u,n):this.createIndex(u,a,n));return n}let o={jsonPath:i,name:r,node:t,parent:n};this.indexByObject.set(t,o),this.indexByPath.set(i,o);for(let[s,a]of Object.entries(t))typeof a=="object"&&a!==null&&this.createIndex(a,s,o);return o}staticExplicit(t){return this.explicit(this.ir,t)}explicit(t,r){let n=this.provenance(t)??Uy(`Provenance not found for node: ${JSON.stringify(t).substring(0,100)}`),i={...n,jsonPath:`${n.jsonPath}+${r}`,name:r,node:n.node,parent:n,explicit:!0},o=this.explicitByObject.get(n.node);return o?o.add(i):this.explicitByObject.set(n.node,new Set([i])),this.explicitByPath.set(i.jsonPath,i),i}provenance(t){if(t!==void 0)return $a.string(t)?this.explicitByPath.get(t)??this.indexByPath.get(t):$a.Provenance(t)?this.explicitByPath.get(t.jsonPath)??this.indexByPath.get(t.jsonPath):this.indexByObject.get(t)}origin(t){let r=this.provenance(t);return r?.explicit?r:r?.node}irNode(t){return this.provenance(t)?.node}jsonPath(t){return this.provenance(t)?.jsonPath}getEnumValueName(t,r){let n=$a.IR.ExampleEnumType(r)?r.value.name:r.name,i=t.values.find(o=>this.nameEquals(o.name.name,n));return i?this.getPropertyNameFor(i):Uy(`Unexpected - can't find enum value ${n} in enum`)}getPropertyNameFor(t){let r=this.registry.getFieldNameByOrigin(t);if(r)return r;if($a.Provenance(t))return t.name;if("name"in t){if($a.IR.NameAndWireValue(t.name))return t.name.name.pascalCase.safeName;if($a.IR.Name(t.name))return t.name.pascalCase.safeName;if(typeof t.name=="string")return t.name}if("pascalCase"in t)return t.pascalCase.safeName;throw new Error(`Unknown property type: ${this.jsonPath(t)}`)}getClassNameFor(t){if($a.Provenance(t))return t.name;if("name"in t){if($a.IR.TypeDeclaration(t)||$a.IR.NameAndWireValue(t.name))return t.name.name.pascalCase.safeName;if($a.IR.Name(t.name))return t.name.pascalCase.safeName;if(typeof t.name=="string")return t.name}if("pascalCase"in t)return t.pascalCase.safeName;throw new Error(`Unknown property type: ${JSON.stringify(t)}`)}nameEquals(t,r){return t.camelCase.safeName===r.camelCase.safeName}dereferenceType(t){let r=$a.string(t)?t:$a.IR.NamedType(t)||$a.IR.DeclaredTypeName(t)?t.typeId:$a.IR.ExampleNamedType(t)?t.typeName.typeId:t.name.typeId,n=this.irNode(this.ir.types[r]);if($a.IR.TypeDeclaration(n))return{typeId:r,typeDeclaration:n};Uy(`dereferenceType: typeId ${r} not resolved.`)}};function Jjn(...e){return e.filter(Boolean).join("/")}var bLt=class{intermediateRepresentation;apiName;customConfig;generatorConfig;support;constructor(t,r,n,i,o={makeRelativeFilePath:s=>s,makeAbsoluteFilePath:s=>s,getNamespaceForTypeId:s=>"",getDirectoryForTypeId:s=>"",getCoreAsIsFiles:()=>[],getCoreTestAsIsFiles:()=>[],getPublicCoreAsIsFiles:()=>[],getAsyncCoreAsIsFiles:()=>[],getChildNamespaceSegments:s=>[]}){this.intermediateRepresentation=t,this.apiName=r,this.customConfig=n,this.generatorConfig=i,this.support=o,this.model=new Kjn(t,this),this.ir=$a.IR.IntermediateRepresentation(t)?t:{},this.dir=$a.DynamicIR.DynamicIntermediateRepresentation(t)?t:{}}ir;dir;csharp=new $jn(this);registry=new Kft(this);model;extern=new Hjn(this);settings=uc({namespace:()=>this.customConfig.namespace??Njn(kjn(`${this.generatorConfig.organization}_${this.apiName}`)),readOnlyMemoryTypes:()=>this.customConfig["read-only-memory-types"]??[],simplifyObjectDictionaries:()=>this.customConfig["simplify-object-dictionaries"]??!1,useFullyQualifiedNamespaces:()=>this.customConfig["experimental-fully-qualified-namespaces"]??!1,useDotnetFormat:()=>this.customConfig["experimental-dotnet-format"]??!1,enableWebsockets:()=>this.customConfig["experimental-enable-websockets"]??!1,enableReadonlyConstants:()=>this.customConfig["experimental-readonly-constants"]??!1,generateLiterals:()=>this.customConfig["generate-literals"]??this.customConfig["experimental-readonly-constants"]??!1,enableExplicitNullableOptional:()=>this.customConfig["experimental-explicit-nullable-optional"]??!1,useDefaultRequestParameterValues:()=>this.customConfig["use-default-request-parameter-values"]??!1,redactResponseBodyOnError:()=>this.customConfig["redact-response-body-on-error"]??!1,temporaryWebsocketEnvironments:()=>this.customConfig["temporary-websocket-environments"]??{},baseApiExceptionClassName:()=>this.customConfig["base-api-exception-class-name"]??"",baseExceptionClassName:()=>this.customConfig["base-exception-class-name"]??"",shouldGeneratedDiscriminatedUnions:()=>this.customConfig["use-discriminated-unions"]??!0,shouldGenerateUndiscriminatedUnions:()=>this.customConfig["use-undiscriminated-unions"]??!1,exportedClientClassName:()=>this.customConfig["exported-client-class-name"]??"",clientClassName:()=>this.customConfig["client-class-name"]??"",rootNamespaceForCoreClasses:()=>this.customConfig["root-namespace-for-core-classes"]??!0,packageId:()=>this.customConfig["package-id"]??"",isForwardCompatibleEnumsEnabled:()=>this.customConfig["enable-forward-compatible-enums"]??this.customConfig["experimental-enable-forward-compatible-enums"]??!0,websocketEnvironments:()=>this.customConfig["temporary-websocket-environments"]??{},customPagerName:()=>this.customConfig["custom-pager-name"]??"",environmentClassName:()=>this.customConfig["environment-class-name"]??"",generateErrorTypes:()=>this.customConfig["generate-error-types"]??!0,shouldInlinePathParameters:()=>this.customConfig["inline-path-parameters"]??!0,includeExceptionHandler:()=>this.customConfig["include-exception-handler"]??!1,exceptionInterceptorClassName:()=>this.customConfig["exception-interceptor-class-name"]??"",shouldGenerateMockServerTests:()=>this.customConfig["generate-mock-server-tests"]??this.customConfig["enable-wire-tests"]??!0,rootClientAccess:()=>this.customConfig["root-client-class-access"]=="internal"?_w.Internal:_w.Public,extraDependencies:()=>this.customConfig["extra-dependencies"]??{},omitFernHeaders:()=>this.customConfig["omit-fern-headers"]??!1,unifiedClientOptions:()=>this.customConfig["unified-client-options"]??!1,pascalCaseEnvironments:()=>this.customConfig["pascal-case-environments"]??!0,slnFormat:()=>this.customConfig["sln-format"]??"slnx",explicitNamespaces:()=>this.customConfig["explicit-namespaces"]===!0,outputPath:()=>{let t=this.customConfig["output-path"];return t==null?{library:"src",test:"src",solution:".",other:"."}:typeof t=="string"?{library:t,test:t,solution:".",other:"."}:{library:t.library??"src",test:t.test??"src",solution:t.solution??".",other:t.other??"."}}});constants={folders:uc({mockServerTests:()=>this.support.makeRelativeFilePath("Unit/MockServer"),types:()=>"Types",exceptions:()=>"Exceptions",src:()=>"src",protobuf:()=>"proto",serializationTests:()=>this.support.makeRelativeFilePath("Unit/Serialization"),project:()=>this.support.makeRelativeFilePath(Jjn(this.constants.folders.sourceFiles,this.support.makeRelativeFilePath(this.names.files.project))),sourceFiles:()=>this.support.makeRelativeFilePath(this.constants.folders.src),coreFiles:()=>this.support.makeRelativeFilePath(Jjn(this.constants.folders.project,this.support.makeRelativeFilePath(this.constants.defaults.core))),publicCoreFiles:()=>this.support.makeRelativeFilePath(Jjn(this.constants.folders.project,this.support.makeRelativeFilePath(this.constants.defaults.core),this.support.makeRelativeFilePath(this.constants.defaults.publicCore))),testFiles:()=>this.support.makeRelativeFilePath(Jjn(this.constants.folders.sourceFiles,this.support.makeRelativeFilePath(this.names.files.testProject)))}),formatting:uc({indent:()=>" "}),defaults:uc({core:()=>"Core",publicCore:()=>"Public",version:()=>"0.0.0"})};namespaces=uc({root:()=>this.settings.namespace,core:()=>`${this.namespaces.root}.Core`,qualifiedRoot:()=>this.qualifyNamespace(this.namespaces.root),qualifiedCore:()=>this.qualifyNamespace(this.namespaces.core),test:()=>this.registry.canonicalizeNamespace(`${this.namespaces.root}.Test`),testUtils:()=>`${this.namespaces.test}.Utils`,mockServerTest:()=>`${this.namespaces.test}.Unit.MockServer`,publicCore:()=>this.namespaces.root,webSocketsCore:()=>`${this.namespaces.core}.WebSockets`,publicCoreTest:()=>`${this.namespaces.root}.Test.PublicCore`,asIsTestUtils:()=>`${this.namespaces.root}.Test.Utils`,publicCoreClasses:()=>this.settings.rootNamespaceForCoreClasses?this.namespaces.root:this.namespaces.core,implicit:()=>new Set(["System","System.Collections.Generic","System.IO","System.Linq","System.Threading","System.Threading.Tasks","System.Net.Http"])});names={classes:uc({baseApiException:()=>this.settings.baseApiExceptionClassName||`${this.names.project.clientPrefix}ApiException`,baseException:()=>this.settings.baseExceptionClassName||`${this.names.project.clientPrefix}Exception`,rootClient:()=>this.settings.clientClassName||`${this.names.project.clientPrefix}Client`,rootClientForSnippets:()=>this.settings.exportedClientClassName||this.names.classes.rootClient,customPager:()=>this.settings.customPagerName||`${this.names.project.packageId.replace(/[^a-zA-Z0-9]/g,"")}Pager`,environment:()=>this.settings.environmentClassName||`${this.names.project.clientPrefix}Environment`,exceptionInterceptor:()=>this.settings.exceptionInterceptorClassName||`${this.names.project.packageId.replace(/[^a-zA-Z0-9]/g,"")}ExceptionInterceptor`}),project:uc({client:()=>Njn(kjn(`${this.generatorConfig.organization}_${this.generatorConfig.workspaceName}`)),clientPrefix:()=>this.settings.exportedClientClassName||this.settings.clientClassName||this.names.project.client,packageId:()=>this.settings.packageId||this.namespaces.root}),files:uc({project:()=>this.namespaces.root,testProject:()=>`${this.namespaces.root}.Test`}),methods:uc({mockOauth:()=>"MockOAuthEndpoint",mockInferredAuth:()=>"MockInferredAuthEndpoint",getAccessTokenAsync:()=>"GetAccessTokenAsync",getAuthHeadersAsync:()=>"GetAuthHeadersAsync"}),variables:uc({client:()=>"client",response:()=>"response",httpRequest:()=>"httpRequest",sendRequest:()=>"sendRequest",responseBody:()=>"responseBody",query:()=>"_query",headers:()=>"_headers"}),parameters:uc({cancellationToken:()=>"cancellationToken",requestOptions:()=>"options",idempotentOptions:()=>"options"})};Types=uc({Arbitrary:t=>new Nf.ArbitraryType(t,this),HttpMethodExtensions:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("HttpMethodExtensions")}),FormRequest:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("FormRequest")}),Optional:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("Optional")}),ClientOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("ClientOptions"),namespace:this.namespaces.publicCoreClasses}),RawClient:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("RawClient")}),RequestOptions:()=>this.csharp.classReference({namespace:this.namespaces.publicCoreClasses,origin:this.model.staticExplicit("RequestOptions")}),RequestOptionsInterface:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("IRequestOptions")}),JsonRequest:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("JsonRequest")}),Version:()=>this.csharp.classReference({namespace:this.namespaces.publicCore,origin:this.model.staticExplicit("Version")}),ValueConvert:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("ValueConvert")}),FileParameter:()=>this.csharp.classReference({namespace:this.namespaces.publicCore,origin:this.model.staticExplicit("FileParameter"),multipartMethodName:"AddFileParameterPart",multipartMethodNameForCollection:"AddFileParameterParts",isReferenceType:!0}),Headers:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("Headers")}),HeaderValue:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("HeaderValue")}),RootClient:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.rootClient),namespace:this.namespaces.root}),RootClientForSnippets:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.rootClientForSnippets),namespace:this.namespaces.root}),BaseApiException:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.baseApiException),namespace:this.namespaces.publicCoreClasses}),BaseException:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.baseException),namespace:this.namespaces.publicCoreClasses}),ExceptionInterceptor:()=>this.csharp.classReference({origin:this.model.staticExplicit("IExceptionInterceptor"),namespace:this.namespaces.core}),ExceptionHandler:()=>this.csharp.classReference({origin:this.model.staticExplicit("ExceptionHandler"),namespace:this.namespaces.core}),CustomExceptionInterceptor:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.exceptionInterceptor),namespace:this.namespaces.core}),ProtoAnyMapper:()=>this.csharp.classReference({origin:this.model.staticExplicit("ProtoAnyMapper"),namespace:this.namespaces.core}),Constants:()=>this.csharp.classReference({origin:this.model.staticExplicit("Constants"),namespace:this.namespaces.core}),DateTimeSerializer:()=>this.csharp.classReference({origin:this.model.staticExplicit("DateTimeSerializer"),namespace:this.namespaces.core}),JsonUtils:()=>this.csharp.classReference({origin:this.model.staticExplicit("JsonUtils"),namespace:this.namespaces.core}),JsonAssert:()=>this.csharp.classReference({origin:this.model.staticExplicit("JsonAssert"),namespace:this.namespaces.testUtils}),CustomPagerFactory:()=>this.csharp.classReference({origin:this.model.staticExplicit(`${this.names.classes.customPager}Factory`),namespace:this.namespaces.core}),CustomPagerContext:()=>this.csharp.classReference({origin:this.model.staticExplicit(`${this.names.classes.customPager}Context`),namespace:this.namespaces.core}),Environments:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.environment),namespace:this.namespaces.publicCoreClasses}),TestClient:()=>this.csharp.classReference({origin:this.model.staticExplicit("TestClient"),namespace:this.namespaces.test}),BaseMockServerTest:()=>this.csharp.classReference({origin:this.model.staticExplicit("BaseMockServerTest"),namespace:this.namespaces.mockServerTest}),IdempotentRequestOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("IdempotentRequestOptions"),namespace:this.namespaces.publicCoreClasses}),IdempotentRequestOptionsInterface:()=>this.csharp.classReference({origin:this.model.staticExplicit("IIdempotentRequestOptions"),namespace:this.namespaces.core}),IStringEnum:()=>this.csharp.classReference({origin:this.model.staticExplicit("IStringEnum"),namespace:this.namespaces.core}),WebSocketClient:()=>this.csharp.classReference({origin:this.model.staticExplicit("WebSocketClient"),namespace:this.namespaces.webSocketsCore}),QueryBuilder:()=>this.csharp.classReference({origin:this.model.staticExplicit("Query"),namespace:this.namespaces.webSocketsCore}),QueryStringBuilder:()=>this.csharp.classReference({origin:this.model.staticExplicit("QueryStringBuilder"),namespace:this.namespaces.core}),QueryStringBuilderBuilder:()=>this.csharp.classReference({origin:this.model.staticExplicit("QueryStringBuilder.Builder"),namespace:this.namespaces.core}),OAuthTokenProvider:()=>this.csharp.classReference({origin:this.model.staticExplicit("OAuthTokenProvider"),namespace:this.namespaces.core}),InferredAuthTokenProvider:()=>this.csharp.classReference({origin:this.model.staticExplicit("InferredAuthTokenProvider"),namespace:this.namespaces.core}),ProtoConverter:()=>this.csharp.classReference({origin:this.model.staticExplicit("ProtoConverter"),namespace:this.namespaces.core}),RawGrpcClient:()=>this.csharp.classReference({origin:this.model.staticExplicit("RawGrpcClient"),namespace:this.namespaces.core}),Extensions:()=>this.csharp.classReference({origin:this.model.staticExplicit("Extensions"),namespace:this.namespaces.core}),GrpcRequestOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("GrpcRequestOptions"),namespace:this.namespaces.root}),GrpcChannelOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("GrpcChannelOptions"),namespace:"Grpc.Net.Client"}),StringEnum:t=>this.csharp.classReference({origin:this.model.staticExplicit("StringEnum"),namespace:this.namespaces.core,generics:t?[t]:void 0}),WebSocketEvent:t=>this.csharp.classReference({origin:this.model.staticExplicit("Event"),namespace:this.namespaces.webSocketsCore,generics:[t]}),ConnectionStatus:()=>this.csharp.classReference({origin:this.model.staticExplicit("ConnectionStatus"),namespace:this.namespaces.webSocketsCore}),WebSocketConnected:()=>this.csharp.classReference({origin:this.model.staticExplicit("Connected"),namespace:this.namespaces.webSocketsCore}),WebSocketClosed:()=>this.csharp.classReference({origin:this.model.staticExplicit("Closed"),namespace:this.namespaces.webSocketsCore}),ReconnectionInfo:()=>this.csharp.classReference({origin:this.model.staticExplicit("ReconnectionInfo"),namespace:this.namespaces.webSocketsCore}),CustomPagerClass:t=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.customPager),namespace:this.namespaces.core,generics:[t]}),Pager:t=>this.csharp.classReference({origin:this.model.staticExplicit("Pager"),namespace:this.namespaces.core,generics:[t]}),OffsetPager:({requestType:t,requestOptionsType:r,responseType:n,offsetType:i,stepType:o,itemType:s})=>this.csharp.classReference({origin:this.model.staticExplicit("OffsetPager"),namespace:this.namespaces.core,generics:[t,r,n,i,o,s]}),CursorPager:({requestType:t,requestOptionsType:r,responseType:n,cursorType:i,itemType:o})=>this.csharp.classReference({origin:this.model.staticExplicit("CursorPager"),namespace:this.namespaces.core,generics:[t,r,n,i,o]}),CollectionItemSerializer:(t,r)=>this.csharp.classReference({origin:this.model.staticExplicit("CollectionItemSerializer"),namespace:this.namespaces.core,generics:[t,r]}),OneOfSerializer:t=>this.csharp.classReference({origin:this.model.staticExplicit("OneOfSerializer"),namespace:this.namespaces.core,generics:[t]}),AdditionalProperties:t=>this.csharp.classReference({origin:this.model.staticExplicit("AdditionalProperties"),namespace:this.namespaces.publicCore,generics:t?[t]:void 0}),ReadOnlyAdditionalProperties:t=>this.csharp.classReference({origin:this.model.staticExplicit("ReadOnlyAdditionalProperties"),namespace:this.namespaces.publicCore,generics:t?[t]:void 0})});Primitive=uc({string:()=>new Nf.String(this),boolean:()=>new Nf.Boolean(this),integer:()=>new Nf.Integer(this),long:()=>new Nf.Long(this),uint:()=>new Nf.Uint(this),ulong:()=>new Nf.ULong(this),float:()=>new Nf.Float(this),double:()=>new Nf.Double(this),object:()=>new Nf.Object(this)});Value=uc({binary:()=>new sL.Binary(this),dateOnly:()=>new sL.DateOnly(this),dateTime:()=>new sL.DateTime(this),uuid:()=>new sL.Uuid(this),stringEnum:t=>new sL.StringEnum(t,this)});Collection=uc({array:t=>new uS.Array(t,this),listType:t=>new uS.ListType(t,this),list:t=>new uS.List(t,this),set:t=>new uS.Set(t,this),map:(t,r,n)=>new uS.Map(t,r,this,n),idictionary:(t,r,n)=>new uS.IDictionary(t,r,this,n),keyValuePair:(t,r)=>new uS.KeyValuePair(t,r,this)});format=uc({private:t=>`_${Qjn.camelCase(t)}`});initialize(){return this.initializers.implicitNamespaces}initializers=uc({implicitNamespaces:()=>{for(let t of this.namespaces.implicit)this.registry.addImplicitNamespace(t);return!0}});get System(){return this.extern.System}get NUnit(){return this.extern.NUnit}get OneOf(){return this.extern.OneOf}get Google(){return this.extern.Google}get Grpc(){return this.extern.Grpc}get WireMock(){return this.extern.WireMock}qualifyNamespace(t){let r=t.split(".")[0];return r&&this.registry.hasTypeNamespaceConflict(r)?`global::${t}`:t}};var D7=class{generation;constructor(t){this.generation=t}get csharp(){return this.generation.csharp}get settings(){return this.generation.settings}get constants(){return this.generation.constants}get namespaces(){return this.generation.namespaces}get names(){return this.generation.names}get model(){return this.generation.model}get format(){return this.generation.format}get registry(){return this.generation.registry}get Types(){return this.generation.Types}get System(){return this.generation.extern.System}get NUnit(){return this.generation.extern.NUnit}get OneOf(){return this.generation.extern.OneOf}get Google(){return this.generation.extern.Google}get Grpc(){return this.generation.extern.Grpc}get WireMock(){return this.generation.extern.WireMock}get Primitive(){return this.generation.Primitive}get Value(){return this.generation.Value}get Collection(){return this.generation.Collection}};St();var Yjn=class extends D7{context;constructor({context:t}){super(t.generation),this.context=t}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?this.csharp.Literal.null():(this.context.errors.add({severity:Ir.Critical,message:"Expected non-null value, but got null"}),this.csharp.Literal.nop());if(t.value===void 0&&!t.fallbackToDefault)return this.csharp.Literal.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value,fallbackToDefault:t.fallbackToDefault});case"literal":return this.convertLiteral({literal:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value,fallbackToDefault:t.fallbackToDefault});case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.csharp.Literal.nop():this.convertNamed({named:r,value:t.value,as:t.as,fallbackToDefault:t.fallbackToDefault})}case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as,fallbackToDefault:t.fallbackToDefault});case"set":return this.convertSet({set:t.typeReference.value,value:t.value,fallbackToDefault:t.fallbackToDefault});case"unknown":return this.convertUnknown({value:t.value,fallbackToDefault:t.fallbackToDefault});default:Be(t.typeReference)}}convertList({list:t,value:r,fallbackToDefault:n}){return Array.isArray(r)?this.csharp.Literal.list({valueType:this.context.dynamicTypeMapper.convert({typeReference:t,unboxOptionals:!0}),values:r.map((i,o)=>{this.context.errors.scope({index:o});try{return this.convert({typeReference:t,value:i})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),this.csharp.Literal.nop())}convertLiteral({literal:t,value:r,fallbackToDefault:n}){switch(t.type){case"boolean":{let i=this.context.getValueAsBoolean({value:r});return i==null?this.csharp.Literal.nop():this.csharp.Literal.boolean(i)}case"string":{let i=this.context.getValueAsString({value:r});return i==null?n?this.Primitive.string.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.string(i)}default:Be(t)}}convertSet({set:t,value:r,fallbackToDefault:n}){return Array.isArray(r)?this.csharp.Literal.set({valueType:this.context.dynamicTypeMapper.convert({typeReference:t,unboxOptionals:!0}),values:r.map((i,o)=>{this.context.errors.scope({index:o});try{return this.convert({typeReference:t,value:i})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),this.csharp.Literal.nop())}convertMap({map:t,value:r,fallbackToDefault:n}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),this.csharp.Literal.nop()):this.csharp.Literal.dictionary({keyType:this.context.dynamicTypeMapper.convert({typeReference:t.key}),valueType:t.value.type==="unknown"?this.context.dynamicTypeMapper.convert({typeReference:t.value}).asOptional():this.context.dynamicTypeMapper.convert({typeReference:t.value}),entries:Object.entries(r).map(([i,o])=>{this.context.errors.scope(i);try{return{key:this.convert({typeReference:t.key,value:i,as:"key"}),value:this.convert({typeReference:t.value,value:o})}}finally{this.context.errors.unscope()}})})}convertNamed({named:t,value:r,as:n,fallbackToDefault:i}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference,value:r,as:n,fallbackToDefault:i});case"discriminatedUnion":return this.settings.shouldGeneratedDiscriminatedUnions?this.convertDiscriminatedUnion({discriminatedUnion:t,value:r,fallbackToDefault:i}):this.convertUnknown({value:r,fallbackToDefault:i});case"enum":return this.getEnumValue(t,r);case"object":return this.convertObject({object_:t,value:r,fallbackToDefault:i});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,fallbackToDefault:i});default:Be(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r,fallbackToDefault:n}){let i=this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),o=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(o==null)return this.csharp.Literal.nop();let s=o.singleDiscriminatedUnionType,a=this.getBaseProperties({discriminatedUnionTypeInstance:o,singleDiscriminatedUnionType:s});switch(s.type){case"samePropertiesAsObject":{let u=this.context.resolveNamedType({typeId:s.typeId});return u==null?this.csharp.Literal.nop():this.instantiateUnionWithBaseProperties({classReference:i,baseProperties:a,arguments_:[this.convertNamed({named:u,value:o.value})]})}case"singleProperty":{if(this.context.getRecord(o.value)==null)return this.csharp.Literal.nop();try{let c=["Value","Type"].includes(s.discriminantValue.name.pascalCase.safeName)?`${s.discriminantValue.name.pascalCase.safeName}Inner`:s.discriminantValue.name.pascalCase.safeName;return this.context.errors.scope(s.discriminantValue.wireValue),this.instantiateUnionWithBaseProperties({classReference:i,baseProperties:a,arguments_:[this.csharp.instantiateClass({classReference:this.csharp.classReference({name:c,enclosingType:i}),arguments_:[this.convert({typeReference:s.typeReference,value:s.discriminantValue.wireValue})]})]})}finally{this.context.errors.unscope()}}case"noProperties":return this.instantiateUnionWithBaseProperties({classReference:i,baseProperties:a,arguments_:[this.csharp.instantiateClass({classReference:this.csharp.classReference({origin:o.discriminantValue,enclosingType:i}),arguments_:[]})]});default:Be(s)}}getBaseProperties({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r}){return this.context.associateByWireValue({parameters:r.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(i=>{this.context.errors.scope(i.name.wireValue);try{return{name:this.context.getPropertyName(i.name.name),assignment:this.convert(i)}}finally{this.context.errors.unscope()}})}instantiateUnionWithBaseProperties({classReference:t,arguments_:r,baseProperties:n}){let i=this.csharp.instantiateClass({classReference:t,arguments_:r,multiline:!0});return n.length===0?this.csharp.Literal.reference(i):this.csharp.Literal.reference(this.csharp.codeblock(o=>{o.write(i," "),o.pushScope();for(let s of n)o.write(s.name," = ",s.assignment,",");o.popScope(!1)}))}getEnumValue(t,r){if(typeof r!="string")return this.context.errors.add({severity:Ir.Critical,message:`Expected enum value string, got: ${typeof r}`}),this.csharp.Literal.nop();let n=t.values.find(s=>s.wireValue===r);if(n==null)return this.context.errors.add({severity:Ir.Critical,message:`An enum value named "${r}" does not exist in this context`}),this.csharp.Literal.nop();let i=this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),o=i.registerField(this.model.getPropertyNameFor(n),n);return this.csharp.Literal.reference(this.csharp.enumInstantiation({reference:i,value:o}))}convertObject({object_:t,value:r,fallbackToDefault:n}){let i=this.context.associateByWireValue({parameters:t.properties,values:this.context.getRecord(r)??{}});return this.csharp.Literal.class_({reference:this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),fields:i.map(o=>{this.context.errors.scope(o.name.wireValue);try{return{name:this.context.getClassName(o.name.name),value:this.convert(o)}}finally{this.context.errors.unscope()}})})}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,fallbackToDefault:n}){let i=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r});return i==null?this.csharp.Literal.nop():i.typeLiteral}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r}){for(let n of t.types)try{let i=this.convert({typeReference:n,value:r});return{valueTypeReference:n,typeLiteral:i}}catch{continue}this.context.errors.add({severity:Ir.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}convertUnknown({value:t,fallbackToDefault:r}){return this.csharp.Literal.unknown(t)}convertPrimitive({primitive:t,value:r,as:n,fallbackToDefault:i}){switch(t){case"INTEGER":{let o=this.getValueAsNumber({value:r,as:n});return o==null?i?this.Primitive.integer.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.integer(o)}case"LONG":{let o=this.getValueAsNumber({value:r,as:n});return o==null?i?this.Primitive.long.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.long(o)}case"UINT":{let o=this.getValueAsNumber({value:r,as:n});return o==null?i?this.Primitive.uint.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.uint(o)}case"UINT_64":{let o=this.getValueAsNumber({value:r,as:n});return o==null?i?this.Primitive.ulong.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.ulong(o)}case"FLOAT":{let o=this.getValueAsNumber({value:r,as:n});return o==null?i?this.Primitive.float.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.float(o)}case"DOUBLE":{let o=this.getValueAsNumber({value:r,as:n});return o==null?i?this.Primitive.double.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.double(o)}case"BOOLEAN":{let o=this.getValueAsBoolean({value:r,as:n});return o==null?i?this.Primitive.boolean.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.boolean(o)}case"STRING":{let o=this.context.getValueAsString({value:r});return o==null?i?this.Primitive.string.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.string(o)}case"DATE":{let o=this.context.getValueAsString({value:r});return o==null?i?this.Value.dateOnly.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.date(o)}case"DATE_TIME":{let o=this.context.getValueAsString({value:r});return o==null?i?this.Value.dateTime.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.datetime(o)}case"UUID":{let o=this.context.getValueAsString({value:r});return o==null?i?this.Primitive.string.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.string(o)}case"BASE_64":{let o=this.context.getValueAsString({value:r});return o==null?i?this.Primitive.string.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.string(o)}case"BIG_INTEGER":{let o=this.context.getValueAsString({value:r});return o==null?i?this.Primitive.string.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.string(o)}default:Be(t)}}getValueAsNumber({value:t,as:r}){let n=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:n})}};St();var Xjn=class extends D7{context;constructor({context:t}){super(t.generation),this.context=t}convert(t){switch(t.typeReference.type){case"list":return this.Collection.list(this.convert({typeReference:t.typeReference.value,unboxOptionals:!0}));case"literal":return this.convertLiteral({literal:t.typeReference.value});case"map":return this.Collection.map(this.convert({typeReference:t.typeReference.key}),this.convert({typeReference:t.typeReference.value}));case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.convertUnknown():this.convertNamed({named:r})}case"optional":case"nullable":{let r=this.convert({typeReference:t.typeReference.value});return t.unboxOptionals?r.asNonOptional():r.asOptional()}case"primitive":return this.convertPrimitive({primitive:t.typeReference.value});case"set":return this.Collection.set(this.convert({typeReference:t.typeReference.value,unboxOptionals:!0}));case"unknown":return this.convertUnknown();default:Be(t.typeReference)}}convertToClassReference(t){return this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)})}convertNamed({named:t}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference});case"enum":case"object":return this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)});case"discriminatedUnion":return this.settings.shouldGeneratedDiscriminatedUnions?this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}):this.Primitive.object;case"undiscriminatedUnion":return this.settings.shouldGenerateUndiscriminatedUnions?this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}):this.OneOf.OneOf(t.types.map(r=>this.convert({typeReference:r})));default:Be(t)}}convertLiteral({literal:t}){switch(t.type){case"boolean":return this.Primitive.boolean;case"string":return this.Primitive.string}}convertUnknown(){return this.Primitive.object}convertPrimitive({primitive:t}){switch(t){case"INTEGER":return this.Primitive.integer;case"UINT":return this.Primitive.uint;case"LONG":return this.Primitive.long;case"UINT_64":return this.Primitive.ulong;case"FLOAT":return this.Primitive.float;case"DOUBLE":return this.Primitive.double;case"BOOLEAN":return this.Primitive.boolean;case"STRING":return this.Primitive.string;case"DATE":return this.Value.dateOnly;case"DATE_TIME":return this.Value.dateTime;case"UUID":return this.Primitive.string;case"BASE_64":return this.Primitive.string;case"BIG_INTEGER":return this.Primitive.string;default:Be(t)}}};St();var Zjn=class extends D7{context;constructor({context:t}){super(t.generation),this.context=t}getFilePropertyInfo({body:t,value:r}){let n={fileFields:[],bodyPropertyFields:[]},i=this.context.getRecord(r)??{};for(let o of t.properties)switch(o.type){case"file":$a.Record.missingKey(i,o.wireValue)&&(i[o.wireValue]="[bytes]"),n.fileFields.push({name:this.context.getPropertyName(o.name),value:this.getSingleFileProperty({property:o,record:i})});break;case"fileArray":$a.Record.missingKey(i,o.wireValue)&&(i[o.wireValue]=["[bytes]"]),n.fileFields.push({name:this.context.getPropertyName(o.name),value:this.getArrayFileProperty({property:o,record:i})});break;case"bodyProperty":if($a.Record.missingKey(i,o.name.wireValue))switch(o.typeReference.type){case"optional":break;case"primitive":{switch(o.typeReference.value.toLowerCase()){case"integer":{i[o.name.wireValue]=123;break}case"string":{i[o.name.wireValue]="[string]";break}case"boolean":{i[o.name.wireValue]=!0;break}case"double":{i[o.name.wireValue]=123.456;break}case"float":{i[o.name.wireValue]=123.456;break}case"long":{i[o.name.wireValue]=123456789;break}case"uint":{i[o.name.wireValue]=123;break}case"uint64":{i[o.name.wireValue]=12345;break}case"date":{i[o.name.wireValue]=new Date(2021,1,1);break}case"datetime":{i[o.name.wireValue]=new Date(2021,1,1,12,0,0);break}case"uuid":{i[o.name.wireValue]="123e4567-e89b-12d3-a456-426614174000";break}case"base64":{i[o.name.wireValue]="SGVsbG8gd29ybGQh";break}case"biginteger":{i[o.name.wireValue]="12345678901234567890";break}}break}default:break}n.bodyPropertyFields.push({name:this.context.getPropertyName(o.name.name),value:this.getBodyProperty({property:o,record:i})});break;default:Be(o)}return n}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r});return n==null?this.csharp.Literal.nop():this.context.getFileParameterForString(n)}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});return n==null?this.csharp.Literal.nop():this.csharp.Literal.list({valueType:this.Types.FileParameter,values:n.map(i=>this.context.getFileParameterForString(i))})}getBodyProperty({property:t,record:r}){let n=r[t.name.wireValue];return n==null?this.csharp.Literal.nop():this.context.dynamicLiteralMapper.convert({typeReference:t.typeReference,value:n})}};var eMn=class e extends $v{ir;dynamicTypeMapper;dynamicLiteralMapper;filePropertyMapper;generation;get namespaces(){return this.generation.namespaces}get registry(){return this.generation.registry}get settings(){return this.generation.settings}get constants(){return this.generation.constants}get names(){return this.generation.names}get model(){return this.generation.model}get format(){return this.generation.format}get csharp(){return this.generation.csharp}get Types(){return this.generation.Types}get System(){return this.generation.extern.System}get NUnit(){return this.generation.extern.NUnit}get OneOf(){return this.generation.extern.OneOf}get Google(){return this.generation.extern.Google}get WireMock(){return this.generation.extern.WireMock}get Primitive(){return this.generation.Primitive}get Value(){return this.generation.Value}get Collection(){return this.generation.Collection}constructor({ir:t,config:r,options:n,generation:i}){super({ir:t,config:r,options:n}),this.ir=t,this.generation=i??new bLt(t,r.workspaceName,r.customConfig!=null?r.customConfig:{},r),this.dynamicTypeMapper=new Xjn({context:this}),this.dynamicLiteralMapper=new Yjn({context:this}),this.filePropertyMapper=new Zjn({context:this})}clone(){return new e({ir:this.ir,config:this.config,options:this.options,generation:this.generation})}getFileParameterForString(t){return this.csharp.Literal.reference(this.csharp.instantiateClass({classReference:this.Types.FileParameter,arguments_:[],properties:[{name:"Stream",value:this.getMemoryStreamForString(t)}],multiline:!0}))}getMemoryStreamForString(t){return this.System.IO.MemoryStream.new({arguments_:[this.csharp.invokeMethod({on:this.System.Text.Encoding_UTF8,method:"GetBytes",arguments_:[this.csharp.Literal.string(t)]})]})}getClassName(t){return t.pascalCase.safeName}getParameterName(t){return t.camelCase.safeName}getPropertyName(t){return t.pascalCase.safeName}getMethodName(t){return`${t.pascalCase.safeName}Async`}getNamespace(t,r){let n=this.getNamespaceSegments(t);return n=r!=null?[...n,r]:n,[this.namespaces.root,...n].join(".")}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return this.getEnvironmentClassReferenceForEnumName(r)}getEnvironmentClassReferenceForEnumName(t){return this.csharp.classReference({name:`${this.generation.Types.Environments.name}.${this.getClassName(t)}`,namespace:this.namespaces.root})}getNamespaceSegments(t){return(this.settings.explicitNamespaces?t.allParts:t.packagePath).map(n=>n.pascalCase.safeName)}precalculate(t){this.generation.initialize(),this.System.Collections.Generic.KeyValuePair(),this.System.Collections.Generic.IEnumerable(),this.System.Collections.Generic.IAsyncEnumerable(),this.System.Collections.Generic.HashSet(),this.System.Collections.Generic.List(),this.System.Collections.Generic.Dictionary(),this.System.Threading.Tasks.Task(),Object.entries(this.ir.types).sort((r,n)=>r[0].length-n[0].length).forEach(([r,n])=>{this.dynamicTypeMapper.convertToClassReference(n)});for(let[r,n]of t.entries())if(this.csharp.classReference({origin:this.model.staticExplicit(`Example${r}`),namespace:"Usage"}),n.endpoint){let i=this.resolveEndpointLocation(n.endpoint);for(let o of i)switch(o.request.type){case"inlined":this.csharp.classReference({origin:o.request.declaration.name,namespace:this.getNamespace(o.request.declaration.fernFilepath)});break;case"body":break}}this.generation.Types.ClientOptions,this.generation.Types.RootClient,this.csharp.freezeClassReferences()}};St();Bi();var tMn=class extends D7{context;constructor({context:t}){super(t.generation),this.context=t}async generateSnippet({endpoint:t,request:r,options:n}){return this.buildCodeBlock({endpoint:t,snippet:r,options:n}).toString({namespace:"Usage",generation:this.generation,allNamespaceSegments:new Set,allTypeClassReferences:new Map,skipGlobalQualifier:!0})}generateSnippetSync({endpoint:t,request:r,options:n}){return this.buildCodeBlock({endpoint:t,snippet:r,options:n}).toString({namespace:"Usage",generation:this.generation,allNamespaceSegments:new Set,allTypeClassReferences:new Map,skipGlobalQualifier:!0})}async generateSnippetAst({endpoint:t,request:r,options:n}){throw new Error("Unsupported")}buildCodeBlock({endpoint:t,snippet:r,options:n}){if(t.examples&&!t.examples?.find(s=>$a.DynamicIR.EndpointExample(r)&&s.id===r.id))throw new Error("Endpoint does not have an example that matches the snippet");let i=this.csharp.codeblock(s=>{s.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),s.newLine(),s.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))}),o=this.getStyle(n);switch(o){case CC.Concise:return i;case CC.Full:return this.buildFullCodeBlock({body:i,options:n});default:Be(o)}}buildFullCodeBlock({body:t,options:r}){let n=this.getConfig(r),i=this.csharp.class_({name:n.fullStyleClassName??"Example",namespace:"Usage",access:Hft.Access.Public});return i.addNamespaceReference(this.Types.RootClient.namespace),i.addMethod({name:"Do",access:Hft.Access.Public,isAsync:!0,parameters:[],body:t}),i}constructClient({endpoint:t,snippet:r}){return this.csharp.codeblock(n=>{n.write("var client = "),n.writeNode(this.getRootClientConstructorInvocation(this.getConstructorArgs({endpoint:t,snippet:r})))})}callMethod({endpoint:t,snippet:r}){let n=t.response?.type==="streaming"||t.response?.type==="streamParameter",i=this.csharp.invokeMethod({on:this.csharp.codeblock("client"),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:r}),async:!0,configureAwait:!0,multiline:!0,isAsyncEnumerable:n});return n?this.csharp.codeblock(o=>{o.write("await foreach (var item in "),o.writeNode(i),o.writeLine(")"),o.pushScope(),o.writeLine("/* consume each item */"),o.popScope()}):i}getConstructorArgs({endpoint:t,snippet:r}){let n=[];t.auth!=null&&(r.auth!=null?n.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Ir.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`}));let i=[],o=this.getConstructorBaseUrlArgs({baseUrl:r.baseURL,environment:r.environment});o.length>0&&i.push(...o),this.context.errors.scope(Lo.Headers);let s=[];if(this.context.ir.headers!=null&&r.headers!=null&&s.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),this.settings.unifiedClientOptions){let a=[...n.map(u=>({name:gc(u.name),assignment:u.assignment})),...s.map(u=>({name:gc(u.name),assignment:u.assignment})),...i.map(u=>({name:u.name,assignment:u.assignment}))];return a.length===0?[]:[{name:"clientOptions",assignment:this.csharp.instantiateClass({classReference:this.Types.ClientOptions,arguments_:a,multiline:!0})}]}return i.length===0?[...n,...s]:[...n,...s,{name:"clientOptions",assignment:this.csharp.instantiateClass({classReference:this.Types.ClientOptions,arguments_:i.map(a=>({name:a.name,assignment:a.assignment})),multiline:!0})}]}getConstructorBaseUrlArgs({baseUrl:t,environment:r}){let n=this.getBaseUrlArg({baseUrl:t,environment:r});return $a.Literal.nop(n)?[]:[{name:this.getBaseUrlOptionName(),assignment:n}]}getBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null)return this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"}),this.csharp.Literal.nop();if(t!=null)return this.context.ir.environments?.environments.type==="multipleBaseUrls"?(this.context.errors.add({severity:Ir.Critical,message:"The C# SDK doesn't support a baseUrl when multiple URL environments are configured"}),this.csharp.Literal.nop()):this.csharp.Literal.string(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);return n==null?(this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`}),this.csharp.Literal.nop()):this.csharp.Literal.reference(n)}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?this.csharp.Literal.reference(this.csharp.instantiateClass({classReference:this.Types.Environments,arguments_:Object.entries(r).map(([n,i])=>({name:gc(qn(n)),assignment:this.context.dynamicLiteralMapper.convert({typeReference:{type:"primitive",value:"STRING"},value:i})})),multiline:!0})):this.csharp.Literal.nop()}return this.csharp.Literal.nop()}getConstructorAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?this.getConstructorBasicAuthArg({auth:t,values:r}):[];case"bearer":return r.type==="bearer"?this.getConstructorBearerAuthArgs({auth:t,values:r}):[];case"header":return r.type==="header"?this.getConstructorHeaderAuthArgs({auth:t,values:r}):[];case"oauth":return r.type==="oauth"?this.getConstructorOAuthArgs({auth:t,values:r}):[];case"inferred":return r.type==="inferred"?this.getConstructorInferredAuthArgs({auth:t,values:r}):[];default:Be(t)}}addError(t){this.context.errors.add({severity:Ir.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:r}){return[{name:this.context.getParameterName(t.username),assignment:this.csharp.Literal.string(r.username)},{name:this.context.getParameterName(t.password),assignment:this.csharp.Literal.string(r.password)}]}getConstructorBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getParameterName(t.token),assignment:this.csharp.Literal.string(r.token)}]}getConstructorHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getParameterName(t.header.name.name),assignment:this.context.dynamicLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value,fallbackToDefault:t.header.name.wireValue})}]}getConstructorOAuthArgs({auth:t,values:r}){return[{name:this.context.getParameterName(t.clientId),assignment:this.csharp.Literal.string(r.clientId)},{name:this.context.getParameterName(t.clientSecret),assignment:this.csharp.Literal.string(r.clientSecret)}]}getConstructorInferredAuthArgs({auth:t,values:r}){let n=[];if(t.parameters!=null)for(let i of t.parameters){let o=i.name.wireValue,s=r.values?.[o];n.push({name:this.context.getParameterName(i.name.name),assignment:this.context.dynamicLiteralMapper.convert({typeReference:i.typeReference,value:s,fallbackToDefault:o})})}else this.context.errors.add({severity:Ir.Critical,message:"Inferred auth parameters are not defined in the IR. Please ensure you're using IR version 62.3.0 or later."});return n}getConstructorHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getConstructorHeaderArg({header:i,value:o});s!=null&&n.push({name:this.context.getParameterName(i.name.name),assignment:s})}return n}getConstructorHeaderArg({header:t,value:r}){let n=this.context.dynamicLiteralMapper.convert({typeReference:t.typeReference,value:r,fallbackToDefault:t.name.wireValue});if(!$a.Literal.nop(n))return n}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[],o=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];o.length>0&&i.push(...this.getPathParameters({namedParameters:o,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let s=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:this.settings.shouldInlinePathParameters})||n.push(...i.map(a=>a.value)),n.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:this.settings.shouldInlinePathParameters})?i:[],filePropertyInfo:s})),n}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Lo.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicLiteralMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.Headers);let u=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicLiteralMapper.convert({...l,fallbackToDefault:l.name.wireValue})}));this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let c=t.body!=null?this.getInlinedRequestBodyConstructorFields({body:t.body,value:r.requestBody,filePropertyInfo:i}):[];return this.context.errors.unscope(),this.csharp.Literal.class_({reference:this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),fields:[...n,...s,...u,...c]})}getInlinedRequestBodyConstructorFields({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyConstructorFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyConstructorField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyConstructorFields({filePropertyInfo:n});default:Be(t)}}getInlinedRequestBodyPropertyConstructorFields({parameters:t,value:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicLiteralMapper.convert({...o,fallbackToDefault:o.name.wireValue})});return n}getFileUploadRequestBodyConstructorFields({filePropertyInfo:t}){return[...t.fileFields,...t.bodyPropertyFields]}getReferencedRequestBodyPropertyConstructorField({body:t,value:r}){return{name:this.context.getPropertyName(t.bodyKey),value:this.getReferencedRequestBodyPropertyLiteral({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicLiteralMapper.convert({typeReference:t.value,value:r,fallbackToDefault:JSON.stringify(t.value)});default:Be(t)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];return i.length>0&&n.push(...this.getPathParameters({namedParameters:i,snippet:r}).map(o=>o.value)),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),t.body!=null&&n.push(this.getBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope(),n}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return t.value.type==="optional"&&r==null?this.csharp.Literal.null():this.context.dynamicLiteralMapper.convert({typeReference:t.value,value:r,fallbackToDefault:JSON.stringify(t.value)});default:Be(t)}}getBytesBodyRequestArg({value:t}){let r=this.context.getValueAsString({value:t});return r==null&&(this.context.errors.add({severity:Ir.Critical,message:"The bytes request body must be provided in string format"}),r="[bytes]"),this.csharp.Literal.reference(this.context.getMemoryStreamForString(r))}getRootClientConstructorInvocation(t){return this.csharp.instantiateClass({classReference:this.Types.RootClient,arguments_:t,forceUseConstructor:!0,multiline:!0})}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValueOrDefault({parameters:t,values:r.pathParameters??{}});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicLiteralMapper.convert({...o,fallbackToDefault:o.name.wireValue})});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getClassName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getBaseUrlOptionName(){return this.context.ir.environments?.environments.type==="multipleBaseUrls"?"Environment":"BaseUrl"}getStyle(t){return t.style??this.context.options.style??CC.Full}getConfig(t){return t.config??this.context.options.config??{}}};var ELt=class extends Wv{constructor({ir:t,config:r,options:n={}}){super(new eMn({ir:t,config:r,options:n}))}precalculate(t){this.context.precalculate(t)}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new tMn({context:t})}};qt();var Jft=require("fs/promises"),cYu=Ae(require("path"),1);function pS(e){let t=e.endpoint.method;if(t!=="HEAD")return{...e,baseURL:e.baseUrl,endpoint:{...e.endpoint,method:t},auth:PTm(e.auth)}}function PTm(e){if(e!=null)return e}function uYu(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,DTm(r)]).filter(([t,r])=>r!=null))}function DTm(e){let t=e.location.method;if(t!=="HEAD")return{...e,location:{...e.location,method:t},examples:e.examples!=null?RTm(e.examples):void 0,auth:kTm(e.auth)}}function RTm(e){return e.map(t=>FTm(t)).filter(t=>t!=null)}function FTm(e){let t=e.endpoint.method;if(t!=="HEAD")return{...e,baseURL:e.baseUrl,endpoint:{...e.endpoint,method:t},auth:NTm(e.auth)}}function NTm(e){if(e!=null)return e}function kTm(e){if(e!=null)return e}function fS(e){return{...e,endpoints:uYu(e.endpoints)}}var QTm=`
2493
+ ${kMt()}`)}return this.generation.registry.registerClassReference(t,r)}freezeClassReferences(){this.frozen=!0}getPropertyName(t,r){let n=this.model.getPropertyNameFor(r),i=this.model.origin(r)??Uy(`Origin not found for property: ${JSON.stringify(r).substring(0,100)}`),o=t.getFieldName(i,n);return o||n}class_(t){let r=t;return"reference"in t&&(r={...t.reference,...t}),new One(r,this.generation)}testClass(t){return new $ft(t,this.generation)}annotation(t){return new afe(t,this.generation)}annotationGroup(t){return new Qft(t,this.generation)}instantiateClass(t){return new Eft(t,this.generation)}invokeMethod(t){return new Cft(t,this.generation)}codeblock(t){return new RSe(t,this.generation)}code(){return new FSe({},this.generation)}anonymousFunction(t){return new jft(t)}parameter(t){return new T7(t,this.generation)}interface_(t){return new Wft(t,this.generation)}enum_(t){return new Gft(t,this.generation)}dictionary(t){return new vft(t,this.generation)}list(t){return new wft(t,this.generation)}readOnlyMemory(t){return new xft(t,this.generation)}set(t){return new _ft(t,this.generation)}switch_(t){return new Lft(t,this.generation)}ternary(t){return new Uft(t,this.generation)}and(t){return new kft(t,this.generation)}or(t){return new Mft(t,this.generation)}enumInstantiation(t){return new Ift(t,this.generation)}string_(t){return new Sft(t,this.generation)}xmlDocBlock(t){return new kSe(t,this.generation)}InstantiatedPrimitive={string:t=>new IB({type:"string",value:t},this.generation),boolean:t=>new IB({type:"boolean",value:t},this.generation),integer:t=>new IB({type:"integer",value:t},this.generation),long:t=>new IB({type:"long",value:t},this.generation),uint:t=>new IB({type:"uint",value:t},this.generation),ulong:t=>new IB({type:"ulong",value:t},this.generation),float:t=>new IB({type:"float",value:t},this.generation),double:t=>new IB({type:"double",value:t},this.generation),date:t=>new IB({type:"date",value:t},this.generation),dateTime:(t,r=!0)=>new IB({type:"dateTime",value:t,parse:r},this.generation),uuid:t=>new IB({type:"uuid",value:t},this.generation),null:()=>new IB({type:"null"},this.generation)};Literal={class_:({reference:t,fields:r})=>new Zc.Class_(t,r,this.generation),dictionary:({keyType:t,valueType:r,entries:n})=>new Zc.Dictionary(t,r,n,this.generation),list:({valueType:t,values:r})=>new Zc.List(t,r,this.generation),set:({valueType:t,values:r})=>new Zc.Set(t,r,this.generation),boolean:t=>new Zc.Boolean(t,this.generation),float:t=>new Zc.Float(t,this.generation),date:t=>new Zc.Date(t,this.generation),datetime:t=>new Zc.DateTime(t,this.generation),decimal:t=>new Zc.Decimal(t,this.generation),double:t=>new Zc.Double(t,this.generation),integer:t=>new Zc.Integer(t,this.generation),long:t=>new Zc.Long(t,this.generation),uint:t=>new Zc.Uint(t,this.generation),ulong:t=>new Zc.Ulong(t,this.generation),reference:t=>new Zc.Reference(t,this.generation),string:t=>new Zc.String(t,this.generation),null:()=>new Zc.Null(this.generation),nop:()=>new Zc.Nop(this.generation),unknown:t=>new Zc.Unknown(t,this.generation)};xmlDocBlockOf(t){return t instanceof kSe?t:new kSe(t,this.generation)}VALID_READ_ONLY_MEMORY_TYPES=new Set(["int","long","uint","ulong","string","bool","float","double"]);validateReadOnlyMemoryTypes(){for(let t of this.generation.settings.readOnlyMemoryTypes)if(!this.VALID_READ_ONLY_MEMORY_TYPES.has(t))throw new Error(`Type "${t}" is not a valid 'read-only-memory-types' custom config option; expected one of ${JSON.stringify(this.VALID_READ_ONLY_MEMORY_TYPES)}.`)}};function uc(e){let t={},r={};for(let[n,i]of Object.entries(e))i.length===0?Object.defineProperty(r,n,{get(){return n in t||(t[n]=i()),t[n]},enumerable:!0,configurable:!0}):r[n]=i;return r}var Hjn=class{generation;constructor(t){this.generation=t}get csharp(){return this.generation.csharp}System=uc({Action:t=>this.csharp.classReference({name:"Action",namespace:"System",generics:t||void 0,multipartMethodName:null,multipartMethodNameForCollection:null,isReferenceType:!0}),Func:(t,r)=>this.csharp.classReference({name:"Func",namespace:"System",generics:t?r?[...t,r]:t:r?[r]:void 0,multipartMethodName:null,multipartMethodNameForCollection:null,isReferenceType:!0}),DateOnly:()=>this.csharp.classReference({name:"DateOnly",namespace:"System"}),DateTime:()=>this.csharp.classReference({name:"DateTime",namespace:"System"}),Enum:()=>this.csharp.classReference({name:"Enum",namespace:"System"}),Exception:()=>this.csharp.classReference({name:"Exception",namespace:"System"}),ReadOnlyMemory:t=>this.csharp.classReference({name:"ReadOnlyMemory",namespace:"System",generics:[t]}),Serializable:()=>this.csharp.classReference({name:"SerializableAttribute",namespace:"System"}),String:()=>this.csharp.classReference({name:"String",namespace:"System"}),Type:()=>this.csharp.classReference({name:"Type",namespace:"System",isReferenceType:!0,multipartMethodName:null,multipartMethodNameForCollection:null,fullyQualified:!0}),TimeSpan:()=>this.csharp.classReference({name:"TimeSpan",namespace:"System"}),Uri:()=>this.csharp.classReference({name:"Uri",namespace:"System"}),UriBuilder:()=>this.csharp.classReference({name:"UriBuilder",namespace:"System"}),Runtime:()=>uc({Serialization:()=>uc({EnumMember:()=>this.csharp.classReference({name:"EnumMemberAttribute",namespace:"System.Runtime.Serialization"})})}),Collections:()=>uc({Generic:()=>uc({IAsyncEnumerable:t=>this.csharp.classReference({name:"IAsyncEnumerable",namespace:"System.Collections.Generic",generics:t?[t]:void 0}),IEnumerable:t=>this.csharp.classReference({name:"IEnumerable",namespace:"System.Collections.Generic",generics:t?[t]:void 0}),KeyValuePair:(t,r)=>this.csharp.classReference({name:"KeyValuePair",namespace:"System.Collections.Generic",generics:t&&r?[t,r]:void 0}),List:t=>this.csharp.classReference({name:"List",namespace:"System.Collections.Generic",generics:t?[t]:void 0,isCollection:!0}),HashSet:t=>this.csharp.classReference({name:"HashSet",namespace:"System.Collections.Generic",generics:t?[t]:void 0,isCollection:!0}),Dictionary:(t,r)=>this.csharp.classReference({name:"Dictionary",namespace:"System.Collections.Generic",generics:t&&r?[t,r]:void 0,isCollection:!0}),IDictionary:(t,r)=>this.csharp.classReference({name:"IDictionary",namespace:"System.Collections.Generic",generics:[t,r]})}),Linq:()=>uc({Enumerable:()=>this.csharp.classReference({name:"Enumerable",namespace:"System.Linq"})})}),Globalization:()=>uc({DateTimeStyles:()=>this.csharp.classReference({name:"DateTimeStyles",namespace:"System.Globalization"})}),Linq:()=>uc({Enumerable:()=>this.csharp.classReference({name:"Enumerable",namespace:"System.Linq"})}),Net:()=>uc({Http:()=>uc({HttpClient:()=>this.csharp.classReference({name:"HttpClient",namespace:"System.Net.Http"}),HttpMethod:()=>this.csharp.classReference({name:"HttpMethod",namespace:"System.Net.Http"}),HttpResponseHeaders:()=>this.csharp.classReference({name:"HttpResponseHeaders",namespace:"System.Net.Http.Headers"})}),ServerSentEvents:()=>uc({SseEvent:()=>this.csharp.classReference({name:"SseEvent",namespace:"System.Net.ServerSentEvents"}),SseParser:()=>this.csharp.classReference({name:"SseParser",namespace:"System.Net.ServerSentEvents"})}),WebSockets:()=>uc({ClientWebSocketOptions:()=>this.csharp.classReference({name:"ClientWebSocketOptions",namespace:"System.Net.WebSockets"})})}),IO:()=>uc({MemoryStream:()=>this.csharp.classReference({name:"MemoryStream",namespace:"System.IO"}),Stream:()=>this.csharp.classReference({name:"Stream",namespace:"System.IO"}),StreamReader:()=>this.csharp.classReference({name:"StreamReader",namespace:"System.IO"})}),Text:()=>uc({Encoding:()=>this.csharp.classReference({name:"Encoding",namespace:"System.Text"}),Encoding_UTF8:()=>this.csharp.classReference({name:"UTF8",enclosingType:this.csharp.classReference({name:"Encoding",namespace:"System.Text"})}),Json:()=>uc({JsonElement:()=>this.csharp.classReference({name:"JsonElement",namespace:"System.Text.Json"}),JsonDocument:()=>this.csharp.classReference({name:"JsonDocument",namespace:"System.Text.Json"}),JsonException:()=>this.csharp.classReference({name:"JsonException",namespace:"System.Text.Json"}),Utf8JsonReader:()=>this.csharp.classReference({name:"Utf8JsonReader",namespace:"System.Text.Json"}),JsonSerializerOptions:()=>this.csharp.classReference({name:"JsonSerializerOptions",namespace:"System.Text.Json"}),JsonSerializer:()=>this.csharp.classReference({name:"JsonSerializer",namespace:"System.Text.Json"}),Utf8JsonWriter:()=>this.csharp.classReference({name:"Utf8JsonWriter",namespace:"System.Text.Json"}),Nodes:()=>uc({JsonNode:()=>this.csharp.classReference({name:"JsonNode",namespace:"System.Text.Json.Nodes"}),JsonObject:()=>this.csharp.classReference({name:"JsonObject",namespace:"System.Text.Json.Nodes"})}),Serialization:()=>uc({IJsonOnDeserialized:()=>this.csharp.classReference({name:"IJsonOnDeserialized",namespace:"System.Text.Json.Serialization"}),IJsonOnSerializing:()=>this.csharp.classReference({name:"IJsonOnSerializing",namespace:"System.Text.Json.Serialization"}),JsonOnDeserializedAttribute:()=>this.csharp.classReference({name:"JsonOnDeserializedAttribute",namespace:"System.Text.Json.Serialization"}),JsonExtensionData:()=>this.csharp.classReference({name:"JsonExtensionDataAttribute",namespace:"System.Text.Json.Serialization"}),JsonConverter:t=>this.csharp.classReference({name:"JsonConverter",namespace:"System.Text.Json.Serialization",generics:t?[t]:void 0}),JsonIgnore:()=>this.csharp.classReference({name:"JsonIgnoreAttribute",namespace:"System.Text.Json.Serialization"}),JsonPropertyName:()=>this.csharp.classReference({name:"JsonPropertyNameAttribute",namespace:"System.Text.Json.Serialization"})})})}),Threading:()=>uc({CancellationToken:()=>this.csharp.classReference({name:"CancellationToken",namespace:"System.Threading"}),Tasks:()=>uc({Task:t=>this.csharp.classReference({name:"Task",namespace:"System.Threading.Tasks",generics:t?[t]:void 0}),ValueTask:t=>this.csharp.classReference({name:"ValueTask",namespace:"System.Threading.Tasks",generics:t?[t]:void 0})})}),ComponentModel:()=>uc({INotifyPropertyChanged:()=>this.csharp.classReference({name:"INotifyPropertyChanged",namespace:"System.ComponentModel"}),PropertyChangedEventHandler:()=>this.csharp.classReference({name:"PropertyChangedEventHandler",namespace:"System.ComponentModel"})}),IAsyncDisposable:()=>this.csharp.classReference({name:"IAsyncDisposable",namespace:"System"}),IDisposable:()=>this.csharp.classReference({name:"IDisposable",namespace:"System"})});NUnit=uc({Framework:()=>uc({TestFixture:()=>this.csharp.classReference({name:"TestFixture",namespace:"NUnit.Framework"}),Test:()=>this.csharp.classReference({name:"Test",namespace:"NUnit.Framework"}),OneTimeTearDown:()=>this.csharp.classReference({name:"OneTimeTearDown",namespace:"NUnit.Framework"}),OneTimeSetUp:()=>this.csharp.classReference({name:"OneTimeSetUp",namespace:"NUnit.Framework"}),SetUpFixture:()=>this.csharp.classReference({name:"SetUpFixture",namespace:"NUnit.Framework"}),Parallelizable:()=>this.csharp.classReference({name:"Parallelizable",namespace:"NUnit.Framework"})})});OneOf=uc({OneOf:t=>this.csharp.classReference({name:"OneOf",namespace:"OneOf",generics:t}),OneOfBase:t=>this.csharp.classReference({name:"OneOfBase",namespace:"OneOf",generics:t})});Google=uc({Protobuf:()=>uc({ByteString:()=>this.csharp.classReference({name:"ByteString",namespace:"Google.Protobuf"}),WellKnownTypes:()=>uc({Struct:()=>this.csharp.classReference({name:"Struct",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"}),Value:()=>this.csharp.classReference({name:"Value",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"}),ListValue:()=>this.csharp.classReference({name:"ListValue",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"}),Timestamp:()=>this.csharp.classReference({name:"Timestamp",namespace:"Google.Protobuf.WellKnownTypes",namespaceAlias:"WellKnownProto"})})})});WireMock=uc({Server:()=>this.csharp.classReference({name:"WireMockServer",namespace:"WireMock.Server"}),WireMockServerSettings:()=>this.csharp.classReference({name:"WireMockServerSettings",namespace:"WireMock.Settings"}),WireMockConsoleLogger:()=>this.csharp.classReference({name:"WireMockConsoleLogger",namespace:"WireMock.Logging"})});Grpc=uc({Core:()=>uc({RpcException:()=>this.csharp.classReference({name:"RpcException",namespace:"Grpc.Core"})})})};var smo=new Set(["name","camelCase","snakeCase","screamingSnakeCase","pascalCase"]);function TTm(e,t){return smo.has(t)?e??"":e?`${e}.${t}`:t}var Kjn=class{generation;indexByObject=new Map;indexByPath=new Map;explicitByObject=new Map;explicitByPath=new Map;root;ir;get csharp(){return this.generation.csharp}get registry(){return this.generation.registry}constructor(t,r){this.generation=r,this.root=this.createIndex(t),this.ir=t}createIndex(t,r="",n){let i=TTm(n?.jsonPath,r);if(this.indexByPath.has(i)){n||Uy(`Parent provenance not found for node: ${JSON.stringify(t).substring(0,100)}`),this.indexByObject.set(t,n);let s=smo.has(r);for(let[a,u]of Object.entries(t))typeof u=="object"&&u!==null&&(s&&smo.has(a)?this.indexByObject.set(u,n):this.createIndex(u,a,n));return n}let o={jsonPath:i,name:r,node:t,parent:n};this.indexByObject.set(t,o),this.indexByPath.set(i,o);for(let[s,a]of Object.entries(t))typeof a=="object"&&a!==null&&this.createIndex(a,s,o);return o}staticExplicit(t){return this.explicit(this.ir,t)}explicit(t,r){let n=this.provenance(t)??Uy(`Provenance not found for node: ${JSON.stringify(t).substring(0,100)}`),i={...n,jsonPath:`${n.jsonPath}+${r}`,name:r,node:n.node,parent:n,explicit:!0},o=this.explicitByObject.get(n.node);return o?o.add(i):this.explicitByObject.set(n.node,new Set([i])),this.explicitByPath.set(i.jsonPath,i),i}provenance(t){if(t!==void 0)return $a.string(t)?this.explicitByPath.get(t)??this.indexByPath.get(t):$a.Provenance(t)?this.explicitByPath.get(t.jsonPath)??this.indexByPath.get(t.jsonPath):this.indexByObject.get(t)}origin(t){let r=this.provenance(t);return r?.explicit?r:r?.node}irNode(t){return this.provenance(t)?.node}jsonPath(t){return this.provenance(t)?.jsonPath}getEnumValueName(t,r){let n=$a.IR.ExampleEnumType(r)?r.value.name:r.name,i=t.values.find(o=>this.nameEquals(o.name.name,n));return i?this.getPropertyNameFor(i):Uy(`Unexpected - can't find enum value ${n} in enum`)}getPropertyNameFor(t){let r=this.registry.getFieldNameByOrigin(t);if(r)return r;if($a.Provenance(t))return t.name;if("name"in t){if($a.IR.NameAndWireValue(t.name))return t.name.name.pascalCase.safeName;if($a.IR.Name(t.name))return t.name.pascalCase.safeName;if(typeof t.name=="string")return t.name}if("pascalCase"in t)return t.pascalCase.safeName;throw new Error(`Unknown property type: ${this.jsonPath(t)}`)}getClassNameFor(t){if($a.Provenance(t))return t.name;if("name"in t){if($a.IR.TypeDeclaration(t)||$a.IR.NameAndWireValue(t.name))return t.name.name.pascalCase.safeName;if($a.IR.Name(t.name))return t.name.pascalCase.safeName;if(typeof t.name=="string")return t.name}if("pascalCase"in t)return t.pascalCase.safeName;throw new Error(`Unknown property type: ${JSON.stringify(t)}`)}nameEquals(t,r){return t.camelCase.safeName===r.camelCase.safeName}dereferenceType(t){let r=$a.string(t)?t:$a.IR.NamedType(t)||$a.IR.DeclaredTypeName(t)?t.typeId:$a.IR.ExampleNamedType(t)?t.typeName.typeId:t.name.typeId,n=this.irNode(this.ir.types[r]);if($a.IR.TypeDeclaration(n))return{typeId:r,typeDeclaration:n};Uy(`dereferenceType: typeId ${r} not resolved.`)}};function Jjn(...e){return e.filter(Boolean).join("/")}var bLt=class{intermediateRepresentation;apiName;customConfig;generatorConfig;support;constructor(t,r,n,i,o={makeRelativeFilePath:s=>s,makeAbsoluteFilePath:s=>s,getNamespaceForTypeId:s=>"",getDirectoryForTypeId:s=>"",getCoreAsIsFiles:()=>[],getCoreTestAsIsFiles:()=>[],getPublicCoreAsIsFiles:()=>[],getAsyncCoreAsIsFiles:()=>[],getChildNamespaceSegments:s=>[]}){this.intermediateRepresentation=t,this.apiName=r,this.customConfig=n,this.generatorConfig=i,this.support=o,this.model=new Kjn(t,this),this.ir=$a.IR.IntermediateRepresentation(t)?t:{},this.dir=$a.DynamicIR.DynamicIntermediateRepresentation(t)?t:{}}ir;dir;csharp=new $jn(this);registry=new Kft(this);model;extern=new Hjn(this);settings=uc({namespace:()=>this.customConfig.namespace??Njn(kjn(`${this.generatorConfig.organization}_${this.apiName}`)),readOnlyMemoryTypes:()=>this.customConfig["read-only-memory-types"]??[],simplifyObjectDictionaries:()=>this.customConfig["simplify-object-dictionaries"]??!1,useFullyQualifiedNamespaces:()=>this.customConfig["experimental-fully-qualified-namespaces"]??!1,useDotnetFormat:()=>this.customConfig["experimental-dotnet-format"]??!1,enableWebsockets:()=>this.customConfig["experimental-enable-websockets"]??!1,enableReadonlyConstants:()=>this.customConfig["experimental-readonly-constants"]??!1,generateLiterals:()=>this.customConfig["generate-literals"]??this.customConfig["experimental-readonly-constants"]??!1,enableExplicitNullableOptional:()=>this.customConfig["experimental-explicit-nullable-optional"]??!1,useDefaultRequestParameterValues:()=>this.customConfig["use-default-request-parameter-values"]??!1,redactResponseBodyOnError:()=>this.customConfig["redact-response-body-on-error"]??!1,temporaryWebsocketEnvironments:()=>this.customConfig["temporary-websocket-environments"]??{},baseApiExceptionClassName:()=>this.customConfig["base-api-exception-class-name"]??"",baseExceptionClassName:()=>this.customConfig["base-exception-class-name"]??"",shouldGeneratedDiscriminatedUnions:()=>this.customConfig["use-discriminated-unions"]??!0,shouldGenerateUndiscriminatedUnions:()=>this.customConfig["use-undiscriminated-unions"]??!1,exportedClientClassName:()=>this.customConfig["exported-client-class-name"]??"",clientClassName:()=>this.customConfig["client-class-name"]??"",rootNamespaceForCoreClasses:()=>this.customConfig["root-namespace-for-core-classes"]??!0,packageId:()=>this.customConfig["package-id"]??"",isForwardCompatibleEnumsEnabled:()=>this.customConfig["enable-forward-compatible-enums"]??this.customConfig["experimental-enable-forward-compatible-enums"]??!0,websocketEnvironments:()=>this.customConfig["temporary-websocket-environments"]??{},customPagerName:()=>this.customConfig["custom-pager-name"]??"",environmentClassName:()=>this.customConfig["environment-class-name"]??"",generateErrorTypes:()=>this.customConfig["generate-error-types"]??!0,shouldInlinePathParameters:()=>this.customConfig["inline-path-parameters"]??!0,includeExceptionHandler:()=>this.customConfig["include-exception-handler"]??!1,exceptionInterceptorClassName:()=>this.customConfig["exception-interceptor-class-name"]??"",shouldGenerateMockServerTests:()=>this.customConfig["generate-mock-server-tests"]??this.customConfig["enable-wire-tests"]??!0,rootClientAccess:()=>this.customConfig["root-client-class-access"]=="internal"?_w.Internal:_w.Public,extraDependencies:()=>this.customConfig["extra-dependencies"]??{},omitFernHeaders:()=>this.customConfig["omit-fern-headers"]??!1,unifiedClientOptions:()=>this.customConfig["unified-client-options"]??!1,pascalCaseEnvironments:()=>this.customConfig["pascal-case-environments"]??!0,slnFormat:()=>this.customConfig["sln-format"]??"slnx",explicitNamespaces:()=>this.customConfig["explicit-namespaces"]===!0,outputPath:()=>{let t=this.customConfig["output-path"];return t==null?{library:"src",test:"src",solution:".",other:"."}:typeof t=="string"?{library:t,test:t,solution:".",other:"."}:{library:t.library??"src",test:t.test??"src",solution:t.solution??".",other:t.other??"."}}});constants={folders:uc({mockServerTests:()=>this.support.makeRelativeFilePath("Unit/MockServer"),types:()=>"Types",exceptions:()=>"Exceptions",src:()=>"src",protobuf:()=>"proto",serializationTests:()=>this.support.makeRelativeFilePath("Unit/Serialization"),project:()=>this.support.makeRelativeFilePath(Jjn(this.constants.folders.sourceFiles,this.support.makeRelativeFilePath(this.names.files.project))),sourceFiles:()=>this.support.makeRelativeFilePath(this.constants.folders.src),coreFiles:()=>this.support.makeRelativeFilePath(Jjn(this.constants.folders.project,this.support.makeRelativeFilePath(this.constants.defaults.core))),publicCoreFiles:()=>this.support.makeRelativeFilePath(Jjn(this.constants.folders.project,this.support.makeRelativeFilePath(this.constants.defaults.core),this.support.makeRelativeFilePath(this.constants.defaults.publicCore))),testFiles:()=>this.support.makeRelativeFilePath(Jjn(this.constants.folders.sourceFiles,this.support.makeRelativeFilePath(this.names.files.testProject)))}),formatting:uc({indent:()=>" "}),defaults:uc({core:()=>"Core",publicCore:()=>"Public",version:()=>"0.0.0"})};namespaces=uc({root:()=>this.settings.namespace,core:()=>`${this.namespaces.root}.Core`,qualifiedRoot:()=>this.qualifyNamespace(this.namespaces.root),qualifiedCore:()=>this.qualifyNamespace(this.namespaces.core),test:()=>this.registry.canonicalizeNamespace(`${this.namespaces.root}.Test`),testUtils:()=>`${this.namespaces.test}.Utils`,mockServerTest:()=>`${this.namespaces.test}.Unit.MockServer`,publicCore:()=>this.namespaces.root,webSocketsCore:()=>`${this.namespaces.core}.WebSockets`,publicCoreTest:()=>`${this.namespaces.root}.Test.PublicCore`,asIsTestUtils:()=>`${this.namespaces.root}.Test.Utils`,publicCoreClasses:()=>this.settings.rootNamespaceForCoreClasses?this.namespaces.root:this.namespaces.core,implicit:()=>new Set(["System","System.Collections.Generic","System.IO","System.Linq","System.Threading","System.Threading.Tasks","System.Net.Http"])});names={classes:uc({baseApiException:()=>this.settings.baseApiExceptionClassName||`${this.names.project.clientPrefix}ApiException`,baseException:()=>this.settings.baseExceptionClassName||`${this.names.project.clientPrefix}Exception`,rootClient:()=>this.settings.clientClassName||`${this.names.project.clientPrefix}Client`,rootClientForSnippets:()=>this.settings.exportedClientClassName||this.names.classes.rootClient,customPager:()=>this.settings.customPagerName||`${this.names.project.packageId.replace(/[^a-zA-Z0-9]/g,"")}Pager`,environment:()=>this.settings.environmentClassName||`${this.names.project.clientPrefix}Environment`,exceptionInterceptor:()=>this.settings.exceptionInterceptorClassName||`${this.names.project.packageId.replace(/[^a-zA-Z0-9]/g,"")}ExceptionInterceptor`}),project:uc({client:()=>Njn(kjn(`${this.generatorConfig.organization}_${this.generatorConfig.workspaceName}`)),clientPrefix:()=>this.settings.exportedClientClassName||this.settings.clientClassName||this.names.project.client,packageId:()=>this.settings.packageId||this.namespaces.root}),files:uc({project:()=>this.namespaces.root,testProject:()=>`${this.namespaces.root}.Test`}),methods:uc({mockOauth:()=>"MockOAuthEndpoint",mockInferredAuth:()=>"MockInferredAuthEndpoint",getAccessTokenAsync:()=>"GetAccessTokenAsync",getAuthHeadersAsync:()=>"GetAuthHeadersAsync"}),variables:uc({client:()=>"client",response:()=>"response",httpRequest:()=>"httpRequest",sendRequest:()=>"sendRequest",responseBody:()=>"responseBody",query:()=>"_query",headers:()=>"_headers"}),parameters:uc({cancellationToken:()=>"cancellationToken",requestOptions:()=>"options",idempotentOptions:()=>"options"})};Types=uc({Arbitrary:t=>new Nf.ArbitraryType(t,this),HttpMethodExtensions:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("HttpMethodExtensions")}),FormRequest:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("FormRequest")}),Optional:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("Optional")}),ClientOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("ClientOptions"),namespace:this.namespaces.publicCoreClasses}),RawClient:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("RawClient")}),RequestOptions:()=>this.csharp.classReference({namespace:this.namespaces.publicCoreClasses,origin:this.model.staticExplicit("RequestOptions")}),RequestOptionsInterface:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("IRequestOptions")}),JsonRequest:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("JsonRequest")}),Version:()=>this.csharp.classReference({namespace:this.namespaces.publicCore,origin:this.model.staticExplicit("Version")}),ValueConvert:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("ValueConvert")}),FileParameter:()=>this.csharp.classReference({namespace:this.namespaces.publicCore,origin:this.model.staticExplicit("FileParameter"),multipartMethodName:"AddFileParameterPart",multipartMethodNameForCollection:"AddFileParameterParts",isReferenceType:!0}),Headers:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("Headers")}),HeaderValue:()=>this.csharp.classReference({namespace:this.namespaces.core,origin:this.model.staticExplicit("HeaderValue")}),RootClient:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.rootClient),namespace:this.namespaces.root}),RootClientForSnippets:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.rootClientForSnippets),namespace:this.namespaces.root}),BaseApiException:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.baseApiException),namespace:this.namespaces.publicCoreClasses}),BaseException:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.baseException),namespace:this.namespaces.publicCoreClasses}),ExceptionInterceptor:()=>this.csharp.classReference({origin:this.model.staticExplicit("IExceptionInterceptor"),namespace:this.namespaces.core}),ExceptionHandler:()=>this.csharp.classReference({origin:this.model.staticExplicit("ExceptionHandler"),namespace:this.namespaces.core}),CustomExceptionInterceptor:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.exceptionInterceptor),namespace:this.namespaces.core}),ProtoAnyMapper:()=>this.csharp.classReference({origin:this.model.staticExplicit("ProtoAnyMapper"),namespace:this.namespaces.core}),Constants:()=>this.csharp.classReference({origin:this.model.staticExplicit("Constants"),namespace:this.namespaces.core}),DateTimeSerializer:()=>this.csharp.classReference({origin:this.model.staticExplicit("DateTimeSerializer"),namespace:this.namespaces.core}),JsonUtils:()=>this.csharp.classReference({origin:this.model.staticExplicit("JsonUtils"),namespace:this.namespaces.core}),JsonAssert:()=>this.csharp.classReference({origin:this.model.staticExplicit("JsonAssert"),namespace:this.namespaces.testUtils}),CustomPagerFactory:()=>this.csharp.classReference({origin:this.model.staticExplicit(`${this.names.classes.customPager}Factory`),namespace:this.namespaces.core}),CustomPagerContext:()=>this.csharp.classReference({origin:this.model.staticExplicit(`${this.names.classes.customPager}Context`),namespace:this.namespaces.core}),Environments:()=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.environment),namespace:this.namespaces.publicCoreClasses}),TestClient:()=>this.csharp.classReference({origin:this.model.staticExplicit("TestClient"),namespace:this.namespaces.test}),BaseMockServerTest:()=>this.csharp.classReference({origin:this.model.staticExplicit("BaseMockServerTest"),namespace:this.namespaces.mockServerTest}),IdempotentRequestOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("IdempotentRequestOptions"),namespace:this.namespaces.publicCoreClasses}),IdempotentRequestOptionsInterface:()=>this.csharp.classReference({origin:this.model.staticExplicit("IIdempotentRequestOptions"),namespace:this.namespaces.core}),IStringEnum:()=>this.csharp.classReference({origin:this.model.staticExplicit("IStringEnum"),namespace:this.namespaces.core}),WebSocketClient:()=>this.csharp.classReference({origin:this.model.staticExplicit("WebSocketClient"),namespace:this.namespaces.webSocketsCore}),QueryBuilder:()=>this.csharp.classReference({origin:this.model.staticExplicit("Query"),namespace:this.namespaces.webSocketsCore}),QueryStringBuilder:()=>this.csharp.classReference({origin:this.model.staticExplicit("QueryStringBuilder"),namespace:this.namespaces.core}),QueryStringBuilderBuilder:()=>this.csharp.classReference({origin:this.model.staticExplicit("QueryStringBuilder.Builder"),namespace:this.namespaces.core}),OAuthTokenProvider:()=>this.csharp.classReference({origin:this.model.staticExplicit("OAuthTokenProvider"),namespace:this.namespaces.core}),InferredAuthTokenProvider:()=>this.csharp.classReference({origin:this.model.staticExplicit("InferredAuthTokenProvider"),namespace:this.namespaces.core}),ProtoConverter:()=>this.csharp.classReference({origin:this.model.staticExplicit("ProtoConverter"),namespace:this.namespaces.core}),RawGrpcClient:()=>this.csharp.classReference({origin:this.model.staticExplicit("RawGrpcClient"),namespace:this.namespaces.core}),Extensions:()=>this.csharp.classReference({origin:this.model.staticExplicit("Extensions"),namespace:this.namespaces.core}),GrpcRequestOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("GrpcRequestOptions"),namespace:this.namespaces.root}),GrpcChannelOptions:()=>this.csharp.classReference({origin:this.model.staticExplicit("GrpcChannelOptions"),namespace:"Grpc.Net.Client"}),StringEnum:t=>this.csharp.classReference({origin:this.model.staticExplicit("StringEnum"),namespace:this.namespaces.core,generics:t?[t]:void 0}),WebSocketEvent:t=>this.csharp.classReference({origin:this.model.staticExplicit("Event"),namespace:this.namespaces.webSocketsCore,generics:[t]}),ConnectionStatus:()=>this.csharp.classReference({origin:this.model.staticExplicit("ConnectionStatus"),namespace:this.namespaces.webSocketsCore}),WebSocketConnected:()=>this.csharp.classReference({origin:this.model.staticExplicit("Connected"),namespace:this.namespaces.webSocketsCore}),WebSocketClosed:()=>this.csharp.classReference({origin:this.model.staticExplicit("Closed"),namespace:this.namespaces.webSocketsCore}),ReconnectionInfo:()=>this.csharp.classReference({origin:this.model.staticExplicit("ReconnectionInfo"),namespace:this.namespaces.webSocketsCore}),CustomPagerClass:t=>this.csharp.classReference({origin:this.model.staticExplicit(this.names.classes.customPager),namespace:this.namespaces.core,generics:[t]}),Pager:t=>this.csharp.classReference({origin:this.model.staticExplicit("Pager"),namespace:this.namespaces.core,generics:[t]}),OffsetPager:({requestType:t,requestOptionsType:r,responseType:n,offsetType:i,stepType:o,itemType:s})=>this.csharp.classReference({origin:this.model.staticExplicit("OffsetPager"),namespace:this.namespaces.core,generics:[t,r,n,i,o,s]}),CursorPager:({requestType:t,requestOptionsType:r,responseType:n,cursorType:i,itemType:o})=>this.csharp.classReference({origin:this.model.staticExplicit("CursorPager"),namespace:this.namespaces.core,generics:[t,r,n,i,o]}),CollectionItemSerializer:(t,r)=>this.csharp.classReference({origin:this.model.staticExplicit("CollectionItemSerializer"),namespace:this.namespaces.core,generics:[t,r]}),OneOfSerializer:t=>this.csharp.classReference({origin:this.model.staticExplicit("OneOfSerializer"),namespace:this.namespaces.core,generics:[t]}),AdditionalProperties:t=>this.csharp.classReference({origin:this.model.staticExplicit("AdditionalProperties"),namespace:this.namespaces.publicCore,generics:t?[t]:void 0}),ReadOnlyAdditionalProperties:t=>this.csharp.classReference({origin:this.model.staticExplicit("ReadOnlyAdditionalProperties"),namespace:this.namespaces.publicCore,generics:t?[t]:void 0})});Primitive=uc({string:()=>new Nf.String(this),boolean:()=>new Nf.Boolean(this),integer:()=>new Nf.Integer(this),long:()=>new Nf.Long(this),uint:()=>new Nf.Uint(this),ulong:()=>new Nf.ULong(this),float:()=>new Nf.Float(this),double:()=>new Nf.Double(this),object:()=>new Nf.Object(this)});Value=uc({binary:()=>new sL.Binary(this),dateOnly:()=>new sL.DateOnly(this),dateTime:()=>new sL.DateTime(this),uuid:()=>new sL.Uuid(this),stringEnum:t=>new sL.StringEnum(t,this)});Collection=uc({array:t=>new uS.Array(t,this),listType:t=>new uS.ListType(t,this),list:t=>new uS.List(t,this),set:t=>new uS.Set(t,this),map:(t,r,n)=>new uS.Map(t,r,this,n),idictionary:(t,r,n)=>new uS.IDictionary(t,r,this,n),keyValuePair:(t,r)=>new uS.KeyValuePair(t,r,this)});format=uc({private:t=>`_${Qjn.camelCase(t)}`});initialize(){return this.initializers.implicitNamespaces}initializers=uc({implicitNamespaces:()=>{for(let t of this.namespaces.implicit)this.registry.addImplicitNamespace(t);return!0}});get System(){return this.extern.System}get NUnit(){return this.extern.NUnit}get OneOf(){return this.extern.OneOf}get Google(){return this.extern.Google}get Grpc(){return this.extern.Grpc}get WireMock(){return this.extern.WireMock}qualifyNamespace(t){let r=t.split(".")[0];return r&&this.registry.hasTypeNamespaceConflict(r)?`global::${t}`:t}};var D7=class{generation;constructor(t){this.generation=t}get csharp(){return this.generation.csharp}get settings(){return this.generation.settings}get constants(){return this.generation.constants}get namespaces(){return this.generation.namespaces}get names(){return this.generation.names}get model(){return this.generation.model}get format(){return this.generation.format}get registry(){return this.generation.registry}get Types(){return this.generation.Types}get System(){return this.generation.extern.System}get NUnit(){return this.generation.extern.NUnit}get OneOf(){return this.generation.extern.OneOf}get Google(){return this.generation.extern.Google}get Grpc(){return this.generation.extern.Grpc}get WireMock(){return this.generation.extern.WireMock}get Primitive(){return this.generation.Primitive}get Value(){return this.generation.Value}get Collection(){return this.generation.Collection}};St();var Yjn=class extends D7{context;constructor({context:t}){super(t.generation),this.context=t}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?this.csharp.Literal.null():(this.context.errors.add({severity:Ir.Critical,message:"Expected non-null value, but got null"}),this.csharp.Literal.nop());if(t.value===void 0&&!t.fallbackToDefault)return this.csharp.Literal.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value,fallbackToDefault:t.fallbackToDefault});case"literal":return this.convertLiteral({literal:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value,fallbackToDefault:t.fallbackToDefault});case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.csharp.Literal.nop():this.convertNamed({named:r,value:t.value,as:t.as,fallbackToDefault:t.fallbackToDefault})}case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as,fallbackToDefault:t.fallbackToDefault});case"set":return this.convertSet({set:t.typeReference.value,value:t.value,fallbackToDefault:t.fallbackToDefault});case"unknown":return this.convertUnknown({value:t.value,fallbackToDefault:t.fallbackToDefault});default:Be(t.typeReference)}}convertList({list:t,value:r,fallbackToDefault:n}){return Array.isArray(r)?this.csharp.Literal.list({valueType:this.context.dynamicTypeMapper.convert({typeReference:t,unboxOptionals:!0}),values:r.map((i,o)=>{this.context.errors.scope({index:o});try{return this.convert({typeReference:t,value:i})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),this.csharp.Literal.nop())}convertLiteral({literal:t,value:r,fallbackToDefault:n}){switch(t.type){case"boolean":{let i=this.context.getValueAsBoolean({value:r});return i==null?this.csharp.Literal.nop():this.csharp.Literal.boolean(i)}case"string":{let i=this.context.getValueAsString({value:r});return i==null?n?this.Primitive.string.getDeterminsticDefault(n):this.csharp.Literal.nop():this.csharp.Literal.string(i)}default:Be(t)}}convertSet({set:t,value:r,fallbackToDefault:n}){return Array.isArray(r)?this.csharp.Literal.set({valueType:this.context.dynamicTypeMapper.convert({typeReference:t,unboxOptionals:!0}),values:r.map((i,o)=>{this.context.errors.scope({index:o});try{return this.convert({typeReference:t,value:i})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),this.csharp.Literal.nop())}convertMap({map:t,value:r,fallbackToDefault:n}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),this.csharp.Literal.nop()):this.csharp.Literal.dictionary({keyType:this.context.dynamicTypeMapper.convert({typeReference:t.key}),valueType:t.value.type==="unknown"?this.context.dynamicTypeMapper.convert({typeReference:t.value}).asOptional():this.context.dynamicTypeMapper.convert({typeReference:t.value}),entries:Object.entries(r).map(([i,o])=>{this.context.errors.scope(i);try{return{key:this.convert({typeReference:t.key,value:i,as:"key"}),value:this.convert({typeReference:t.value,value:o})}}finally{this.context.errors.unscope()}})})}convertNamed({named:t,value:r,as:n,fallbackToDefault:i}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference,value:r,as:n,fallbackToDefault:i});case"discriminatedUnion":return this.settings.shouldGeneratedDiscriminatedUnions?this.convertDiscriminatedUnion({discriminatedUnion:t,value:r,fallbackToDefault:i}):this.convertUnknown({value:r,fallbackToDefault:i});case"enum":return this.getEnumValue(t,r);case"object":return this.convertObject({object_:t,value:r,fallbackToDefault:i});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,fallbackToDefault:i});default:Be(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r,fallbackToDefault:n}){let i=this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),o=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(o==null)return this.csharp.Literal.nop();let s=o.singleDiscriminatedUnionType,a=this.getBaseProperties({discriminatedUnionTypeInstance:o,singleDiscriminatedUnionType:s});switch(s.type){case"samePropertiesAsObject":{let u=this.context.resolveNamedType({typeId:s.typeId});return u==null?this.csharp.Literal.nop():this.instantiateUnionWithBaseProperties({classReference:i,baseProperties:a,arguments_:[this.convertNamed({named:u,value:o.value})]})}case"singleProperty":{if(this.context.getRecord(o.value)==null)return this.csharp.Literal.nop();try{let c=["Value","Type"].includes(s.discriminantValue.name.pascalCase.safeName)?`${s.discriminantValue.name.pascalCase.safeName}Inner`:s.discriminantValue.name.pascalCase.safeName;return this.context.errors.scope(s.discriminantValue.wireValue),this.instantiateUnionWithBaseProperties({classReference:i,baseProperties:a,arguments_:[this.csharp.instantiateClass({classReference:this.csharp.classReference({name:c,enclosingType:i}),arguments_:[this.convert({typeReference:s.typeReference,value:s.discriminantValue.wireValue})]})]})}finally{this.context.errors.unscope()}}case"noProperties":return this.instantiateUnionWithBaseProperties({classReference:i,baseProperties:a,arguments_:[this.csharp.instantiateClass({classReference:this.csharp.classReference({origin:o.discriminantValue,enclosingType:i}),arguments_:[]})]});default:Be(s)}}getBaseProperties({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r}){return this.context.associateByWireValue({parameters:r.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(i=>{this.context.errors.scope(i.name.wireValue);try{return{name:this.context.getPropertyName(i.name.name),assignment:this.convert(i)}}finally{this.context.errors.unscope()}})}instantiateUnionWithBaseProperties({classReference:t,arguments_:r,baseProperties:n}){let i=this.csharp.instantiateClass({classReference:t,arguments_:r,multiline:!0});return n.length===0?this.csharp.Literal.reference(i):this.csharp.Literal.reference(this.csharp.codeblock(o=>{o.write(i," "),o.pushScope();for(let s of n)o.write(s.name," = ",s.assignment,",");o.popScope(!1)}))}getEnumValue(t,r){if(typeof r!="string")return this.context.errors.add({severity:Ir.Critical,message:`Expected enum value string, got: ${typeof r}`}),this.csharp.Literal.nop();let n=t.values.find(s=>s.wireValue===r);if(n==null)return this.context.errors.add({severity:Ir.Critical,message:`An enum value named "${r}" does not exist in this context`}),this.csharp.Literal.nop();let i=this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),o=i.registerField(this.model.getPropertyNameFor(n),n);return this.csharp.Literal.reference(this.csharp.enumInstantiation({reference:i,value:o}))}convertObject({object_:t,value:r,fallbackToDefault:n}){let i=this.context.associateByWireValue({parameters:t.properties,values:this.context.getRecord(r)??{}});return this.csharp.Literal.class_({reference:this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),fields:i.map(o=>{this.context.errors.scope(o.name.wireValue);try{return{name:this.context.getClassName(o.name.name),value:this.convert(o)}}finally{this.context.errors.unscope()}})})}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,fallbackToDefault:n}){let i=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r});return i==null?this.csharp.Literal.nop():i.typeLiteral}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r}){for(let n of t.types)try{let i=this.convert({typeReference:n,value:r});return{valueTypeReference:n,typeLiteral:i}}catch{continue}this.context.errors.add({severity:Ir.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}convertUnknown({value:t,fallbackToDefault:r}){return this.csharp.Literal.unknown(t)}convertPrimitive({primitive:t,value:r,as:n,fallbackToDefault:i}){switch(t){case"INTEGER":{let o=this.getValueAsNumber({value:r,as:n});return o==null?i?this.Primitive.integer.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.integer(o)}case"LONG":{let o=this.getValueAsNumber({value:r,as:n});return o==null?i?this.Primitive.long.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.long(o)}case"UINT":{let o=this.getValueAsNumber({value:r,as:n});return o==null?i?this.Primitive.uint.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.uint(o)}case"UINT_64":{let o=this.getValueAsNumber({value:r,as:n});return o==null?i?this.Primitive.ulong.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.ulong(o)}case"FLOAT":{let o=this.getValueAsNumber({value:r,as:n});return o==null?i?this.Primitive.float.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.float(o)}case"DOUBLE":{let o=this.getValueAsNumber({value:r,as:n});return o==null?i?this.Primitive.double.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.double(o)}case"BOOLEAN":{let o=this.getValueAsBoolean({value:r,as:n});return o==null?i?this.Primitive.boolean.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.boolean(o)}case"STRING":{let o=this.context.getValueAsString({value:r});return o==null?i?this.Primitive.string.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.string(o)}case"DATE":{let o=this.context.getValueAsString({value:r});return o==null?i?this.Value.dateOnly.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.date(o)}case"DATE_TIME":{let o=this.context.getValueAsString({value:r});return o==null?i?this.Value.dateTime.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.datetime(o)}case"UUID":{let o=this.context.getValueAsString({value:r});return o==null?i?this.Primitive.string.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.string(o)}case"BASE_64":{let o=this.context.getValueAsString({value:r});return o==null?i?this.Primitive.string.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.string(o)}case"BIG_INTEGER":{let o=this.context.getValueAsString({value:r});return o==null?i?this.Primitive.string.getDeterminsticDefault(i):this.csharp.Literal.nop():this.csharp.Literal.string(o)}default:Be(t)}}getValueAsNumber({value:t,as:r}){let n=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:n})}};St();var Xjn=class extends D7{context;constructor({context:t}){super(t.generation),this.context=t}convert(t){switch(t.typeReference.type){case"list":return this.Collection.list(this.convert({typeReference:t.typeReference.value,unboxOptionals:!0}));case"literal":return this.convertLiteral({literal:t.typeReference.value});case"map":return this.Collection.map(this.convert({typeReference:t.typeReference.key}),this.convert({typeReference:t.typeReference.value}));case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.convertUnknown():this.convertNamed({named:r})}case"optional":case"nullable":{let r=this.convert({typeReference:t.typeReference.value});return t.unboxOptionals?r.asNonOptional():r.asOptional()}case"primitive":return this.convertPrimitive({primitive:t.typeReference.value});case"set":return this.Collection.set(this.convert({typeReference:t.typeReference.value,unboxOptionals:!0}));case"unknown":return this.convertUnknown();default:Be(t.typeReference)}}convertToClassReference(t){return this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)})}convertNamed({named:t}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference});case"enum":case"object":return this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)});case"discriminatedUnion":return this.settings.shouldGeneratedDiscriminatedUnions?this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}):this.Primitive.object;case"undiscriminatedUnion":return this.settings.shouldGenerateUndiscriminatedUnions?this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}):this.OneOf.OneOf(t.types.map(r=>this.convert({typeReference:r})));default:Be(t)}}convertLiteral({literal:t}){switch(t.type){case"boolean":return this.Primitive.boolean;case"string":return this.Primitive.string}}convertUnknown(){return this.Primitive.object}convertPrimitive({primitive:t}){switch(t){case"INTEGER":return this.Primitive.integer;case"UINT":return this.Primitive.uint;case"LONG":return this.Primitive.long;case"UINT_64":return this.Primitive.ulong;case"FLOAT":return this.Primitive.float;case"DOUBLE":return this.Primitive.double;case"BOOLEAN":return this.Primitive.boolean;case"STRING":return this.Primitive.string;case"DATE":return this.Value.dateOnly;case"DATE_TIME":return this.Value.dateTime;case"UUID":return this.Primitive.string;case"BASE_64":return this.Primitive.string;case"BIG_INTEGER":return this.Primitive.string;default:Be(t)}}};St();var Zjn=class extends D7{context;constructor({context:t}){super(t.generation),this.context=t}getFilePropertyInfo({body:t,value:r}){let n={fileFields:[],bodyPropertyFields:[]},i=this.context.getRecord(r)??{};for(let o of t.properties)switch(o.type){case"file":$a.Record.missingKey(i,o.wireValue)&&(i[o.wireValue]="[bytes]"),n.fileFields.push({name:this.context.getPropertyName(o.name),value:this.getSingleFileProperty({property:o,record:i})});break;case"fileArray":$a.Record.missingKey(i,o.wireValue)&&(i[o.wireValue]=["[bytes]"]),n.fileFields.push({name:this.context.getPropertyName(o.name),value:this.getArrayFileProperty({property:o,record:i})});break;case"bodyProperty":if($a.Record.missingKey(i,o.name.wireValue))switch(o.typeReference.type){case"optional":break;case"primitive":{switch(o.typeReference.value.toLowerCase()){case"integer":{i[o.name.wireValue]=123;break}case"string":{i[o.name.wireValue]="[string]";break}case"boolean":{i[o.name.wireValue]=!0;break}case"double":{i[o.name.wireValue]=123.456;break}case"float":{i[o.name.wireValue]=123.456;break}case"long":{i[o.name.wireValue]=123456789;break}case"uint":{i[o.name.wireValue]=123;break}case"uint64":{i[o.name.wireValue]=12345;break}case"date":{i[o.name.wireValue]=new Date(2021,1,1);break}case"datetime":{i[o.name.wireValue]=new Date(2021,1,1,12,0,0);break}case"uuid":{i[o.name.wireValue]="123e4567-e89b-12d3-a456-426614174000";break}case"base64":{i[o.name.wireValue]="SGVsbG8gd29ybGQh";break}case"biginteger":{i[o.name.wireValue]="12345678901234567890";break}}break}default:break}n.bodyPropertyFields.push({name:this.context.getPropertyName(o.name.name),value:this.getBodyProperty({property:o,record:i})});break;default:Be(o)}return n}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r});return n==null?this.csharp.Literal.nop():this.context.getFileParameterForString(n)}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});return n==null?this.csharp.Literal.nop():this.csharp.Literal.list({valueType:this.Types.FileParameter,values:n.map(i=>this.context.getFileParameterForString(i))})}getBodyProperty({property:t,record:r}){let n=r[t.name.wireValue];return n==null?this.csharp.Literal.nop():this.context.dynamicLiteralMapper.convert({typeReference:t.typeReference,value:n})}};var eMn=class e extends $v{ir;dynamicTypeMapper;dynamicLiteralMapper;filePropertyMapper;generation;get namespaces(){return this.generation.namespaces}get registry(){return this.generation.registry}get settings(){return this.generation.settings}get constants(){return this.generation.constants}get names(){return this.generation.names}get model(){return this.generation.model}get format(){return this.generation.format}get csharp(){return this.generation.csharp}get Types(){return this.generation.Types}get System(){return this.generation.extern.System}get NUnit(){return this.generation.extern.NUnit}get OneOf(){return this.generation.extern.OneOf}get Google(){return this.generation.extern.Google}get WireMock(){return this.generation.extern.WireMock}get Primitive(){return this.generation.Primitive}get Value(){return this.generation.Value}get Collection(){return this.generation.Collection}constructor({ir:t,config:r,options:n,generation:i}){super({ir:t,config:r,options:n}),this.ir=t,this.generation=i??new bLt(t,r.workspaceName,r.customConfig!=null?r.customConfig:{},r),this.dynamicTypeMapper=new Xjn({context:this}),this.dynamicLiteralMapper=new Yjn({context:this}),this.filePropertyMapper=new Zjn({context:this})}clone(){return new e({ir:this.ir,config:this.config,options:this.options,generation:this.generation})}getFileParameterForString(t){return this.csharp.Literal.reference(this.csharp.instantiateClass({classReference:this.Types.FileParameter,arguments_:[],properties:[{name:"Stream",value:this.getMemoryStreamForString(t)}],multiline:!0}))}getMemoryStreamForString(t){return this.System.IO.MemoryStream.new({arguments_:[this.csharp.invokeMethod({on:this.System.Text.Encoding_UTF8,method:"GetBytes",arguments_:[this.csharp.Literal.string(t)]})]})}getClassName(t){return t.pascalCase.safeName}getParameterName(t){return t.camelCase.safeName}getPropertyName(t){return t.pascalCase.safeName}getMethodName(t){return`${t.pascalCase.safeName}Async`}getNamespace(t,r){let n=this.getNamespaceSegments(t);return n=r!=null?[...n,r]:n,[this.namespaces.root,...n].join(".")}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return this.getEnvironmentClassReferenceForEnumName(r)}getEnvironmentClassReferenceForEnumName(t){return this.csharp.classReference({name:`${this.generation.Types.Environments.name}.${this.getClassName(t)}`,namespace:this.namespaces.root})}getNamespaceSegments(t){return(this.settings.explicitNamespaces?t.allParts:t.packagePath).map(n=>n.pascalCase.safeName)}precalculate(t){this.generation.initialize(),this.System.Collections.Generic.KeyValuePair(),this.System.Collections.Generic.IEnumerable(),this.System.Collections.Generic.IAsyncEnumerable(),this.System.Collections.Generic.HashSet(),this.System.Collections.Generic.List(),this.System.Collections.Generic.Dictionary(),this.System.Threading.Tasks.Task(),Object.entries(this.ir.types).sort((r,n)=>r[0].length-n[0].length).forEach(([r,n])=>{this.dynamicTypeMapper.convertToClassReference(n)});for(let[r,n]of t.entries())if(this.csharp.classReference({origin:this.model.staticExplicit(`Example${r}`),namespace:"Usage"}),n.endpoint){let i=this.resolveEndpointLocation(n.endpoint);for(let o of i)switch(o.request.type){case"inlined":this.csharp.classReference({origin:o.request.declaration.name,namespace:this.getNamespace(o.request.declaration.fernFilepath)});break;case"body":break}}this.generation.Types.ClientOptions,this.generation.Types.RootClientForSnippets,this.csharp.freezeClassReferences()}};St();Bi();var tMn=class extends D7{context;constructor({context:t}){super(t.generation),this.context=t}async generateSnippet({endpoint:t,request:r,options:n}){return this.buildCodeBlock({endpoint:t,snippet:r,options:n}).toString({namespace:"Usage",generation:this.generation,allNamespaceSegments:new Set,allTypeClassReferences:new Map,skipGlobalQualifier:!0})}generateSnippetSync({endpoint:t,request:r,options:n}){return this.buildCodeBlock({endpoint:t,snippet:r,options:n}).toString({namespace:"Usage",generation:this.generation,allNamespaceSegments:new Set,allTypeClassReferences:new Map,skipGlobalQualifier:!0})}async generateSnippetAst({endpoint:t,request:r,options:n}){throw new Error("Unsupported")}buildCodeBlock({endpoint:t,snippet:r,options:n}){if(t.examples&&!t.examples?.find(s=>$a.DynamicIR.EndpointExample(r)&&s.id===r.id))throw new Error("Endpoint does not have an example that matches the snippet");let i=this.csharp.codeblock(s=>{s.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),s.newLine(),s.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))}),o=this.getStyle(n);switch(o){case CC.Concise:return i;case CC.Full:return this.buildFullCodeBlock({body:i,options:n});default:Be(o)}}buildFullCodeBlock({body:t,options:r}){let n=this.getConfig(r),i=this.csharp.class_({name:n.fullStyleClassName??"Example",namespace:"Usage",access:Hft.Access.Public});return i.addNamespaceReference(this.Types.RootClientForSnippets.namespace),i.addMethod({name:"Do",access:Hft.Access.Public,isAsync:!0,parameters:[],body:t}),i}constructClient({endpoint:t,snippet:r}){return this.csharp.codeblock(n=>{n.write("var client = "),n.writeNode(this.getRootClientConstructorInvocation(this.getConstructorArgs({endpoint:t,snippet:r})))})}callMethod({endpoint:t,snippet:r}){let n=t.response?.type==="streaming"||t.response?.type==="streamParameter",i=this.csharp.invokeMethod({on:this.csharp.codeblock("client"),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:r}),async:!0,configureAwait:!0,multiline:!0,isAsyncEnumerable:n});return n?this.csharp.codeblock(o=>{o.write("await foreach (var item in "),o.writeNode(i),o.writeLine(")"),o.pushScope(),o.writeLine("/* consume each item */"),o.popScope()}):i}getConstructorArgs({endpoint:t,snippet:r}){let n=[];t.auth!=null&&(r.auth!=null?n.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Ir.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`}));let i=[],o=this.getConstructorBaseUrlArgs({baseUrl:r.baseURL,environment:r.environment});o.length>0&&i.push(...o),this.context.errors.scope(Lo.Headers);let s=[];if(this.context.ir.headers!=null&&r.headers!=null&&s.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),this.settings.unifiedClientOptions){let a=[...n.map(u=>({name:gc(u.name),assignment:u.assignment})),...s.map(u=>({name:gc(u.name),assignment:u.assignment})),...i.map(u=>({name:u.name,assignment:u.assignment}))];return a.length===0?[]:[{name:"clientOptions",assignment:this.csharp.instantiateClass({classReference:this.Types.ClientOptions,arguments_:a,multiline:!0})}]}return i.length===0?[...n,...s]:[...n,...s,{name:"clientOptions",assignment:this.csharp.instantiateClass({classReference:this.Types.ClientOptions,arguments_:i.map(a=>({name:a.name,assignment:a.assignment})),multiline:!0})}]}getConstructorBaseUrlArgs({baseUrl:t,environment:r}){let n=this.getBaseUrlArg({baseUrl:t,environment:r});return $a.Literal.nop(n)?[]:[{name:this.getBaseUrlOptionName(),assignment:n}]}getBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null)return this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"}),this.csharp.Literal.nop();if(t!=null)return this.context.ir.environments?.environments.type==="multipleBaseUrls"?(this.context.errors.add({severity:Ir.Critical,message:"The C# SDK doesn't support a baseUrl when multiple URL environments are configured"}),this.csharp.Literal.nop()):this.csharp.Literal.string(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);return n==null?(this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`}),this.csharp.Literal.nop()):this.csharp.Literal.reference(n)}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?this.csharp.Literal.reference(this.csharp.instantiateClass({classReference:this.Types.Environments,arguments_:Object.entries(r).map(([n,i])=>({name:gc(qn(n)),assignment:this.context.dynamicLiteralMapper.convert({typeReference:{type:"primitive",value:"STRING"},value:i})})),multiline:!0})):this.csharp.Literal.nop()}return this.csharp.Literal.nop()}getConstructorAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?this.getConstructorBasicAuthArg({auth:t,values:r}):[];case"bearer":return r.type==="bearer"?this.getConstructorBearerAuthArgs({auth:t,values:r}):[];case"header":return r.type==="header"?this.getConstructorHeaderAuthArgs({auth:t,values:r}):[];case"oauth":return r.type==="oauth"?this.getConstructorOAuthArgs({auth:t,values:r}):[];case"inferred":return r.type==="inferred"?this.getConstructorInferredAuthArgs({auth:t,values:r}):[];default:Be(t)}}addError(t){this.context.errors.add({severity:Ir.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:r}){return[{name:this.context.getParameterName(t.username),assignment:this.csharp.Literal.string(r.username)},{name:this.context.getParameterName(t.password),assignment:this.csharp.Literal.string(r.password)}]}getConstructorBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getParameterName(t.token),assignment:this.csharp.Literal.string(r.token)}]}getConstructorHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getParameterName(t.header.name.name),assignment:this.context.dynamicLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value,fallbackToDefault:t.header.name.wireValue})}]}getConstructorOAuthArgs({auth:t,values:r}){return[{name:this.context.getParameterName(t.clientId),assignment:this.csharp.Literal.string(r.clientId)},{name:this.context.getParameterName(t.clientSecret),assignment:this.csharp.Literal.string(r.clientSecret)}]}getConstructorInferredAuthArgs({auth:t,values:r}){let n=[];if(t.parameters!=null)for(let i of t.parameters){let o=i.name.wireValue,s=r.values?.[o];n.push({name:this.context.getParameterName(i.name.name),assignment:this.context.dynamicLiteralMapper.convert({typeReference:i.typeReference,value:s,fallbackToDefault:o})})}else this.context.errors.add({severity:Ir.Critical,message:"Inferred auth parameters are not defined in the IR. Please ensure you're using IR version 62.3.0 or later."});return n}getConstructorHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getConstructorHeaderArg({header:i,value:o});s!=null&&n.push({name:this.context.getParameterName(i.name.name),assignment:s})}return n}getConstructorHeaderArg({header:t,value:r}){let n=this.context.dynamicLiteralMapper.convert({typeReference:t.typeReference,value:r,fallbackToDefault:t.name.wireValue});if(!$a.Literal.nop(n))return n}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[],o=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];o.length>0&&i.push(...this.getPathParameters({namedParameters:o,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let s=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:this.settings.shouldInlinePathParameters})||n.push(...i.map(a=>a.value)),n.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:this.settings.shouldInlinePathParameters})?i:[],filePropertyInfo:s})),n}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Lo.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicLiteralMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.Headers);let u=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicLiteralMapper.convert({...l,fallbackToDefault:l.name.wireValue})}));this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let c=t.body!=null?this.getInlinedRequestBodyConstructorFields({body:t.body,value:r.requestBody,filePropertyInfo:i}):[];return this.context.errors.unscope(),this.csharp.Literal.class_({reference:this.csharp.classReference({origin:t.declaration,namespace:this.context.getNamespace(t.declaration.fernFilepath)}),fields:[...n,...s,...u,...c]})}getInlinedRequestBodyConstructorFields({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyConstructorFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyConstructorField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyConstructorFields({filePropertyInfo:n});default:Be(t)}}getInlinedRequestBodyPropertyConstructorFields({parameters:t,value:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicLiteralMapper.convert({...o,fallbackToDefault:o.name.wireValue})});return n}getFileUploadRequestBodyConstructorFields({filePropertyInfo:t}){return[...t.fileFields,...t.bodyPropertyFields]}getReferencedRequestBodyPropertyConstructorField({body:t,value:r}){return{name:this.context.getPropertyName(t.bodyKey),value:this.getReferencedRequestBodyPropertyLiteral({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicLiteralMapper.convert({typeReference:t.value,value:r,fallbackToDefault:JSON.stringify(t.value)});default:Be(t)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];return i.length>0&&n.push(...this.getPathParameters({namedParameters:i,snippet:r}).map(o=>o.value)),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),t.body!=null&&n.push(this.getBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope(),n}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return t.value.type==="optional"&&r==null?this.csharp.Literal.null():this.context.dynamicLiteralMapper.convert({typeReference:t.value,value:r,fallbackToDefault:JSON.stringify(t.value)});default:Be(t)}}getBytesBodyRequestArg({value:t}){let r=this.context.getValueAsString({value:t});return r==null&&(this.context.errors.add({severity:Ir.Critical,message:"The bytes request body must be provided in string format"}),r="[bytes]"),this.csharp.Literal.reference(this.context.getMemoryStreamForString(r))}getRootClientConstructorInvocation(t){return this.csharp.instantiateClass({classReference:this.Types.RootClientForSnippets,arguments_:t,forceUseConstructor:!0,multiline:!0})}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValueOrDefault({parameters:t,values:r.pathParameters??{}});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicLiteralMapper.convert({...o,fallbackToDefault:o.name.wireValue})});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getClassName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getBaseUrlOptionName(){return this.context.ir.environments?.environments.type==="multipleBaseUrls"?"Environment":"BaseUrl"}getStyle(t){return t.style??this.context.options.style??CC.Full}getConfig(t){return t.config??this.context.options.config??{}}};var ELt=class extends Wv{constructor({ir:t,config:r,options:n={}}){super(new eMn({ir:t,config:r,options:n}))}precalculate(t){this.context.precalculate(t)}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new tMn({context:t})}};qt();var Jft=require("fs/promises"),cYu=Ae(require("path"),1);function pS(e){let t=e.endpoint.method;if(t!=="HEAD")return{...e,baseURL:e.baseUrl,endpoint:{...e.endpoint,method:t},auth:PTm(e.auth)}}function PTm(e){if(e!=null)return e}function uYu(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,DTm(r)]).filter(([t,r])=>r!=null))}function DTm(e){let t=e.location.method;if(t!=="HEAD")return{...e,location:{...e.location,method:t},examples:e.examples!=null?RTm(e.examples):void 0,auth:kTm(e.auth)}}function RTm(e){return e.map(t=>FTm(t)).filter(t=>t!=null)}function FTm(e){let t=e.endpoint.method;if(t!=="HEAD")return{...e,baseURL:e.baseUrl,endpoint:{...e.endpoint,method:t},auth:NTm(e.auth)}}function NTm(e){if(e!=null)return e}function kTm(e){if(e!=null)return e}function fS(e){return{...e,endpoints:uYu(e.endpoints)}}var QTm=`
2494
2494
  <Project Sdk="Microsoft.NET.Sdk">
2495
2495
  <PropertyGroup>
2496
2496
  <TargetFramework>net8.0</TargetFramework>
@@ -2502,7 +2502,7 @@ ${kMt()}`)}return this.generation.registry.registerClassReference(t,r)}freezeCla
2502
2502
  <ItemGroup>
2503
2503
  <ProjectReference Include="..\\..\\**\\*.csproj" Exclude="..\\..\\**\\*.DynamicSnippets.csproj;..\\..\\**\\*.Test.csproj" />
2504
2504
  </ItemGroup>
2505
- </Project>`,rMn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new ELt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests..."),this.dynamicSnippetsGenerator.context.precalculate(r);let n=await this.initializeProject(t);for(let[i,o]of r.entries())try{let s=pS(o);if(s==null)continue;let a=await this.dynamicSnippetsGenerator.generate(s,{config:{fullStyleClassName:`Example${i}`},style:CC.Full}),u=this.getTestFilePath({absolutePathToOutputDir:n,idx:i});await(0,Jft.mkdir)(cYu.default.dirname(u),{recursive:!0}),await(0,Jft.writeFile)(u,a.snippet)}catch(s){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(o.endpoint)}: ${s}`)}this.context.logger.debug("Done generating dynamic snippet tests")}async initializeProject(t){let r=Ge(t,Se.of("src/SeedApi.DynamicSnippets"));return await(0,Jft.mkdir)(r,{recursive:!0}),await(0,Jft.writeFile)(Ge(r,Se.of("SeedApi.DynamicSnippets.csproj")),QTm),r}getTestFilePath({absolutePathToOutputDir:t,idx:r}){return Ge(t,Se.of(`Example${r}.cs`))}};qt();St();sA();var jTm=/[^0-9a-zA-Z_]/g,MTm=["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"],lMe=class extends wC{packageName;rootImportPath;importPath;customConfig;formatter;imports={};constructor({packageName:t,rootImportPath:r,importPath:n,customConfig:i,formatter:o}){super(),this.packageName=t,this.rootImportPath=r,this.importPath=n,this.customConfig=i,this.formatter=o??new B7}addImport(t){let r=this.imports[t];if(r!=null)return r;if(t===this.rootImportPath&&this.customConfig.packageName!=null)return this.imports[t]=this.customConfig.packageName,this.customConfig.packageName;let n=new Set(Object.values(this.imports)),i=t.split("/");for(let s=1;s<=i.length;s++){let a=i.slice(-s),u=this.getValidAlias(a.join(""));if(!n.has(u))return this.imports[t]=u,u}let o=this.getValidAlias(qB(t));for(;n.has(o);)o="_"+o;return this.imports[t]=o,o}isValidAlias(t){return!MTm.includes(t)}getValidAlias(t){let r=t.split("-");if(r[0]==null)return t;let n=r.map(i=>i.replace(jTm,"")).join("");return this.isValidAlias(n)?n:"_"+n}};var vLt=class extends lMe{constructor({packageName:t,rootImportPath:r,importPath:n,customConfig:i,formatter:o}){super({packageName:t,rootImportPath:r,importPath:n,customConfig:i,formatter:o})}async toStringAsync(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.format(t)}catch(r){throw new Error(`Failed to format Go file: ${r}
2505
+ </Project>`,rMn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new ELt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests..."),this.dynamicSnippetsGenerator.context.precalculate(r.map(i=>i.request));let n=await this.initializeProject(t);for(let[i,{endpointId:o,request:s}]of r.entries())try{let a=pS(s);if(a==null)continue;let u=await this.dynamicSnippetsGenerator.generate(a,{config:{fullStyleClassName:`Example${i}`},style:CC.Full,endpointId:o}),c=this.getTestFilePath({absolutePathToOutputDir:n,idx:i});await(0,Jft.mkdir)(cYu.default.dirname(c),{recursive:!0}),await(0,Jft.writeFile)(c,u.snippet)}catch(a){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(s.endpoint)}: ${a}`)}this.context.logger.debug("Done generating dynamic snippet tests")}async initializeProject(t){let r=Ge(t,Se.of("src/SeedApi.DynamicSnippets"));return await(0,Jft.mkdir)(r,{recursive:!0}),await(0,Jft.writeFile)(Ge(r,Se.of("SeedApi.DynamicSnippets.csproj")),QTm),r}getTestFilePath({absolutePathToOutputDir:t,idx:r}){return Ge(t,Se.of(`Example${r}.cs`))}};qt();St();sA();var jTm=/[^0-9a-zA-Z_]/g,MTm=["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"],lMe=class extends wC{packageName;rootImportPath;importPath;customConfig;formatter;imports={};constructor({packageName:t,rootImportPath:r,importPath:n,customConfig:i,formatter:o}){super(),this.packageName=t,this.rootImportPath=r,this.importPath=n,this.customConfig=i,this.formatter=o??new B7}addImport(t){let r=this.imports[t];if(r!=null)return r;if(t===this.rootImportPath&&this.customConfig.packageName!=null)return this.imports[t]=this.customConfig.packageName,this.customConfig.packageName;let n=new Set(Object.values(this.imports)),i=t.split("/");for(let s=1;s<=i.length;s++){let a=i.slice(-s),u=this.getValidAlias(a.join(""));if(!n.has(u))return this.imports[t]=u,u}let o=this.getValidAlias(qB(t));for(;n.has(o);)o="_"+o;return this.imports[t]=o,o}isValidAlias(t){return!MTm.includes(t)}getValidAlias(t){let r=t.split("-");if(r[0]==null)return t;let n=r.map(i=>i.replace(jTm,"")).join("");return this.isValidAlias(n)?n:"_"+n}};var vLt=class extends lMe{constructor({packageName:t,rootImportPath:r,importPath:n,customConfig:i,formatter:o}){super({packageName:t,rootImportPath:r,importPath:n,customConfig:i,formatter:o})}async toStringAsync(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.format(t)}catch(r){throw new Error(`Failed to format Go file: ${r}
2506
2506
  ${t}`)}return t}toString(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.formatSync(t)}catch(r){throw new Error(`Failed to format Go file: ${r}
2507
2507
  ${t}`)}return t}getContent(){let t=`package ${this.packageName}
2508
2508
 
@@ -2517,7 +2517,7 @@ ${s.join(`
2517
2517
  )`}};var Ht={};Z(Ht,{Alias:()=>pMe,AstNode:()=>Vc,CodeBlock:()=>Tne,Enum:()=>fMe,Field:()=>dMe,File:()=>mMe,Func:()=>hMe,FuncInvocation:()=>R7,IoReaderTypeReference:()=>amo,Method:()=>lfe,MethodInvocation:()=>cfe,MultiNode:()=>wLt,Parameter:()=>gMe,Pointer:()=>AMe,Selector:()=>yMe,Struct:()=>bMe,TimeTypeReference:()=>nMn,Type:()=>xLt,TypeDeclaration:()=>EMe,TypeInstantiation:()=>ZR,TypeReference:()=>eF,UuidTypeReference:()=>iMn,Writer:()=>lMe,alias:()=>YTm,codeblock:()=>XTm,enum_:()=>ZTm,field:()=>ePm,file:()=>tPm,func:()=>rPm,identifier:()=>nPm,invokeFunc:()=>iPm,invokeMethod:()=>oPm,method:()=>sPm,parameter:()=>aPm,pointer:()=>uPm,selector:()=>cPm,struct:()=>lPm,switch_:()=>pPm,typeDeclaration:()=>fPm,typeReference:()=>dPm});var Vc=class extends O0{async toStringAsync({packageName:t,rootImportPath:r,importPath:n,customConfig:i,formatter:o}){let s=new vLt({packageName:t,rootImportPath:r,importPath:n,customConfig:i,formatter:o});return this.write(s),s.toStringAsync()}toString({packageName:t,rootImportPath:r,importPath:n,customConfig:i,formatter:o}){let s=new vLt({packageName:t,rootImportPath:r,importPath:n,customConfig:i,formatter:o});return this.write(s),s.toString()}};var CB=class extends Vc{docs;constructor({docs:t}={}){super(),this.docs=t}write(t){this.docs!=null&&this.docs.split(`
2518
2518
  `).forEach(r=>{t.writeLine(`// ${r}`)})}};var pMe=class extends Vc{name;type;docs;constructor({name:t,type:r,docs:n}){super(),this.name=t,this.type=r,this.docs=n}write(t){t.writeNode(new CB({docs:this.docs})),t.write("type "),t.write(this.name),t.write(" = "),t.writeNode(this.type)}};var Tne=class extends Vc{arg;constructor(t){super(),this.arg=t}write(t){return new Ly(this.arg).write(t)}};var ufe=class extends Vc{name;constructor(t){super(),this.name=t}write(t){t.write(this.name)}};St();function Yft({writer:e,arguments_:t,multiline:r=!0}){let n=t.map(i=>i instanceof ZR&&ZR.isNop(i)?ZR.nil():i);if(n.length===0){e.write("()");return}if(r){LTm({writer:e,arguments_:n});return}UTm({writer:e,arguments_:n})}function LTm({writer:e,arguments_:t}){e.writeLine("("),e.indent();for(let r of t)r.write(e),e.writeLine(",");e.dedent(),e.write(")")}function UTm({writer:e,arguments_:t}){e.write("("),t.forEach((r,n)=>{n>0&&e.write(", "),r.write(e)}),e.write(")")}var R7=class extends Vc{func;arguments_;multiline;constructor({func:t,arguments_:r,multiline:n=!0}){super(),this.func=t,this.arguments_=r,this.multiline=n}write(t){t.writeNode(this.func),Yft({writer:t,arguments_:this.arguments_,multiline:this.multiline})}};function lYu({writer:e,generics:t}){t.length!==0&&(e.write("["),t.forEach((r,n)=>{n>0&&e.write(", "),r!=null&&e.writeNode(r)}),e.write("]"))}var eF=class extends Vc{name;importPath;generics;constructor({name:t,importPath:r,generics:n}){super(),this.name=t,this.importPath=r,this.generics=n}write(t){if(this.importPath==null||t.importPath===this.importPath){t.write(this.name);return}let r=t.addImport(this.importPath);t.write(`${r}.${this.name}`),this.generics!=null&&lYu({writer:t,generics:this.generics})}};var cfe=class extends Vc{on;method;arguments_;multiline;constructor({method:t,arguments_:r,on:n,multiline:i}){super(),this.on=n,this.method=t,this.arguments_=r,this.multiline=i}write(t){this.on.write(t),t.write("."),t.write(this.method),Yft({writer:t,arguments_:this.arguments_,multiline:this.multiline})}};var zTm=new Set(["bool","bytes","date","dateTime","float64","int","int64","string","uuid"]),pYu=new Set(["any","map","slice"]),ZR=class e extends Vc{internalType;constructor(t){super(),this.internalType=t}write(t){switch(this.internalType.type){case"any":this.writeAny({writer:t,value:this.internalType.value});break;case"bool":t.write(this.internalType.value.toString());break;case"bytes":t.write(`[]byte("${this.internalType.value}")`);break;case"date":case"dateTime":t.writeNode(GTm({writer:t,type:this.internalType}));break;case"enum":t.writeNode(this.internalType.typeReference);break;case"float64":t.write(this.internalType.value.toString());break;case"int":t.write(this.internalType.value.toString());break;case"int64":t.write(`int64(${this.internalType.value.toString()})`);break;case"map":this.writeMap({writer:t,map:this.internalType});break;case"nil":t.write("nil");break;case"nop":break;case"optional":this.writeOptional({writer:t,type:this.internalType.value});break;case"reference":t.writeNode(this.internalType.value);break;case"slice":this.writeSlice({writer:t,slice:this.internalType});break;case"string":t.write(this.internalType.value.includes("`")?`"${ILt(this.internalType.value)}"`:this.internalType.value.includes('"')||this.internalType.value.includes(`
2519
2519
  `)?`\`${this.internalType.value}\``:`"${ILt(this.internalType.value)}"`);break;case"struct":this.writeStruct({writer:t,struct:this.internalType});break;case"uuid":t.writeNode(WTm({value:this.internalType.value}));break;default:Be(this.internalType)}}static any(t){return new this({type:"any",value:t})}static bool(t){return new this({type:"bool",value:t})}static bytes(t){return new this({type:"bytes",value:t})}static date(t){return new this({type:"date",value:t})}static dateTime(t){return new this({type:"dateTime",value:t})}static enum(t){return new this({type:"enum",typeReference:t})}static float64(t){return new this({type:"float64",value:t})}static int(t){return new this({type:"int",value:t})}static int64(t){return new this({type:"int64",value:t})}static map({keyType:t,valueType:r,entries:n}){return new this({type:"map",keyType:t,valueType:r,entries:n})}static nil(){return new this({type:"nil"})}static nop(){return new this({type:"nop"})}static optional(t){return this.isAlreadyOptional(t)?t:new this({type:"optional",value:t})}static reference(t){return new this({type:"reference",value:t})}static slice({valueType:t,values:r}){return new this({type:"slice",valueType:t,values:r})}static string(t){return new this({type:"string",value:t})}static struct({typeReference:t,fields:r}){return new this({type:"struct",typeReference:t,fields:r})}static structPointer({typeReference:t,fields:r,generics:n}){return new this({type:"optional",value:new this({type:"struct",typeReference:t,fields:r,generics:n})})}static uuid(t){return new this({type:"uuid",value:t})}static isNop(t){return t.internalType.type==="optional"?this.isNop(t.internalType.value):t.internalType.type==="nop"}writeAny({writer:t,value:r}){switch(typeof r){case"boolean":t.write(r.toString());return;case"string":t.write(r.includes("`")?`"${ILt(r)}"`:r.includes('"')||r.includes(`
2520
- `)?`\`${r}\``:`"${ILt(r)}"`);return;case"number":t.write(r.toString());return;case"object":if(r==null){t.write("nil");return}if(Array.isArray(r)){this.writeAnyArray({writer:t,value:r});return}this.writeAnyObject({writer:t,value:r});return;default:throw new Error(`Internal error; unsupported unknown type: ${typeof r}`)}}writeAnyArray({writer:t,value:r}){if(t.write("[]any"),r.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let n of r)t.writeNode(e.any(n)),t.writeLine(",");t.dedent(),t.write("}")}writeAnyObject({writer:t,value:r}){t.write("map[string]any");let n=Object.entries(r).sort(([i],[o])=>i<o?-1:i>o?1:0);if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let[i,o]of n)t.write(`"${ILt(i)}": `),t.writeNode(e.any(o)),t.writeLine(",");t.dedent(),t.write("}")}writeMap({writer:t,map:r}){t.write("map["),t.writeNode(r.keyType),t.write("]"),t.writeNode(r.valueType);let n=$Tm({entries:r.entries});if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let i of n)i.key.write(t),t.write(": "),i.value.write(t),t.writeLine(",");t.dedent(),t.write("}")}writeOptional({writer:t,type:r}){if(zTm.has(r.internalType.type)){t.writeNode(VTm({writer:t,type:r}));return}if(pYu.has(r.internalType.type)){r.write(t);return}if(r.internalType.type==="enum"){t.writeNode(new cfe({on:r.internalType.typeReference,method:"Ptr",arguments_:[]}));return}t.write("&"),r.write(t)}static isAlreadyOptional(t){return t.internalType.type==="optional"||pYu.has(t.internalType.type)}writeSlice({writer:t,slice:r}){t.write("[]"),t.writeNode(r.valueType);let n=KTm({values:r.values});if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let i of n)i.write(t),t.writeLine(",");t.dedent(),t.write("}")}writeStruct({writer:t,struct:r}){t.writeNode(r.typeReference),r.generics!=null&&(t.write("["),r.generics.forEach((i,o)=>{o>0&&t.write(", "),t.writeNode(i)}),t.write("]"));let n=HTm({fields:r.fields});if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let i of n)t.write(`${i.name}: `),i.value.write(t),t.writeLine(",");t.dedent(),t.write("}")}};function VTm({writer:e,type:t}){return new R7({func:new eF({name:qTm({type:t}),importPath:e.rootImportPath}),arguments_:[t]})}function qTm({type:e}){switch(e.internalType.type){case"bool":return"Bool";case"bytes":return"Bytes";case"date":case"dateTime":return"Time";case"float64":return"Float64";case"int":return"Int";case"int64":return"Int64";case"string":return"String";case"uuid":return"UUID";default:return""}}function GTm({writer:e,type:t}){let r=t.type==="date"?"MustParseDate":"MustParseDateTime";return new R7({func:new eF({name:r,importPath:e.rootImportPath}),arguments_:[new Tne(`"${t.value}"`)]})}function WTm({value:e}){return new R7({func:new eF({name:"MustParse",importPath:"github.com/google/uuid"}),arguments_:[new Tne(`"${e}"`)]})}function ILt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function $Tm({entries:e}){return e.filter(t=>!ZR.isNop(t.key)&&!ZR.isNop(t.value))}function HTm({fields:e}){return e.filter(t=>!ZR.isNop(t.value))}function KTm({values:e}){return e.filter(t=>!ZR.isNop(t))}var fMe=class e extends Vc{name;docs;members=[];methods=[];constructor_;constructor({name:t,docs:r}){super(),this.name=t,this.docs=r}addConstructor(t){this.constructor_=t}addMember(t){this.members.push(t)}addMethod(t){this.methods.push(t)}write(t){this.writeType({writer:t}),this.writeMembers({writer:t}),this.writeConstructor({writer:t}),this.writeMethods({writer:t})}writeType({writer:t}){t.writeNode(new CB({docs:this.docs})),t.writeLine(`type ${this.name} string`)}writeMembers({writer:t}){if(this.members.length!==0){t.newLine(),t.writeLine("const ("),t.indent();for(let r of this.members)t.writeNode(new CB({docs:r.docs})),t.writeNode(e.getMemberIdentifier({name:this.name,member:r})),t.write(" = "),t.writeNode(ZR.string(r.value)),t.newLine();t.dedent(),t.write(")")}}writeConstructor({writer:t}){this.constructor_!=null&&(t.newLine(),t.writeNode(this.constructor_))}writeMethods({writer:t}){t.newLine();for(let r of this.methods)t.newLine(),t.writeNode(r),t.newLine()}static getMemberIdentifier({name:t,member:r}){return new ufe(`${t}${r.name}`)}};var dMe=class extends Vc{name;type;docs;tags=[];constructor({name:t,type:r,docs:n,tags:i}){super(),this.name=t,this.type=r,this.docs=n,this.tags=i??[]}addTags(...t){this.tags.push(...t)}write(t){t.writeNode(new CB({docs:this.docs})),t.write(`${this.name} `),this.type.write(t),this.writeTags({writer:t})}writeTags({writer:t}){this.tags.length!==0&&(t.write(" `"),this.tags.forEach((r,n)=>{n>0&&t.write(" "),t.write(`${r.name}:"${r.value}"`)}),t.write("`"))}};var mMe=class extends Vc{nodes;constructor({nodes:t}={nodes:[]}){super(),this.nodes=t??[]}add(...t){this.nodes.push(...t)}write(t){for(let r of this.nodes)r.write(t)}};var lfe=class extends Vc{parameters;return_;name;body;docs;typeReference;multiline;receiver;pointerReceiver;constructor({name:t,parameters:r,return_:n,body:i,docs:o,typeReference:s,multiline:a,receiver:u,pointerReceiver:c}){super(),this.name=t,this.parameters=r,this.return_=n,this.body=i,this.docs=o,this.typeReference=s,this.multiline=a,this.receiver=u,this.pointerReceiver=c}write(t){t.writeNode(new CB({docs:this.docs})),t.write("func"),this.typeReference!=null&&this.writeReceiver({writer:t,typeReference:this.typeReference,receiver:this.receiver}),this.name!=null&&t.write(` ${this.name}`),Yft({writer:t,arguments_:this.parameters,multiline:this.multiline}),this.return_!=null&&(t.write(" "),this.return_.length>1&&t.write("("),this.return_.forEach((r,n)=>{n>0&&t.write(", "),t.writeNode(r)}),this.return_.length>1&&t.write(")")),t.writeLine("{"),t.indent(),this.body?.write(t),t.dedent(),t.writeNewLineIfLastLineNot(),t.write("}")}writeReceiver({writer:t,typeReference:r,receiver:n}){t.write(` (${this.getReceiverName({typeReference:r,receiver:n})} `),this.pointerReceiver&&t.write("*"),r.write(t),t.write(")")}getReceiverName({typeReference:t,receiver:r}){return r??t.name.charAt(0).toLowerCase()}};var hMe=class extends Vc{func;constructor({name:t,parameters:r,return_:n,body:i,docs:o,multiline:s}){super(),this.func=new lfe({name:t,parameters:r,return_:n,body:i,docs:o,multiline:s})}get parameters(){return this.func.parameters}get return_(){return this.func.return_}get name(){return this.func.name}get body(){return this.func.body}get docs(){return this.func.docs}write(t){t.writeNode(this.func)}};var wLt=class extends Vc{nodes;constructor({nodes:t}){super(),this.nodes=t}write(t){for(let r of this.nodes)t.newLine(),r.write(t),t.newLine()}};var gMe=class extends Vc{name;type;docs;constructor({name:t,type:r,docs:n}){super(),this.name=t,this.type=r,this.docs=n}write(t){t.writeNode(new CB({docs:this.docs})),t.write(`${this.name} `),this.type.write(t)}};var AMe=class extends Vc{node;constructor({node:t}){super(),this.node=t}write(t){t.write("*"),this.node.write(t)}};var yMe=class extends Vc{on;selector;constructor({on:t,selector:r}){super(),this.on=t,this.selector=r}write(t){t.writeNode(this.on),t.write("."),t.writeNode(this.selector)}};var bMe=class extends Vc{name;embeds=[];fields=[];docs;methods=[];constructor_;constructor({name:t,embeds:r,fields:n,docs:i}){super(),this.name=t,this.docs=i,this.embeds=r??[],this.fields=n??[]}addConstructor(t){this.constructor_=t}addField(...t){this.fields.push(...t)}addMethod(...t){this.methods.push(...t)}write(t){this.writeType({writer:t}),this.constructor_!=null&&(t.newLine(),t.newLine(),this.writeConstructor({writer:t,constructor:this.constructor_})),this.writeMethods({writer:t})}writeType({writer:t}){if(t.writeNode(new CB({docs:this.docs})),this.name!=null?t.write(`type ${this.name} struct {`):t.write("struct{"),this.embeds.length===0&&this.fields.length===0){t.writeLine("}");return}t.newLine(),t.indent();for(let i of this.embeds)t.writeNode(i),t.newLine();let r=this.fields.filter(i=>this.isExported(i));for(let i of r)t.writeNode(i),t.newLine();let n=this.fields.filter(i=>!this.isExported(i));r.length>0&&n.length>0&&t.newLine();for(let i of n)t.writeNode(i),t.newLine();t.dedent(),t.write("}")}writeConstructor({writer:t,constructor:r}){r.name!=null?t.write(`func ${r.name}(`):t.write(`func New${this.name}(`),r.parameters.forEach((n,i)=>{i>0&&t.write(", "),t.writeNode(n)}),t.write(`) *${this.name} {`),t.newLine(),t.indent(),t.writeNode(r.body),t.writeNewLineIfLastLineNot(),t.dedent(),t.writeLine("}")}writeMethods({writer:t}){if(this.methods.length!==0){t.writeNewLineIfLastLineNot();for(let r of this.methods)t.newLine(),t.writeNode(r),t.newLine()}}isExported(t){let r=t.name.charAt(0);return r===r.toUpperCase()}};var CLt=class extends Vc{on;cases;default;constructor({on:t,cases:r,default:n}){super(),this.on=t,this.cases=r,this.default=n}write(t){let r=this.cases;this.default!=null&&r.push({on:new ufe("default"),body:this.default}),t.write("switch "),t.writeNode(this.on),t.writeLine("{"),t.indent();for(let n of r)t.write("case "),t.writeNode(n.on),t.writeLine(":"),t.indent(),t.writeNode(n.body),t.dedent(),t.writeNewLineIfLastLineNot();t.dedent(),t.write("}")}};St();var JTm=new Set(["any","bytes","map","slice"]),xLt=class e extends Vc{internalType;constructor(t){super(),this.internalType=t}write(t,{comment:r}={}){switch(this.internalType.type){case"any":t.write("any");break;case"bool":t.write("bool");break;case"bytes":t.write("[]byte");break;case"date":case"dateTime":t.writeNode(nMn);break;case"error":t.write("error");break;case"float64":t.write("float64");break;case"int":t.write("int");break;case"int64":t.write("int64");break;case"map":{t.write("map["),this.internalType.keyType.write(t),t.write("]"),this.internalType.valueType.write(t);break}case"optional":{t.write("*"),this.internalType.value.write(t);break}case"reference":t.writeNode(this.internalType.value);break;case"slice":t.write("[]"),this.internalType.value.write(t);break;case"string":t.write("string");break;case"uuid":t.writeNode(iMn);break;case"variadic":t.write("..."),this.internalType.value.write(t);break;default:Be(this.internalType)}}isOptional(){return this.internalType.type==="optional"}isIterable(){return this.internalType.type==="slice"||this.internalType.type==="variadic"}iterableElement(){if(this.internalType.type==="slice"||this.internalType.type==="variadic")return this.internalType.value}underlying(){return this.internalType.type==="optional"?this.internalType.value:this}static any(){return new this({type:"any"})}static bool(){return new this({type:"bool"})}static bytes(){return new this({type:"bytes"})}static date(){return new this({type:"date"})}static dateTime(){return new this({type:"dateTime"})}static dereference(t){return t.internalType.type==="optional"?t.internalType.value:t}static error(){return new this({type:"error"})}static float64(){return new this({type:"float64"})}static int(){return new this({type:"int"})}static int64(){return new this({type:"int64"})}static map(t,r){return new this({type:"map",keyType:t,valueType:r})}static optional(t){return this.isAlreadyOptional(t)?t:new this({type:"optional",value:t})}static pointer(t){return e.optional(t)}static reference(t){return new this({type:"reference",value:t})}static slice(t){return new this({type:"slice",value:t})}static string(){return new this({type:"string"})}static uuid(){return new this({type:"uuid"})}static variadic(t){return this.isAlreadyVariadic(t)?t:new this({type:"variadic",value:t})}static isAlreadyOptional(t){return t.internalType.type==="optional"||JTm.has(t.internalType.type)}static isAlreadyVariadic(t){return t.internalType.type==="variadic"}},nMn=new eF({importPath:"time",name:"Time"}),iMn=new eF({importPath:"github.com/google/uuid",name:"UUID"}),amo=new eF({importPath:"io",name:"Reader"});var EMe=class extends Vc{name;type;docs;constructor({name:t,type:r,docs:n}){super(),this.name=t,this.type=r,this.docs=n}write(t){t.writeNode(new CB({docs:this.docs})),t.write("type "),t.write(this.name),t.write(" "),t.writeNode(this.type)}};function YTm(e){return new pMe(e)}function XTm(e){return new Tne(e)}function ZTm(e){return new fMe(e)}function ePm(e){return new dMe(e)}function tPm(e={}){return new mMe(e)}function rPm(e){return new hMe(e)}function nPm(e){return new ufe(e)}function iPm(e){return new R7(e)}function oPm(e){return new cfe(e)}function sPm(e){return new lfe(e)}function aPm(e){return new gMe(e)}function uPm(e){return new AMe(e)}function cPm(e){return new yMe(e)}function lPm(e={}){return new bMe(e)}function pPm(e){return new CLt(e)}function fPm(e){return new EMe(e)}function dPm(e){return new eF(e)}var mPm=new Set(["string"]);function umo(e){if(e==="")return"Underscore";let t=e;for(;t.startsWith("_");)t=t.slice(1);if(t==="")return"Underscore";if(t.length>0&&/^\d/.test(t))return"Field"+t;let r=t,n=t[0];return t.length>0&&n!=null&&n!==n.toUpperCase()&&(r=n.toUpperCase()+t.slice(1)),mPm.has(r.toLowerCase())?"Field"+r:r}sA();var fYu=Ae(require("path"),1),hPm="sdk";function cmo({config:e,customConfig:t}){let r=APm({config:e}),n=gPm({config:e,customConfig:t});return r!=null?bPm({importPath:n,majorVersion:r}):n}function gPm({config:e,customConfig:t,isModulePath:r=!1}){let n=t?.importPath??t?.module?.path??(e.output.mode.type==="github"?EPm(e.output.mode.repoUrl,"https://"):hPm);return r?n:fYu.default.join(n,t?.packagePath??"")}function APm({config:e}){let t=yPm({config:e});if(!(t==null||t==="v0"||t==="v1"))return`${t}`}function yPm({config:e}){let t=vPm(e);if(t==null)return;let r=t.split(".");if(r[0]==null)return;let n=r[0];return n.startsWith("v")?n:`v${n}`}function bPm({importPath:e,majorVersion:t}){return qB(e)===t?e:`${e}/${t}`}function EPm(e,t){return e.startsWith(t)?e.slice(t.length):e}function vPm(e){let t=e?.output?.mode;if(t!=null)return t.type==="github"||t.type==="publish"?t.version:void 0}St();var oMn=class{context;constructor({context:t}){this.context=t}convert(t){if(t.value===null&&!this.context.isNullable(t.typeReference)&&this.context.errors.add({severity:Ir.Critical,message:"Expected non-null value, but got null"}),t.value==null)return Ht.TypeInstantiation.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value});case"literal":return Ht.TypeInstantiation.nop();case"map":return this.convertMap({map:t.typeReference,value:t.value});case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?Ht.TypeInstantiation.nop():this.convertNamed({named:r,value:t.value,as:t.as})}case"nullable":{let r=t.typeReference.value;if(r.type==="named"){let n=this.context.resolveNamedType({typeId:r.value});if(n?.type==="alias"&&["list","set","map"].includes(n.typeReference.type)){let i=this.convert({typeReference:n.typeReference,value:t.value,as:t.as}),o=this.context.getTypeName(n.declaration.name),s=this.context.getImportPath(n.declaration.fernFilepath);return this.reconstructAliasCollectionLiteral({collectionLiteral:i,aliasName:o,aliasImportPath:s})}if(n?.type==="alias"&&n.typeReference.type==="literal")return this.convertLiteralToOptionalPrimitive(n.typeReference.value)}return Ht.TypeInstantiation.optional(this.convert({typeReference:r,value:t.value,as:t.as}))}case"optional":{let r=t.typeReference.value;if(r.type==="named"){let n=this.context.resolveNamedType({typeId:r.value});if(n?.type==="alias"&&["list","set","map"].includes(n.typeReference.type)){let i=this.convert({typeReference:n.typeReference,value:t.value,as:t.as}),o=this.context.getTypeName(n.declaration.name),s=this.context.getImportPath(n.declaration.fernFilepath);return this.reconstructAliasCollectionLiteral({collectionLiteral:i,aliasName:o,aliasImportPath:s})}if(n?.type==="alias"&&n.typeReference.type==="literal")return this.convertLiteralToOptionalPrimitive(n.typeReference.value)}return Ht.TypeInstantiation.optional(this.convert({typeReference:r,value:t.value,as:t.as}))}case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as});case"set":return this.convertList({list:t.typeReference.value,value:t.value});case"unknown":return this.convertUnknown({value:t.value});default:Be(t.typeReference)}}convertToPointerIfPossible(t){let r=this.convert(t);return t.typeReference.type==="named"&&this.context.resolveNamedType({typeId:t.typeReference.value})?.type==="enum"?Ht.TypeInstantiation.reference(Ht.invokeMethod({on:r,method:"Ptr",arguments_:[]})):r}convertList({list:t,value:r}){return Array.isArray(r)?Ht.TypeInstantiation.slice({valueType:this.context.dynamicTypeMapper.convert({typeReference:t}),values:r.map((n,i)=>{this.context.errors.scope({index:i});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),Ht.TypeInstantiation.nop())}convertMap({map:t,value:r}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),Ht.TypeInstantiation.nop()):Ht.TypeInstantiation.map({keyType:this.context.dynamicTypeMapper.convert({typeReference:t.key}),valueType:this.context.dynamicTypeMapper.convert({typeReference:t.value}),entries:Object.entries(r).sort(([n],[i])=>n<i?-1:n>i?1:0).map(([n,i])=>{this.context.errors.scope(n);try{return{key:this.convert({typeReference:t.key,value:n,as:"key"}),value:this.convert({typeReference:t.value,value:i})}}finally{this.context.errors.unscope()}})})}convertNamed({named:t,value:r,as:n}){switch(t.type){case"alias":return this.convertAlias({aliasType:t,value:r,as:n});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:r});case"enum":return this.convertEnum({enum_:t,value:r});case"object":return this.convertObject({object_:t,value:r});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r});default:Be(t)}}convertAlias({aliasType:t,value:r,as:n}){return t.typeReference.type==="literal"?Ht.TypeInstantiation.reference(Ht.invokeFunc({func:Ht.typeReference({name:this.context.getTypeName(t.declaration.name),importPath:this.context.getImportPath(t.declaration.fernFilepath)}),arguments_:[this.convertLiteralValue(t.typeReference.value)]})):this.convert({typeReference:t.typeReference,value:r,as:n})}reconstructAliasCollectionLiteral({collectionLiteral:t,aliasName:r,aliasImportPath:n}){let i=t.internalType;return i.type==="slice"?Ht.TypeInstantiation.reference(Ht.codeblock(o=>{o.write("&"),o.writeNode(Ht.typeReference({name:r,importPath:n}));let s=i.values;if(s.length===0){o.write("{}");return}o.writeLine("{"),o.indent();for(let a of s)o.writeNode(a),o.writeLine(",");o.dedent(),o.write("}")})):i.type==="map"?Ht.TypeInstantiation.reference(Ht.codeblock(o=>{o.write("&"),o.writeNode(Ht.typeReference({name:r,importPath:n}));let s=i.entries;if(s.length===0){o.write("{}");return}o.writeLine("{"),o.indent();for(let a of s)o.writeNode(a.key),o.write(": "),o.writeNode(a.value),o.writeLine(",");o.dedent(),o.write("}")})):Ht.TypeInstantiation.reference(Ht.codeblock(o=>{o.write("&"),o.writeNode(t)}))}convertLiteralValue(t){switch(t.type){case"boolean":return Ht.TypeInstantiation.bool(t.value);case"string":return Ht.TypeInstantiation.string(t.value);default:Be(t)}}convertLiteralToOptionalPrimitive(t){switch(t.type){case"boolean":return Ht.TypeInstantiation.optional(Ht.TypeInstantiation.bool(t.value));case"string":return Ht.TypeInstantiation.optional(Ht.TypeInstantiation.string(t.value));default:Be(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r}){let n=this.context.getGoTypeReferenceFromDeclaration({declaration:t.declaration}),i=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(i==null)return Ht.TypeInstantiation.nop();let o=i.singleDiscriminatedUnionType,s=this.getBaseFields({discriminatedUnionTypeInstance:i,singleDiscriminatedUnionType:o});switch(o.type){case"samePropertiesAsObject":{let a=this.context.resolveNamedType({typeId:o.typeId});return a==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.structPointer({typeReference:n,fields:[{name:this.context.getFieldName(o.discriminantValue.name),value:this.convertNamed({named:a,value:i.value})},...s]})}case"singleProperty":{let a=this.context.getRecord(i.value);if(a==null)return Ht.TypeInstantiation.nop();try{return this.context.errors.scope(o.discriminantValue.wireValue),Ht.TypeInstantiation.structPointer({typeReference:n,fields:[{name:this.context.getFieldName(o.discriminantValue.name),value:this.convert({typeReference:o.typeReference,value:a[o.discriminantValue.wireValue]})},...s]})}finally{this.context.errors.unscope()}}case"noProperties":return Ht.TypeInstantiation.structPointer({typeReference:n,fields:[{name:this.context.getFieldName(i.discriminantValue.name),value:Ht.TypeInstantiation.string(o.discriminantValue.wireValue)},...s]});default:Be(o)}}getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r}){return this.context.associateByWireValue({parameters:r.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(i=>{this.context.errors.scope(i.name.wireValue);try{return{name:this.context.getFieldName(i.name.name),value:this.convert(i)}}finally{this.context.errors.unscope()}})}convertObject({object_:t,value:r}){let n=this.context.associateByWireValue({parameters:t.properties,values:this.context.getRecord(r)??{}});return Ht.TypeInstantiation.structPointer({typeReference:Ht.typeReference({name:this.context.getTypeName(t.declaration.name),importPath:this.context.getImportPath(t.declaration.fernFilepath)}),fields:n.map(i=>{this.context.errors.scope(i.name.wireValue);try{return{name:this.context.getFieldName(i.name.name),value:this.convert(i)}}finally{this.context.errors.unscope()}})})}convertEnum({enum_:t,value:r}){let n=this.getEnumValueName({enum_:t,value:r});return n==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.enum(Ht.typeReference({name:n,importPath:this.context.getImportPath(t.declaration.fernFilepath)}))}getEnumValueName({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Ir.Critical,message:`Expected enum value string, got: ${typeof r}`});return}let n=t.values.find(i=>i.wireValue===r);if(n==null){this.context.errors.add({severity:Ir.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return`${this.context.getTypeName(t.declaration.name)}${this.context.getTypeName(n.name)}`}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r}){let n=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r});if(n==null)return Ht.TypeInstantiation.nop();let i=this.getUndiscriminatedUnionFieldName({typeReference:n.valueTypeReference});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.structPointer({typeReference:this.context.getGoTypeReferenceFromDeclaration({declaration:t.declaration}),fields:[{name:i,value:n.typeInstantiation}]})}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r}){for(let n of t.types)try{let i=this.convert({typeReference:n,value:r});if(Ht.TypeInstantiation.isNop(i))continue;return{valueTypeReference:n,typeInstantiation:i}}catch{continue}this.context.errors.add({severity:Ir.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}getUndiscriminatedUnionFieldName({typeReference:t}){switch(t.type){case"list":return this.getUndiscriminatedUnionFieldNameForList({list:t});case"literal":return this.getUndiscriminatedUnionFieldNameForLiteral({literal:t.value});case"map":return this.getUndiscriminatedUnionFieldNameForMap({map:t});case"named":{let r=this.context.resolveNamedType({typeId:t.value});return r==null?void 0:this.context.getTypeName(r.declaration.name)}case"optional":return this.getUndiscriminatedUnionFieldNameForOptional({typeReference:t});case"nullable":return this.getUndiscriminatedUnionFieldNameForOptional({typeReference:t});case"primitive":return this.getUndiscriminatedUnionFieldNameForPrimitive({primitive:t.value});case"set":return this.getUndiscriminatedUnionFieldNameForSet({set:t});case"unknown":return"Unknown";default:Be(t)}}getUndiscriminatedUnionFieldNameForList({list:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t.value});if(r!=null)return`${r}List`}getUndiscriminatedUnionFieldNameForMap({map:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t.key});if(r==null)return;let n=this.getUndiscriminatedUnionFieldName({typeReference:t.value});if(n!=null)return`${r}${n}Map`}getUndiscriminatedUnionFieldNameForOptional({typeReference:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t.value});if(r!=null)return`${r}Optional`}getUndiscriminatedUnionFieldNameForSet({set:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t.value});if(r!=null)return`${r}Set`}getUndiscriminatedUnionFieldNameForLiteral({literal:t}){switch(t.type){case"boolean":return t.value?"TrueLiteral":"FalseLiteral";case"string":return`${t.value}StringLiteral`;default:Be(t)}}getUndiscriminatedUnionFieldNameForPrimitive({primitive:t}){switch(t){case"INTEGER":case"UINT":return"Integer";case"LONG":case"UINT_64":return"Long";case"FLOAT":case"DOUBLE":return"Double";case"BOOLEAN":return"Boolean";case"BIG_INTEGER":case"STRING":return"String";case"UUID":return"Uuid";case"DATE":return"Date";case"DATE_TIME":return"DateTime";case"BASE_64":return"Base64";default:Be(t)}}convertUnknown({value:t}){return Ht.TypeInstantiation.any(t)}convertPrimitive({primitive:t,value:r,as:n}){switch(t){case"INTEGER":case"UINT":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.int(i)}case"LONG":case"UINT_64":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.int64(i)}case"FLOAT":case"DOUBLE":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.float64(i)}case"BOOLEAN":{let i=this.getValueAsBoolean({value:r,as:n});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.bool(i)}case"STRING":{let i=this.context.getValueAsString({value:r});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.string(i)}case"DATE":{let i=this.context.getValueAsString({value:r});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.date(i)}case"DATE_TIME":{let i=this.context.getValueAsString({value:r});if(i==null)return Ht.TypeInstantiation.nop();let o=this.normalizeDateTimeString(i);return Ht.TypeInstantiation.dateTime(o)}case"UUID":{let i=this.context.getValueAsString({value:r});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.uuid(i)}case"BASE_64":{let i=this.context.getValueAsString({value:r});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.bytes(i)}case"BIG_INTEGER":{let i=this.context.getValueAsString({value:r});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.string(i)}default:Be(t)}}getValueAsNumber({value:t,as:r}){let n=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:n})}normalizeDateTimeString(t){return/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t}T00:00:00Z`:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(t)?`${t}Z`:t}};St();var sMn=class{context;constructor({context:t}){this.context=t}convert(t){switch(t.typeReference.type){case"list":return Ht.Type.slice(this.convert({typeReference:t.typeReference.value}));case"literal":return this.convertLiteral({literal:t.typeReference.value});case"map":return Ht.Type.map(this.convert({typeReference:t.typeReference.key}),this.convert({typeReference:t.typeReference.value}));case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.convertUnknown():this.convertNamed({named:r})}case"optional":return Ht.Type.optional(this.convert({typeReference:t.typeReference.value}));case"nullable":return Ht.Type.optional(this.convert({typeReference:t.typeReference.value}));case"primitive":return this.convertPrimitive({primitive:t.typeReference.value});case"set":return Ht.Type.slice(this.convert({typeReference:t.typeReference}));case"unknown":return this.convertUnknown();default:Be(t.typeReference)}}convertLiteral({literal:t}){switch(t.type){case"boolean":return Ht.Type.bool();case"string":return Ht.Type.string()}}convertNamed({named:t}){let r=Ht.Type.reference(Ht.typeReference({name:this.context.getTypeName(t.declaration.name),importPath:this.context.getImportPath(t.declaration.fernFilepath)}));switch(t.type){case"alias":case"enum":return r;case"discriminatedUnion":case"object":case"undiscriminatedUnion":return Ht.Type.pointer(r);default:Be(t)}}convertUnknown(){return Ht.Type.any()}convertPrimitive({primitive:t}){switch(t){case"INTEGER":return Ht.Type.int();case"UINT":return Ht.Type.int();case"LONG":return Ht.Type.int64();case"UINT_64":return Ht.Type.int64();case"FLOAT":return Ht.Type.float64();case"DOUBLE":return Ht.Type.float64();case"BOOLEAN":return Ht.Type.bool();case"STRING":return Ht.Type.string();case"DATE":return Ht.Type.date();case"DATE_TIME":return Ht.Type.dateTime();case"UUID":return Ht.Type.uuid();case"BASE_64":return Ht.Type.bytes();case"BIG_INTEGER":return Ht.Type.string();default:Be(t)}}};St();var aMn=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({body:t,value:r}){let n={fileFields:[],bodyPropertyFields:[]},i=this.context.getRecord(r)??{};for(let o of t.properties)switch(o.type){case"file":n.fileFields.push({name:this.context.getFieldName(o.name),value:this.getSingleFileProperty({property:o,record:i})});break;case"fileArray":n.fileFields.push({name:this.context.getFieldName(o.name),value:this.getArrayFileProperty({property:o,record:i})});break;case"bodyProperty":n.bodyPropertyFields.push({name:this.context.getFieldName(o.name.name),value:this.getBodyProperty({property:o,record:i})});break;default:Be(o)}return n}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r})||"";return Ht.TypeInstantiation.reference(this.context.getNewStringsReaderFunctionInvocation(n))}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});return n==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.slice({valueType:Ht.Type.reference(this.context.getIoReaderTypeReference()),values:n.map(i=>Ht.TypeInstantiation.reference(this.context.getNewStringsReaderFunctionInvocation(i)))})}getBodyProperty({property:t,record:r}){let n=r[t.name.wireValue];return n==null?Ht.TypeInstantiation.nop():this.context.dynamicTypeInstantiationMapper.convert({typeReference:t.typeReference,value:n})}};var uMn=class e extends $v{ir;customConfig;dynamicTypeMapper;dynamicTypeInstantiationMapper;filePropertyMapper;rootImportPath;constructor({ir:t,config:r}){super({ir:t,config:r}),this.ir=t,this.customConfig=r.customConfig!=null?r.customConfig:void 0,this.dynamicTypeMapper=new sMn({context:this}),this.dynamicTypeInstantiationMapper=new oMn({context:this}),this.filePropertyMapper=new aMn({context:this}),this.rootImportPath=cmo({config:r,customConfig:this.customConfig})}clone(){return new e({ir:this.ir,config:this.config})}isOptional(t){switch(t.type){case"optional":case"map":return!0;case"nullable":case"list":case"set":return this.isOptional(t.value);case"named":case"literal":case"primitive":case"unknown":return!1;default:Be(t)}}getMethodName(t){return t.pascalCase.unsafeName}getTestMethodName(t){return t.declaration.fernFilepath.allParts.map(r=>r.pascalCase.unsafeName).join("")+t.declaration.name.pascalCase.unsafeName}getTypeName(t){return t.pascalCase.unsafeName}getFieldName(t){return umo(t.pascalCase.unsafeName)}getImportPath(t){let r=t.packagePath.map(n=>n.pascalCase.unsafeName.toLowerCase());return[this.rootImportPath,...r].join("/")}getImportPathForRequest(t){return this.customConfig?.exportAllRequestsAtRoot?this.rootImportPath:this.getImportPath(t)}getContextTypeReference(){return Ht.typeReference({name:"Context",importPath:"context"})}getContextTodoFunctionInvocation(){return Ht.invokeFunc({func:Ht.typeReference({name:"TODO",importPath:"context"}),arguments_:[]})}getIoReaderTypeReference(){return Ht.typeReference({name:"Reader",importPath:"io"})}getTestingTypeReference(){return Ht.typeReference({name:"T",importPath:"testing"})}getNewStringsReaderFunctionInvocation(t){return Ht.invokeFunc({func:Ht.typeReference({name:"NewReader",importPath:"strings"}),arguments_:[Ht.TypeInstantiation.string(t)]})}getClientConstructorName(){return this.customConfig?.clientConstructorName!=null?this.customConfig.clientConstructorName:this.customConfig?.exportedClientName!=null?`New${this.customConfig.exportedClientName}`:`New${this.getClientName()}`}getClientName(){return this.customConfig?.clientName!=null?this.customConfig.clientName:"Client"}getClientImportPath(){return`${this.rootImportPath}/client`}getOptionImportPath(){return`${this.rootImportPath}/option`}getGoTypeReferenceFromDeclaration({declaration:t}){return Ht.typeReference({name:t.name.pascalCase.unsafeName,importPath:this.getImportPath(t.fernFilepath)})}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return this.getEnvironmentTypeReference(r)}getEnvironmentTypeReference(t){return Ht.typeReference({name:`Environments.${this.getTypeName(t)}`,importPath:this.rootImportPath})}static chainMethods(t,...r){if(r.length===0)throw new Error("Must have methods to chain");let n=t;for(let i of r)n=Ht.invokeMethod({on:n,method:i.method,arguments_:i.arguments_,multiline:i.multiline});return n}};St();var dYu="example",lmo="fern",IPm="do",_Lt="client",oWC=Ht.TypeInstantiation,wPm="WireMockBaseURL",CPm="WireMockClient",cMn=class{context;formatter;constructor({context:t,formatter:r}){this.context=t,this.formatter=r}async generateSnippet({endpoint:t,request:r,options:n}){return n?.config?.outputWiremockTests??!1?this.generateWiremockTest({endpoint:t,snippet:r}):await this.buildCodeBlock({endpoint:t,snippet:r}).toStringAsync({packageName:dYu,importPath:lmo,rootImportPath:this.context.rootImportPath,customConfig:this.context.customConfig??{},formatter:this.formatter})}generateSnippetSync({endpoint:t,request:r,options:n}){return n?.config?.outputWiremockTests??!1?this.generateWiremockTest({endpoint:t,snippet:r}):this.buildCodeBlock({endpoint:t,snippet:r}).toString({packageName:dYu,importPath:lmo,rootImportPath:this.context.rootImportPath,customConfig:this.context.customConfig??{},formatter:this.formatter})}async generateSnippetAst({endpoint:t,request:r,options:n}){throw new Error("Unsupported")}generateWiremockTest({endpoint:t,snippet:r}){return this.buildWiremockTestCodeBlock({endpoint:t,snippet:r}).toString({packageName:"wiremock",importPath:lmo,rootImportPath:this.context.rootImportPath,customConfig:this.context.customConfig??{},formatter:this.formatter})}buildCodeBlock({endpoint:t,snippet:r}){return Ht.codeblock(n=>{n.writeNode(Ht.func({name:IPm,parameters:[],return_:[],body:Ht.codeblock(i=>{i.writeNode(this.constructClient({endpoint:t,snippet:r})),i.writeLine(),i.writeNode(this.callMethod({endpoint:t,snippet:r}))})})),n.writeNewLineIfLastLineNot()})}buildWiremockTestCodeBlock({endpoint:t,snippet:r}){return Ht.codeblock(n=>{n.writeNode(Ht.func({name:"Test"+this.context.getTestMethodName(t)+"WithWireMock",parameters:[Ht.parameter({name:"t",type:Ht.Type.pointer(Ht.Type.reference(this.context.getTestingTypeReference()))})],return_:[],body:Ht.codeblock(i=>{for(let o of this.buildWiremockTestSetup({endpoint:t}))i.writeNode(o),i.writeLine();i.writeLine(),i.writeNode(this.constructWiremockTestClient({endpoint:t,snippet:r})),i.writeLine(),i.writeNode(this.callClientMethodAndAssert({endpoint:t,snippet:r,includeTestIdHeader:!0}))})})),n.writeNewLineIfLastLineNot()})}constructClient({endpoint:t,snippet:r}){return Ht.codeblock(n=>{n.write(`${_Lt} := `),n.writeNode(this.getRootClientFuncInvocation(this.getConstructorArgs({endpoint:t,snippet:r})))})}constructWiremockTestClient({endpoint:t,snippet:r}){return Ht.codeblock(n=>{n.write(`${_Lt} := `),n.writeNode(this.getRootClientFuncInvocation(this.getWiremockTestConstructorArgs()))})}writeMethodInvocation({writer:t,endpoint:r,snippet:n,includeTestIdHeader:i}){let{otherArgs:o,requestArg:s}=this.getMethodArgs({endpoint:r,snippet:n}),a=i?[Ht.codeblock(u=>{u.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"WithHTTPHeader",importPath:this.context.getOptionImportPath()}),arguments_:[Ht.codeblock('http.Header{"X-Test-Id": []string{"TEST-ID-PLACEHOLDER"}}')]}))})]:[];if(s!=null)if(s instanceof Ht.TypeInstantiation&&Ht.TypeInstantiation.isNop(s))t.writeNode(Ht.invokeMethod({on:Ht.codeblock(_Lt),method:this.getMethod({endpoint:r}),arguments_:[this.context.getContextTodoFunctionInvocation(),...o,Ht.codeblock("nil"),...a]}));else{t.write("request := "),t.writeNode(s),t.writeLine();let u=Ht.codeblock("request");t.writeNode(Ht.invokeMethod({on:Ht.codeblock(_Lt),method:this.getMethod({endpoint:r}),arguments_:[this.context.getContextTodoFunctionInvocation(),...o,u,...a]}))}else t.writeNode(Ht.invokeMethod({on:Ht.codeblock(_Lt),method:this.getMethod({endpoint:r}),arguments_:[this.context.getContextTodoFunctionInvocation(),...o,...a]}))}callMethod({endpoint:t,snippet:r}){return Ht.codeblock(n=>{this.writeMethodInvocation({writer:n,endpoint:t,snippet:r})})}getConstructorArgs({endpoint:t,snippet:r}){let n=[],i=this.getConstructorBaseUrlArg({baseUrl:r.baseURL,environment:r.environment});return i!=null&&n.push(i),t.auth!=null&&(r.auth!=null?n.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Ir.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`})),this.context.errors.scope(Lo.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),n}getWiremockTestConstructorArgs(){return[Ht.codeblock(t=>{t.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"WithBaseURL",importPath:this.context.getOptionImportPath()}),arguments_:[Ht.codeblock(wPm)]}))})]}getConstructorAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?[this.getConstructorBasicAuthArg({auth:t,values:r})]:[];case"bearer":return r.type==="bearer"?[this.getConstructorBearerAuthArg({auth:t,values:r})]:[];case"header":return r.type==="header"?[this.getConstructorHeaderAuthArg({auth:t,values:r})]:[];case"oauth":return r.type==="oauth"?[this.getConstructorOAuthAuthArg({values:r})]:[];case"inferred":return r.type==="inferred"?this.getConstructorInferredAuthArgs({auth:t,values:r}):[];default:Be(t)}}addError(t){this.context.errors.add({severity:Ir.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:r}){return Ht.codeblock(n=>{n.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"WithBasicAuth",importPath:this.context.getOptionImportPath()}),arguments_:[Ht.TypeInstantiation.string(r.username),Ht.TypeInstantiation.string(r.password)]}))})}getConstructorBaseUrlArg({baseUrl:t,environment:r}){let n=this.getBaseUrlArg({baseUrl:t,environment:r});if(n!=null)return Ht.codeblock(i=>{i.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"WithBaseURL",importPath:this.context.getOptionImportPath()}),arguments_:[n]}))})}getBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null)return Ht.TypeInstantiation.string(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);if(n==null){this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return Ht.TypeInstantiation.reference(n)}this.context.isMultiEnvironmentValues(r)&&this.context.errors.add({severity:Ir.Warning,message:"The Go SDK doesn't support a multi-environment client option yet; use the baseUrl option instead"})}}getConstructorBearerAuthArg({auth:t,values:r}){return Ht.codeblock(n=>{n.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:`With${t.token.pascalCase.unsafeName}`,importPath:this.context.getOptionImportPath()}),arguments_:[Ht.TypeInstantiation.string(r.token)]}))})}getConstructorHeaderAuthArg({auth:t,values:r}){return Ht.codeblock(n=>{n.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:`With${t.header.name.name.pascalCase.unsafeName}`,importPath:this.context.getOptionImportPath()}),arguments_:[this.context.dynamicTypeInstantiationMapper.convert({typeReference:t.header.typeReference,value:r.value})]}))})}getConstructorOAuthAuthArg({values:t}){return Ht.codeblock(r=>{r.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"WithClientCredentials",importPath:this.context.getOptionImportPath()}),arguments_:[Ht.TypeInstantiation.string(t.clientId),Ht.TypeInstantiation.string(t.clientSecret)]}))})}getConstructorInferredAuthArgs({auth:t,values:r}){let n=t.parameters;if(n==null||n.length===0)return[];let i=[];for(let o of n){if(o.typeReference.type==="optional"||o.typeReference.type==="literal")continue;let s=o.name.wireValue,a=r.values?.[s]??o.name.name.originalName,u=this.context.dynamicTypeInstantiationMapper.convert({typeReference:o.typeReference,value:a});Ht.TypeInstantiation.isNop(u)||i.push(Ht.codeblock(c=>{c.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:`With${o.name.name.pascalCase.unsafeName}`,importPath:this.context.getOptionImportPath()}),arguments_:[u]}))}))}return i}getConstructorHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getConstructorHeaderArg({header:i,value:o});s!=null&&n.push(s)}return n}getConstructorHeaderArg({header:t,value:r}){let n=this.context.dynamicTypeInstantiationMapper.convert({typeReference:t.typeReference,value:r});if(!Ht.TypeInstantiation.isNop(n))return Ht.codeblock(i=>{i.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:`With${t.name.name.pascalCase.unsafeName}`,importPath:this.context.getOptionImportPath()}),arguments_:[n]}))})}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];i.length>0&&n.push(...this.getPathParameters({namedParameters:i,snippet:r}).map(s=>s.value)),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let o=t.body!=null?this.getBodyRequestArg({body:t.body,value:r.requestBody}):void 0;return this.context.errors.unscope(),{otherArgs:n,requestArg:o}}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeInstantiationMapper.convertToPointerIfPossible({typeReference:t.value,value:r});default:Be(t)}}getBytesBodyRequestArg({value:t}){let r=typeof t=="string"?t:"";return Ht.TypeInstantiation.reference(Ht.invokeFunc({func:Ht.typeReference({name:"NewReader",importPath:"bytes"}),arguments_:[Ht.TypeInstantiation.bytes(r)]}))}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[],{inlinePathParameters:i,inlineFileProperties:o}={inlinePathParameters:this.context.customConfig?.inlinePathParameters??!0,inlineFileProperties:this.context.customConfig?.inlineFileProperties??!0};this.context.errors.scope(Lo.PathParameters);let s=[],a=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];a.length>0&&s.push(...this.getPathParameters({namedParameters:a,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let u=this.getFilePropertyInfo({request:t,snippet:r});this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})||n.push(...s.map(l=>l.value)),o||n.push(...u.fileFields.map(l=>l.value));let c=this.context.needsRequestParameter({request:t,inlinePathParameters:i,inlineFileProperties:o})?this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})?s:[],filePropertyInfo:u}):void 0;return{otherArgs:n,requestArg:c}}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Lo.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(l=>({name:l.name.name.pascalCase.unsafeName,value:this.context.dynamicTypeInstantiationMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.Headers);let u=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(l=>({name:l.name.name.pascalCase.unsafeName,value:this.context.dynamicTypeInstantiationMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let c=t.body!=null?this.getInlinedRequestBodyStructFields({body:t.body,value:r.requestBody,filePropertyInfo:i}):[];return this.context.errors.unscope(),Ht.TypeInstantiation.structPointer({typeReference:Ht.typeReference({name:this.context.getMethodName(t.declaration.name),importPath:this.context.getImportPathForRequest(t.declaration.fernFilepath)}),fields:[...n,...s,...u,...c]})}getInlinedRequestBodyStructFields({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyStructFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyStructField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyStructFields({filePropertyInfo:n});default:Be(t)}}getFileUploadRequestBodyStructFields({filePropertyInfo:t}){return this.context.customConfig?.inlineFileProperties??!0?[...t.fileFields,...t.bodyPropertyFields]:t.bodyPropertyFields}getReferencedRequestBodyPropertyStructField({body:t,value:r}){return{name:this.context.getTypeName(t.bodyKey),value:this.getReferencedRequestBodyPropertyTypeInstantiation({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyTypeInstantiation({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeInstantiationMapper.convert({typeReference:t.value,value:r});default:Be(t)}}getInlinedRequestBodyPropertyStructFields({parameters:t,value:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}});for(let o of i)n.push({name:this.context.getFieldName(o.name.name),value:this.context.dynamicTypeInstantiationMapper.convert(o)});return n}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValueOrDefault({parameters:t,values:r.pathParameters??{}});for(let o of i)n.push({name:this.context.getTypeName(o.name.name),value:this.context.dynamicTypeInstantiationMapper.convertToPointerIfPossible(o)});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getMethodName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getRootClientFuncInvocation(t){return Ht.invokeFunc({func:Ht.typeReference({name:this.context.getClientConstructorName(),importPath:this.context.getClientImportPath()}),arguments_:t})}buildWiremockTestSetup({endpoint:t,errorCase:r}){let n="stub";return[]}callClientMethodAndAssert({endpoint:t,snippet:r,includeTestIdHeader:n}){return Ht.codeblock(i=>{this.writeMethodInvocation({writer:i,endpoint:t,snippet:r,includeTestIdHeader:!0}),i.writeLine(),i.writeLine(),i.write("ok, countErr := "),i.writeNode(Ht.invokeMethod({on:Ht.codeblock(CPm),method:"Verify",arguments_:[Ht.invokeMethod({on:Ht.codeblock("stub"),method:"Request",arguments_:[],multiline:!1}),Ht.codeblock("1")],multiline:!1})),i.writeLine(),i.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"NoError",importPath:"github.com/stretchr/testify/require"}),arguments_:[Ht.codeblock("t"),Ht.codeblock("countErr"),Ht.TypeInstantiation.string("Failed to verify WireMock request was matched")],multiline:!1})),i.writeLine(),i.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"True",importPath:"github.com/stretchr/testify/require"}),arguments_:[Ht.codeblock("t"),Ht.codeblock("ok"),Ht.TypeInstantiation.string("WireMock request was not matched")],multiline:!1})),i.writeLine()})}};var SLt=class extends Wv{formatter;constructor({ir:t,config:r,formatter:n}){super(new uMn({ir:t,config:r})),this.formatter=n}async generate(t,r){return super.generate(t,r)}generateSync(t,r){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new cMn({context:t,formatter:this.formatter})}};var pMn=require("fs/promises"),mYu=Ae(require("path"),1);var lMn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new SLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");for(let[n,i]of r.entries())try{let o=pS(i);if(o==null)continue;let s=await this.dynamicSnippetsGenerator.generate(o),a=this.getTestFilePath({outputDir:t,idx:n});await(0,pMn.mkdir)(mYu.default.dirname(a),{recursive:!0}),await(0,pMn.writeFile)(a,s.snippet)}catch(o){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(i.endpoint)}: ${o}`),o instanceof Error&&o.stack&&this.context.logger.error(o.stack)}this.context.logger.debug("Done generating dynamic snippet tests")}getTestFilePath({outputDir:t,idx:r}){return Ge(t,Se.of(`dynamic-snippets/example${r}/snippet.go`))}};qt();St();var vMe=class extends wC{packageName;customConfig;formatter;imports=new Set;constructor({packageName:t,customConfig:r,formatter:n}){super(),this.packageName=t,this.customConfig=r,this.formatter=n??new B7}addImport(t){this.imports.add(t)}getImports(){return new Set(this.imports)}};var BLt=class extends vMe{constructor({packageName:t,customConfig:r,formatter:n}){super({packageName:t,customConfig:r,formatter:n})}async toStringAsync(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.format(t)}catch(r){throw new Error(`Failed to format Java file: ${r}
2520
+ `)?`\`${r}\``:`"${ILt(r)}"`);return;case"number":t.write(r.toString());return;case"object":if(r==null){t.write("nil");return}if(Array.isArray(r)){this.writeAnyArray({writer:t,value:r});return}this.writeAnyObject({writer:t,value:r});return;default:throw new Error(`Internal error; unsupported unknown type: ${typeof r}`)}}writeAnyArray({writer:t,value:r}){if(t.write("[]any"),r.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let n of r)t.writeNode(e.any(n)),t.writeLine(",");t.dedent(),t.write("}")}writeAnyObject({writer:t,value:r}){t.write("map[string]any");let n=Object.entries(r).sort(([i],[o])=>i<o?-1:i>o?1:0);if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let[i,o]of n)t.write(`"${ILt(i)}": `),t.writeNode(e.any(o)),t.writeLine(",");t.dedent(),t.write("}")}writeMap({writer:t,map:r}){t.write("map["),t.writeNode(r.keyType),t.write("]"),t.writeNode(r.valueType);let n=$Tm({entries:r.entries});if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let i of n)i.key.write(t),t.write(": "),i.value.write(t),t.writeLine(",");t.dedent(),t.write("}")}writeOptional({writer:t,type:r}){if(zTm.has(r.internalType.type)){t.writeNode(VTm({writer:t,type:r}));return}if(pYu.has(r.internalType.type)){r.write(t);return}if(r.internalType.type==="enum"){t.writeNode(new cfe({on:r.internalType.typeReference,method:"Ptr",arguments_:[]}));return}t.write("&"),r.write(t)}static isAlreadyOptional(t){return t.internalType.type==="optional"||pYu.has(t.internalType.type)}writeSlice({writer:t,slice:r}){t.write("[]"),t.writeNode(r.valueType);let n=KTm({values:r.values});if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let i of n)i.write(t),t.writeLine(",");t.dedent(),t.write("}")}writeStruct({writer:t,struct:r}){t.writeNode(r.typeReference),r.generics!=null&&(t.write("["),r.generics.forEach((i,o)=>{o>0&&t.write(", "),t.writeNode(i)}),t.write("]"));let n=HTm({fields:r.fields});if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let i of n)t.write(`${i.name}: `),i.value.write(t),t.writeLine(",");t.dedent(),t.write("}")}};function VTm({writer:e,type:t}){return new R7({func:new eF({name:qTm({type:t}),importPath:e.rootImportPath}),arguments_:[t]})}function qTm({type:e}){switch(e.internalType.type){case"bool":return"Bool";case"bytes":return"Bytes";case"date":case"dateTime":return"Time";case"float64":return"Float64";case"int":return"Int";case"int64":return"Int64";case"string":return"String";case"uuid":return"UUID";default:return""}}function GTm({writer:e,type:t}){let r=t.type==="date"?"MustParseDate":"MustParseDateTime";return new R7({func:new eF({name:r,importPath:e.rootImportPath}),arguments_:[new Tne(`"${t.value}"`)]})}function WTm({value:e}){return new R7({func:new eF({name:"MustParse",importPath:"github.com/google/uuid"}),arguments_:[new Tne(`"${e}"`)]})}function ILt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function $Tm({entries:e}){return e.filter(t=>!ZR.isNop(t.key)&&!ZR.isNop(t.value))}function HTm({fields:e}){return e.filter(t=>!ZR.isNop(t.value))}function KTm({values:e}){return e.filter(t=>!ZR.isNop(t))}var fMe=class e extends Vc{name;docs;members=[];methods=[];constructor_;constructor({name:t,docs:r}){super(),this.name=t,this.docs=r}addConstructor(t){this.constructor_=t}addMember(t){this.members.push(t)}addMethod(t){this.methods.push(t)}write(t){this.writeType({writer:t}),this.writeMembers({writer:t}),this.writeConstructor({writer:t}),this.writeMethods({writer:t})}writeType({writer:t}){t.writeNode(new CB({docs:this.docs})),t.writeLine(`type ${this.name} string`)}writeMembers({writer:t}){if(this.members.length!==0){t.newLine(),t.writeLine("const ("),t.indent();for(let r of this.members)t.writeNode(new CB({docs:r.docs})),t.writeNode(e.getMemberIdentifier({name:this.name,member:r})),t.write(" = "),t.writeNode(ZR.string(r.value)),t.newLine();t.dedent(),t.write(")")}}writeConstructor({writer:t}){this.constructor_!=null&&(t.newLine(),t.writeNode(this.constructor_))}writeMethods({writer:t}){t.newLine();for(let r of this.methods)t.newLine(),t.writeNode(r),t.newLine()}static getMemberIdentifier({name:t,member:r}){return new ufe(`${t}${r.name}`)}};var dMe=class extends Vc{name;type;docs;tags=[];constructor({name:t,type:r,docs:n,tags:i}){super(),this.name=t,this.type=r,this.docs=n,this.tags=i??[]}addTags(...t){this.tags.push(...t)}write(t){t.writeNode(new CB({docs:this.docs})),t.write(`${this.name} `),this.type.write(t),this.writeTags({writer:t})}writeTags({writer:t}){this.tags.length!==0&&(t.write(" `"),this.tags.forEach((r,n)=>{n>0&&t.write(" "),t.write(`${r.name}:"${r.value}"`)}),t.write("`"))}};var mMe=class extends Vc{nodes;constructor({nodes:t}={nodes:[]}){super(),this.nodes=t??[]}add(...t){this.nodes.push(...t)}write(t){for(let r of this.nodes)r.write(t)}};var lfe=class extends Vc{parameters;return_;name;body;docs;typeReference;multiline;receiver;pointerReceiver;constructor({name:t,parameters:r,return_:n,body:i,docs:o,typeReference:s,multiline:a,receiver:u,pointerReceiver:c}){super(),this.name=t,this.parameters=r,this.return_=n,this.body=i,this.docs=o,this.typeReference=s,this.multiline=a,this.receiver=u,this.pointerReceiver=c}write(t){t.writeNode(new CB({docs:this.docs})),t.write("func"),this.typeReference!=null&&this.writeReceiver({writer:t,typeReference:this.typeReference,receiver:this.receiver}),this.name!=null&&t.write(` ${this.name}`),Yft({writer:t,arguments_:this.parameters,multiline:this.multiline}),this.return_!=null&&(t.write(" "),this.return_.length>1&&t.write("("),this.return_.forEach((r,n)=>{n>0&&t.write(", "),t.writeNode(r)}),this.return_.length>1&&t.write(")")),t.writeLine("{"),t.indent(),this.body?.write(t),t.dedent(),t.writeNewLineIfLastLineNot(),t.write("}")}writeReceiver({writer:t,typeReference:r,receiver:n}){t.write(` (${this.getReceiverName({typeReference:r,receiver:n})} `),this.pointerReceiver&&t.write("*"),r.write(t),t.write(")")}getReceiverName({typeReference:t,receiver:r}){return r??t.name.charAt(0).toLowerCase()}};var hMe=class extends Vc{func;constructor({name:t,parameters:r,return_:n,body:i,docs:o,multiline:s}){super(),this.func=new lfe({name:t,parameters:r,return_:n,body:i,docs:o,multiline:s})}get parameters(){return this.func.parameters}get return_(){return this.func.return_}get name(){return this.func.name}get body(){return this.func.body}get docs(){return this.func.docs}write(t){t.writeNode(this.func)}};var wLt=class extends Vc{nodes;constructor({nodes:t}){super(),this.nodes=t}write(t){for(let r of this.nodes)t.newLine(),r.write(t),t.newLine()}};var gMe=class extends Vc{name;type;docs;constructor({name:t,type:r,docs:n}){super(),this.name=t,this.type=r,this.docs=n}write(t){t.writeNode(new CB({docs:this.docs})),t.write(`${this.name} `),this.type.write(t)}};var AMe=class extends Vc{node;constructor({node:t}){super(),this.node=t}write(t){t.write("*"),this.node.write(t)}};var yMe=class extends Vc{on;selector;constructor({on:t,selector:r}){super(),this.on=t,this.selector=r}write(t){t.writeNode(this.on),t.write("."),t.writeNode(this.selector)}};var bMe=class extends Vc{name;embeds=[];fields=[];docs;methods=[];constructor_;constructor({name:t,embeds:r,fields:n,docs:i}){super(),this.name=t,this.docs=i,this.embeds=r??[],this.fields=n??[]}addConstructor(t){this.constructor_=t}addField(...t){this.fields.push(...t)}addMethod(...t){this.methods.push(...t)}write(t){this.writeType({writer:t}),this.constructor_!=null&&(t.newLine(),t.newLine(),this.writeConstructor({writer:t,constructor:this.constructor_})),this.writeMethods({writer:t})}writeType({writer:t}){if(t.writeNode(new CB({docs:this.docs})),this.name!=null?t.write(`type ${this.name} struct {`):t.write("struct{"),this.embeds.length===0&&this.fields.length===0){t.writeLine("}");return}t.newLine(),t.indent();for(let i of this.embeds)t.writeNode(i),t.newLine();let r=this.fields.filter(i=>this.isExported(i));for(let i of r)t.writeNode(i),t.newLine();let n=this.fields.filter(i=>!this.isExported(i));r.length>0&&n.length>0&&t.newLine();for(let i of n)t.writeNode(i),t.newLine();t.dedent(),t.write("}")}writeConstructor({writer:t,constructor:r}){r.name!=null?t.write(`func ${r.name}(`):t.write(`func New${this.name}(`),r.parameters.forEach((n,i)=>{i>0&&t.write(", "),t.writeNode(n)}),t.write(`) *${this.name} {`),t.newLine(),t.indent(),t.writeNode(r.body),t.writeNewLineIfLastLineNot(),t.dedent(),t.writeLine("}")}writeMethods({writer:t}){if(this.methods.length!==0){t.writeNewLineIfLastLineNot();for(let r of this.methods)t.newLine(),t.writeNode(r),t.newLine()}}isExported(t){let r=t.name.charAt(0);return r===r.toUpperCase()}};var CLt=class extends Vc{on;cases;default;constructor({on:t,cases:r,default:n}){super(),this.on=t,this.cases=r,this.default=n}write(t){let r=this.cases;this.default!=null&&r.push({on:new ufe("default"),body:this.default}),t.write("switch "),t.writeNode(this.on),t.writeLine("{"),t.indent();for(let n of r)t.write("case "),t.writeNode(n.on),t.writeLine(":"),t.indent(),t.writeNode(n.body),t.dedent(),t.writeNewLineIfLastLineNot();t.dedent(),t.write("}")}};St();var JTm=new Set(["any","bytes","map","slice"]),xLt=class e extends Vc{internalType;constructor(t){super(),this.internalType=t}write(t,{comment:r}={}){switch(this.internalType.type){case"any":t.write("any");break;case"bool":t.write("bool");break;case"bytes":t.write("[]byte");break;case"date":case"dateTime":t.writeNode(nMn);break;case"error":t.write("error");break;case"float64":t.write("float64");break;case"int":t.write("int");break;case"int64":t.write("int64");break;case"map":{t.write("map["),this.internalType.keyType.write(t),t.write("]"),this.internalType.valueType.write(t);break}case"optional":{t.write("*"),this.internalType.value.write(t);break}case"reference":t.writeNode(this.internalType.value);break;case"slice":t.write("[]"),this.internalType.value.write(t);break;case"string":t.write("string");break;case"uuid":t.writeNode(iMn);break;case"variadic":t.write("..."),this.internalType.value.write(t);break;default:Be(this.internalType)}}isOptional(){return this.internalType.type==="optional"}isIterable(){return this.internalType.type==="slice"||this.internalType.type==="variadic"}iterableElement(){if(this.internalType.type==="slice"||this.internalType.type==="variadic")return this.internalType.value}underlying(){return this.internalType.type==="optional"?this.internalType.value:this}static any(){return new this({type:"any"})}static bool(){return new this({type:"bool"})}static bytes(){return new this({type:"bytes"})}static date(){return new this({type:"date"})}static dateTime(){return new this({type:"dateTime"})}static dereference(t){return t.internalType.type==="optional"?t.internalType.value:t}static error(){return new this({type:"error"})}static float64(){return new this({type:"float64"})}static int(){return new this({type:"int"})}static int64(){return new this({type:"int64"})}static map(t,r){return new this({type:"map",keyType:t,valueType:r})}static optional(t){return this.isAlreadyOptional(t)?t:new this({type:"optional",value:t})}static pointer(t){return e.optional(t)}static reference(t){return new this({type:"reference",value:t})}static slice(t){return new this({type:"slice",value:t})}static string(){return new this({type:"string"})}static uuid(){return new this({type:"uuid"})}static variadic(t){return this.isAlreadyVariadic(t)?t:new this({type:"variadic",value:t})}static isAlreadyOptional(t){return t.internalType.type==="optional"||JTm.has(t.internalType.type)}static isAlreadyVariadic(t){return t.internalType.type==="variadic"}},nMn=new eF({importPath:"time",name:"Time"}),iMn=new eF({importPath:"github.com/google/uuid",name:"UUID"}),amo=new eF({importPath:"io",name:"Reader"});var EMe=class extends Vc{name;type;docs;constructor({name:t,type:r,docs:n}){super(),this.name=t,this.type=r,this.docs=n}write(t){t.writeNode(new CB({docs:this.docs})),t.write("type "),t.write(this.name),t.write(" "),t.writeNode(this.type)}};function YTm(e){return new pMe(e)}function XTm(e){return new Tne(e)}function ZTm(e){return new fMe(e)}function ePm(e){return new dMe(e)}function tPm(e={}){return new mMe(e)}function rPm(e){return new hMe(e)}function nPm(e){return new ufe(e)}function iPm(e){return new R7(e)}function oPm(e){return new cfe(e)}function sPm(e){return new lfe(e)}function aPm(e){return new gMe(e)}function uPm(e){return new AMe(e)}function cPm(e){return new yMe(e)}function lPm(e={}){return new bMe(e)}function pPm(e){return new CLt(e)}function fPm(e){return new EMe(e)}function dPm(e){return new eF(e)}var mPm=new Set(["string"]);function umo(e){if(e==="")return"Underscore";let t=e;for(;t.startsWith("_");)t=t.slice(1);if(t==="")return"Underscore";if(t.length>0&&/^\d/.test(t))return"Field"+t;let r=t,n=t[0];return t.length>0&&n!=null&&n!==n.toUpperCase()&&(r=n.toUpperCase()+t.slice(1)),mPm.has(r.toLowerCase())?"Field"+r:r}sA();var fYu=Ae(require("path"),1),hPm="sdk";function cmo({config:e,customConfig:t}){let r=APm({config:e}),n=gPm({config:e,customConfig:t});return r!=null?bPm({importPath:n,majorVersion:r}):n}function gPm({config:e,customConfig:t,isModulePath:r=!1}){let n=t?.importPath??t?.module?.path??(e.output.mode.type==="github"?EPm(e.output.mode.repoUrl,"https://"):hPm);return r?n:fYu.default.join(n,t?.packagePath??"")}function APm({config:e}){let t=yPm({config:e});if(!(t==null||t==="v0"||t==="v1"))return`${t}`}function yPm({config:e}){let t=vPm(e);if(t==null)return;let r=t.split(".");if(r[0]==null)return;let n=r[0];return n.startsWith("v")?n:`v${n}`}function bPm({importPath:e,majorVersion:t}){return qB(e)===t?e:`${e}/${t}`}function EPm(e,t){return e.startsWith(t)?e.slice(t.length):e}function vPm(e){let t=e?.output?.mode;if(t!=null)return t.type==="github"||t.type==="publish"?t.version:void 0}St();var oMn=class{context;constructor({context:t}){this.context=t}convert(t){if(t.value===null&&!this.context.isNullable(t.typeReference)&&this.context.errors.add({severity:Ir.Critical,message:"Expected non-null value, but got null"}),t.value==null)return Ht.TypeInstantiation.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value});case"literal":return Ht.TypeInstantiation.nop();case"map":return this.convertMap({map:t.typeReference,value:t.value});case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?Ht.TypeInstantiation.nop():this.convertNamed({named:r,value:t.value,as:t.as})}case"nullable":{let r=t.typeReference.value;if(r.type==="named"){let n=this.context.resolveNamedType({typeId:r.value});if(n?.type==="alias"&&["list","set","map"].includes(n.typeReference.type)){let i=this.convert({typeReference:n.typeReference,value:t.value,as:t.as}),o=this.context.getTypeName(n.declaration.name),s=this.context.getImportPath(n.declaration.fernFilepath);return this.reconstructAliasCollectionLiteral({collectionLiteral:i,aliasName:o,aliasImportPath:s})}if(n?.type==="alias"&&n.typeReference.type==="literal")return this.convertLiteralToOptionalPrimitive(n.typeReference.value)}return Ht.TypeInstantiation.optional(this.convert({typeReference:r,value:t.value,as:t.as}))}case"optional":{let r=t.typeReference.value;if(r.type==="named"){let n=this.context.resolveNamedType({typeId:r.value});if(n?.type==="alias"&&["list","set","map"].includes(n.typeReference.type)){let i=this.convert({typeReference:n.typeReference,value:t.value,as:t.as}),o=this.context.getTypeName(n.declaration.name),s=this.context.getImportPath(n.declaration.fernFilepath);return this.reconstructAliasCollectionLiteral({collectionLiteral:i,aliasName:o,aliasImportPath:s})}if(n?.type==="alias"&&n.typeReference.type==="literal")return this.convertLiteralToOptionalPrimitive(n.typeReference.value)}return Ht.TypeInstantiation.optional(this.convert({typeReference:r,value:t.value,as:t.as}))}case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as});case"set":return this.convertList({list:t.typeReference.value,value:t.value});case"unknown":return this.convertUnknown({value:t.value});default:Be(t.typeReference)}}convertToPointerIfPossible(t){let r=this.convert(t);return t.typeReference.type==="named"&&this.context.resolveNamedType({typeId:t.typeReference.value})?.type==="enum"?Ht.TypeInstantiation.reference(Ht.invokeMethod({on:r,method:"Ptr",arguments_:[]})):r}convertList({list:t,value:r}){return Array.isArray(r)?Ht.TypeInstantiation.slice({valueType:this.context.dynamicTypeMapper.convert({typeReference:t}),values:r.map((n,i)=>{this.context.errors.scope({index:i});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),Ht.TypeInstantiation.nop())}convertMap({map:t,value:r}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),Ht.TypeInstantiation.nop()):Ht.TypeInstantiation.map({keyType:this.context.dynamicTypeMapper.convert({typeReference:t.key}),valueType:this.context.dynamicTypeMapper.convert({typeReference:t.value}),entries:Object.entries(r).sort(([n],[i])=>n<i?-1:n>i?1:0).map(([n,i])=>{this.context.errors.scope(n);try{return{key:this.convert({typeReference:t.key,value:n,as:"key"}),value:this.convert({typeReference:t.value,value:i})}}finally{this.context.errors.unscope()}})})}convertNamed({named:t,value:r,as:n}){switch(t.type){case"alias":return this.convertAlias({aliasType:t,value:r,as:n});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:r});case"enum":return this.convertEnum({enum_:t,value:r});case"object":return this.convertObject({object_:t,value:r});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r});default:Be(t)}}convertAlias({aliasType:t,value:r,as:n}){return t.typeReference.type==="literal"?Ht.TypeInstantiation.reference(Ht.invokeFunc({func:Ht.typeReference({name:this.context.getTypeName(t.declaration.name),importPath:this.context.getImportPath(t.declaration.fernFilepath)}),arguments_:[this.convertLiteralValue(t.typeReference.value)]})):this.convert({typeReference:t.typeReference,value:r,as:n})}reconstructAliasCollectionLiteral({collectionLiteral:t,aliasName:r,aliasImportPath:n}){let i=t.internalType;return i.type==="slice"?Ht.TypeInstantiation.reference(Ht.codeblock(o=>{o.write("&"),o.writeNode(Ht.typeReference({name:r,importPath:n}));let s=i.values;if(s.length===0){o.write("{}");return}o.writeLine("{"),o.indent();for(let a of s)o.writeNode(a),o.writeLine(",");o.dedent(),o.write("}")})):i.type==="map"?Ht.TypeInstantiation.reference(Ht.codeblock(o=>{o.write("&"),o.writeNode(Ht.typeReference({name:r,importPath:n}));let s=i.entries;if(s.length===0){o.write("{}");return}o.writeLine("{"),o.indent();for(let a of s)o.writeNode(a.key),o.write(": "),o.writeNode(a.value),o.writeLine(",");o.dedent(),o.write("}")})):Ht.TypeInstantiation.reference(Ht.codeblock(o=>{o.write("&"),o.writeNode(t)}))}convertLiteralValue(t){switch(t.type){case"boolean":return Ht.TypeInstantiation.bool(t.value);case"string":return Ht.TypeInstantiation.string(t.value);default:Be(t)}}convertLiteralToOptionalPrimitive(t){switch(t.type){case"boolean":return Ht.TypeInstantiation.optional(Ht.TypeInstantiation.bool(t.value));case"string":return Ht.TypeInstantiation.optional(Ht.TypeInstantiation.string(t.value));default:Be(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r}){let n=this.context.getGoTypeReferenceFromDeclaration({declaration:t.declaration}),i=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(i==null)return Ht.TypeInstantiation.nop();let o=i.singleDiscriminatedUnionType,s=this.getBaseFields({discriminatedUnionTypeInstance:i,singleDiscriminatedUnionType:o});switch(o.type){case"samePropertiesAsObject":{let a=this.context.resolveNamedType({typeId:o.typeId});return a==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.structPointer({typeReference:n,fields:[{name:this.context.getFieldName(o.discriminantValue.name),value:this.convertNamed({named:a,value:i.value})},...s]})}case"singleProperty":{let a=this.context.getRecord(i.value);if(a==null)return Ht.TypeInstantiation.nop();try{return this.context.errors.scope(o.discriminantValue.wireValue),Ht.TypeInstantiation.structPointer({typeReference:n,fields:[{name:this.context.getFieldName(o.discriminantValue.name),value:this.convert({typeReference:o.typeReference,value:a[o.discriminantValue.wireValue]})},...s]})}finally{this.context.errors.unscope()}}case"noProperties":return Ht.TypeInstantiation.structPointer({typeReference:n,fields:[{name:this.context.getFieldName(i.discriminantValue.name),value:Ht.TypeInstantiation.string(o.discriminantValue.wireValue)},...s]});default:Be(o)}}getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r}){return this.context.associateByWireValue({parameters:r.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(i=>{this.context.errors.scope(i.name.wireValue);try{return{name:this.context.getFieldName(i.name.name),value:this.convert(i)}}finally{this.context.errors.unscope()}})}convertObject({object_:t,value:r}){let n=this.context.associateByWireValue({parameters:t.properties,values:this.context.getRecord(r)??{}});return Ht.TypeInstantiation.structPointer({typeReference:Ht.typeReference({name:this.context.getTypeName(t.declaration.name),importPath:this.context.getImportPath(t.declaration.fernFilepath)}),fields:n.map(i=>{this.context.errors.scope(i.name.wireValue);try{return{name:this.context.getFieldName(i.name.name),value:this.convert(i)}}finally{this.context.errors.unscope()}})})}convertEnum({enum_:t,value:r}){let n=this.getEnumValueName({enum_:t,value:r});return n==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.enum(Ht.typeReference({name:n,importPath:this.context.getImportPath(t.declaration.fernFilepath)}))}getEnumValueName({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Ir.Critical,message:`Expected enum value string, got: ${typeof r}`});return}let n=t.values.find(i=>i.wireValue===r);if(n==null){this.context.errors.add({severity:Ir.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return`${this.context.getTypeName(t.declaration.name)}${this.context.getTypeName(n.name)}`}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r}){let n=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r});if(n==null)return Ht.TypeInstantiation.nop();let i=this.getUndiscriminatedUnionFieldName({typeReference:n.valueTypeReference});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.structPointer({typeReference:this.context.getGoTypeReferenceFromDeclaration({declaration:t.declaration}),fields:[{name:i,value:n.typeInstantiation}]})}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r}){for(let n of t.types)try{let i=this.convert({typeReference:n,value:r});if(Ht.TypeInstantiation.isNop(i))continue;return{valueTypeReference:n,typeInstantiation:i}}catch{continue}this.context.errors.add({severity:Ir.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}getUndiscriminatedUnionFieldName({typeReference:t}){switch(t.type){case"list":return this.getUndiscriminatedUnionFieldNameForList({list:t});case"literal":return this.getUndiscriminatedUnionFieldNameForLiteral({literal:t.value});case"map":return this.getUndiscriminatedUnionFieldNameForMap({map:t});case"named":{let r=this.context.resolveNamedType({typeId:t.value});return r==null?void 0:this.context.getTypeName(r.declaration.name)}case"optional":return this.getUndiscriminatedUnionFieldNameForOptional({typeReference:t});case"nullable":return this.getUndiscriminatedUnionFieldNameForOptional({typeReference:t});case"primitive":return this.getUndiscriminatedUnionFieldNameForPrimitive({primitive:t.value});case"set":return this.getUndiscriminatedUnionFieldNameForSet({set:t});case"unknown":return"Unknown";default:Be(t)}}getUndiscriminatedUnionFieldNameForList({list:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t.value});if(r!=null)return`${r}List`}getUndiscriminatedUnionFieldNameForMap({map:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t.key});if(r==null)return;let n=this.getUndiscriminatedUnionFieldName({typeReference:t.value});if(n!=null)return`${r}${n}Map`}getUndiscriminatedUnionFieldNameForOptional({typeReference:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t.value});if(r!=null)return`${r}Optional`}getUndiscriminatedUnionFieldNameForSet({set:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t.value});if(r!=null)return`${r}Set`}getUndiscriminatedUnionFieldNameForLiteral({literal:t}){switch(t.type){case"boolean":return t.value?"TrueLiteral":"FalseLiteral";case"string":return`${t.value}StringLiteral`;default:Be(t)}}getUndiscriminatedUnionFieldNameForPrimitive({primitive:t}){switch(t){case"INTEGER":case"UINT":return"Integer";case"LONG":case"UINT_64":return"Long";case"FLOAT":case"DOUBLE":return"Double";case"BOOLEAN":return"Boolean";case"BIG_INTEGER":case"STRING":return"String";case"UUID":return"Uuid";case"DATE":return"Date";case"DATE_TIME":return"DateTime";case"BASE_64":return"Base64";default:Be(t)}}convertUnknown({value:t}){return Ht.TypeInstantiation.any(t)}convertPrimitive({primitive:t,value:r,as:n}){switch(t){case"INTEGER":case"UINT":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.int(i)}case"LONG":case"UINT_64":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.int64(i)}case"FLOAT":case"DOUBLE":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.float64(i)}case"BOOLEAN":{let i=this.getValueAsBoolean({value:r,as:n});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.bool(i)}case"STRING":{let i=this.context.getValueAsString({value:r});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.string(i)}case"DATE":{let i=this.context.getValueAsString({value:r});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.date(i)}case"DATE_TIME":{let i=this.context.getValueAsString({value:r});if(i==null)return Ht.TypeInstantiation.nop();let o=this.normalizeDateTimeString(i);return Ht.TypeInstantiation.dateTime(o)}case"UUID":{let i=this.context.getValueAsString({value:r});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.uuid(i)}case"BASE_64":{let i=this.context.getValueAsString({value:r});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.bytes(i)}case"BIG_INTEGER":{let i=this.context.getValueAsString({value:r});return i==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.string(i)}default:Be(t)}}getValueAsNumber({value:t,as:r}){let n=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:n})}normalizeDateTimeString(t){return/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t}T00:00:00Z`:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(t)?`${t}Z`:t}};St();var sMn=class{context;constructor({context:t}){this.context=t}convert(t){switch(t.typeReference.type){case"list":return Ht.Type.slice(this.convert({typeReference:t.typeReference.value}));case"literal":return this.convertLiteral({literal:t.typeReference.value});case"map":return Ht.Type.map(this.convert({typeReference:t.typeReference.key}),this.convert({typeReference:t.typeReference.value}));case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.convertUnknown():this.convertNamed({named:r})}case"optional":return Ht.Type.optional(this.convert({typeReference:t.typeReference.value}));case"nullable":return Ht.Type.optional(this.convert({typeReference:t.typeReference.value}));case"primitive":return this.convertPrimitive({primitive:t.typeReference.value});case"set":return Ht.Type.slice(this.convert({typeReference:t.typeReference}));case"unknown":return this.convertUnknown();default:Be(t.typeReference)}}convertLiteral({literal:t}){switch(t.type){case"boolean":return Ht.Type.bool();case"string":return Ht.Type.string()}}convertNamed({named:t}){let r=Ht.Type.reference(Ht.typeReference({name:this.context.getTypeName(t.declaration.name),importPath:this.context.getImportPath(t.declaration.fernFilepath)}));switch(t.type){case"alias":case"enum":return r;case"discriminatedUnion":case"object":case"undiscriminatedUnion":return Ht.Type.pointer(r);default:Be(t)}}convertUnknown(){return Ht.Type.any()}convertPrimitive({primitive:t}){switch(t){case"INTEGER":return Ht.Type.int();case"UINT":return Ht.Type.int();case"LONG":return Ht.Type.int64();case"UINT_64":return Ht.Type.int64();case"FLOAT":return Ht.Type.float64();case"DOUBLE":return Ht.Type.float64();case"BOOLEAN":return Ht.Type.bool();case"STRING":return Ht.Type.string();case"DATE":return Ht.Type.date();case"DATE_TIME":return Ht.Type.dateTime();case"UUID":return Ht.Type.uuid();case"BASE_64":return Ht.Type.bytes();case"BIG_INTEGER":return Ht.Type.string();default:Be(t)}}};St();var aMn=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({body:t,value:r}){let n={fileFields:[],bodyPropertyFields:[]},i=this.context.getRecord(r)??{};for(let o of t.properties)switch(o.type){case"file":n.fileFields.push({name:this.context.getFieldName(o.name),value:this.getSingleFileProperty({property:o,record:i})});break;case"fileArray":n.fileFields.push({name:this.context.getFieldName(o.name),value:this.getArrayFileProperty({property:o,record:i})});break;case"bodyProperty":n.bodyPropertyFields.push({name:this.context.getFieldName(o.name.name),value:this.getBodyProperty({property:o,record:i})});break;default:Be(o)}return n}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r})||"";return Ht.TypeInstantiation.reference(this.context.getNewStringsReaderFunctionInvocation(n))}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});return n==null?Ht.TypeInstantiation.nop():Ht.TypeInstantiation.slice({valueType:Ht.Type.reference(this.context.getIoReaderTypeReference()),values:n.map(i=>Ht.TypeInstantiation.reference(this.context.getNewStringsReaderFunctionInvocation(i)))})}getBodyProperty({property:t,record:r}){let n=r[t.name.wireValue];return n==null?Ht.TypeInstantiation.nop():this.context.dynamicTypeInstantiationMapper.convert({typeReference:t.typeReference,value:n})}};var uMn=class e extends $v{ir;customConfig;dynamicTypeMapper;dynamicTypeInstantiationMapper;filePropertyMapper;rootImportPath;constructor({ir:t,config:r}){super({ir:t,config:r}),this.ir=t,this.customConfig=r.customConfig!=null?r.customConfig:void 0,this.dynamicTypeMapper=new sMn({context:this}),this.dynamicTypeInstantiationMapper=new oMn({context:this}),this.filePropertyMapper=new aMn({context:this}),this.rootImportPath=cmo({config:r,customConfig:this.customConfig})}clone(){return new e({ir:this.ir,config:this.config})}isOptional(t){switch(t.type){case"optional":case"map":return!0;case"nullable":case"list":case"set":return this.isOptional(t.value);case"named":case"literal":case"primitive":case"unknown":return!1;default:Be(t)}}getMethodName(t){return t.pascalCase.unsafeName}getTestMethodName(t){return t.declaration.fernFilepath.allParts.map(r=>r.pascalCase.unsafeName).join("")+t.declaration.name.pascalCase.unsafeName}getTypeName(t){return t.pascalCase.unsafeName}getFieldName(t){return umo(t.pascalCase.unsafeName)}getImportPath(t){let r=t.packagePath.map(n=>n.pascalCase.unsafeName.toLowerCase());return[this.rootImportPath,...r].join("/")}getImportPathForRequest(t){return this.customConfig?.exportAllRequestsAtRoot?this.rootImportPath:this.getImportPath(t)}getContextTypeReference(){return Ht.typeReference({name:"Context",importPath:"context"})}getContextTodoFunctionInvocation(){return Ht.invokeFunc({func:Ht.typeReference({name:"TODO",importPath:"context"}),arguments_:[]})}getIoReaderTypeReference(){return Ht.typeReference({name:"Reader",importPath:"io"})}getTestingTypeReference(){return Ht.typeReference({name:"T",importPath:"testing"})}getNewStringsReaderFunctionInvocation(t){return Ht.invokeFunc({func:Ht.typeReference({name:"NewReader",importPath:"strings"}),arguments_:[Ht.TypeInstantiation.string(t)]})}getClientConstructorName(){return this.customConfig?.clientConstructorName!=null?this.customConfig.clientConstructorName:this.customConfig?.exportedClientName!=null?`New${this.customConfig.exportedClientName}`:`New${this.getClientName()}`}getClientName(){return this.customConfig?.clientName!=null?this.customConfig.clientName:"Client"}getClientImportPath(){return`${this.rootImportPath}/client`}getOptionImportPath(){return`${this.rootImportPath}/option`}getGoTypeReferenceFromDeclaration({declaration:t}){return Ht.typeReference({name:t.name.pascalCase.unsafeName,importPath:this.getImportPath(t.fernFilepath)})}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return this.getEnvironmentTypeReference(r)}getEnvironmentTypeReference(t){return Ht.typeReference({name:`Environments.${this.getTypeName(t)}`,importPath:this.rootImportPath})}static chainMethods(t,...r){if(r.length===0)throw new Error("Must have methods to chain");let n=t;for(let i of r)n=Ht.invokeMethod({on:n,method:i.method,arguments_:i.arguments_,multiline:i.multiline});return n}};St();var dYu="example",lmo="fern",IPm="do",_Lt="client",oWC=Ht.TypeInstantiation,wPm="WireMockBaseURL",CPm="WireMockClient",cMn=class{context;formatter;constructor({context:t,formatter:r}){this.context=t,this.formatter=r}async generateSnippet({endpoint:t,request:r,options:n}){return n?.config?.outputWiremockTests??!1?this.generateWiremockTest({endpoint:t,snippet:r}):await this.buildCodeBlock({endpoint:t,snippet:r}).toStringAsync({packageName:dYu,importPath:lmo,rootImportPath:this.context.rootImportPath,customConfig:this.context.customConfig??{},formatter:this.formatter})}generateSnippetSync({endpoint:t,request:r,options:n}){return n?.config?.outputWiremockTests??!1?this.generateWiremockTest({endpoint:t,snippet:r}):this.buildCodeBlock({endpoint:t,snippet:r}).toString({packageName:dYu,importPath:lmo,rootImportPath:this.context.rootImportPath,customConfig:this.context.customConfig??{},formatter:this.formatter})}async generateSnippetAst({endpoint:t,request:r,options:n}){throw new Error("Unsupported")}generateWiremockTest({endpoint:t,snippet:r}){return this.buildWiremockTestCodeBlock({endpoint:t,snippet:r}).toString({packageName:"wiremock",importPath:lmo,rootImportPath:this.context.rootImportPath,customConfig:this.context.customConfig??{},formatter:this.formatter})}buildCodeBlock({endpoint:t,snippet:r}){return Ht.codeblock(n=>{n.writeNode(Ht.func({name:IPm,parameters:[],return_:[],body:Ht.codeblock(i=>{i.writeNode(this.constructClient({endpoint:t,snippet:r})),i.writeLine(),i.writeNode(this.callMethod({endpoint:t,snippet:r}))})})),n.writeNewLineIfLastLineNot()})}buildWiremockTestCodeBlock({endpoint:t,snippet:r}){return Ht.codeblock(n=>{n.writeNode(Ht.func({name:"Test"+this.context.getTestMethodName(t)+"WithWireMock",parameters:[Ht.parameter({name:"t",type:Ht.Type.pointer(Ht.Type.reference(this.context.getTestingTypeReference()))})],return_:[],body:Ht.codeblock(i=>{for(let o of this.buildWiremockTestSetup({endpoint:t}))i.writeNode(o),i.writeLine();i.writeLine(),i.writeNode(this.constructWiremockTestClient({endpoint:t,snippet:r})),i.writeLine(),i.writeNode(this.callClientMethodAndAssert({endpoint:t,snippet:r,includeTestIdHeader:!0}))})})),n.writeNewLineIfLastLineNot()})}constructClient({endpoint:t,snippet:r}){return Ht.codeblock(n=>{n.write(`${_Lt} := `),n.writeNode(this.getRootClientFuncInvocation(this.getConstructorArgs({endpoint:t,snippet:r})))})}constructWiremockTestClient({endpoint:t,snippet:r}){return Ht.codeblock(n=>{n.write(`${_Lt} := `),n.writeNode(this.getRootClientFuncInvocation(this.getWiremockTestConstructorArgs()))})}writeMethodInvocation({writer:t,endpoint:r,snippet:n,includeTestIdHeader:i}){let{otherArgs:o,requestArg:s}=this.getMethodArgs({endpoint:r,snippet:n}),a=i?[Ht.codeblock(u=>{u.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"WithHTTPHeader",importPath:this.context.getOptionImportPath()}),arguments_:[Ht.codeblock('http.Header{"X-Test-Id": []string{"TEST-ID-PLACEHOLDER"}}')]}))})]:[];if(s!=null)if(s instanceof Ht.TypeInstantiation&&Ht.TypeInstantiation.isNop(s))t.writeNode(Ht.invokeMethod({on:Ht.codeblock(_Lt),method:this.getMethod({endpoint:r}),arguments_:[this.context.getContextTodoFunctionInvocation(),...o,Ht.codeblock("nil"),...a]}));else{t.write("request := "),t.writeNode(s),t.writeLine();let u=Ht.codeblock("request");t.writeNode(Ht.invokeMethod({on:Ht.codeblock(_Lt),method:this.getMethod({endpoint:r}),arguments_:[this.context.getContextTodoFunctionInvocation(),...o,u,...a]}))}else t.writeNode(Ht.invokeMethod({on:Ht.codeblock(_Lt),method:this.getMethod({endpoint:r}),arguments_:[this.context.getContextTodoFunctionInvocation(),...o,...a]}))}callMethod({endpoint:t,snippet:r}){return Ht.codeblock(n=>{this.writeMethodInvocation({writer:n,endpoint:t,snippet:r})})}getConstructorArgs({endpoint:t,snippet:r}){let n=[],i=this.getConstructorBaseUrlArg({baseUrl:r.baseURL,environment:r.environment});return i!=null&&n.push(i),t.auth!=null&&(r.auth!=null?n.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Ir.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`})),this.context.errors.scope(Lo.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),n}getWiremockTestConstructorArgs(){return[Ht.codeblock(t=>{t.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"WithBaseURL",importPath:this.context.getOptionImportPath()}),arguments_:[Ht.codeblock(wPm)]}))})]}getConstructorAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?[this.getConstructorBasicAuthArg({auth:t,values:r})]:[];case"bearer":return r.type==="bearer"?[this.getConstructorBearerAuthArg({auth:t,values:r})]:[];case"header":return r.type==="header"?[this.getConstructorHeaderAuthArg({auth:t,values:r})]:[];case"oauth":return r.type==="oauth"?[this.getConstructorOAuthAuthArg({values:r})]:[];case"inferred":return r.type==="inferred"?this.getConstructorInferredAuthArgs({auth:t,values:r}):[];default:Be(t)}}addError(t){this.context.errors.add({severity:Ir.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:r}){return Ht.codeblock(n=>{n.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"WithBasicAuth",importPath:this.context.getOptionImportPath()}),arguments_:[Ht.TypeInstantiation.string(r.username),Ht.TypeInstantiation.string(r.password)]}))})}getConstructorBaseUrlArg({baseUrl:t,environment:r}){let n=this.getBaseUrlArg({baseUrl:t,environment:r});if(n!=null)return Ht.codeblock(i=>{i.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"WithBaseURL",importPath:this.context.getOptionImportPath()}),arguments_:[n]}))})}getBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null)return Ht.TypeInstantiation.string(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);if(n==null){this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return Ht.TypeInstantiation.reference(n)}this.context.isMultiEnvironmentValues(r)&&this.context.errors.add({severity:Ir.Warning,message:"The Go SDK doesn't support a multi-environment client option yet; use the baseUrl option instead"})}}getConstructorBearerAuthArg({auth:t,values:r}){return Ht.codeblock(n=>{n.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:`With${t.token.pascalCase.unsafeName}`,importPath:this.context.getOptionImportPath()}),arguments_:[Ht.TypeInstantiation.string(r.token)]}))})}getConstructorHeaderAuthArg({auth:t,values:r}){return Ht.codeblock(n=>{n.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:`With${t.header.name.name.pascalCase.unsafeName}`,importPath:this.context.getOptionImportPath()}),arguments_:[this.context.dynamicTypeInstantiationMapper.convert({typeReference:t.header.typeReference,value:r.value})]}))})}getConstructorOAuthAuthArg({values:t}){return Ht.codeblock(r=>{r.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"WithClientCredentials",importPath:this.context.getOptionImportPath()}),arguments_:[Ht.TypeInstantiation.string(t.clientId),Ht.TypeInstantiation.string(t.clientSecret)]}))})}getConstructorInferredAuthArgs({auth:t,values:r}){let n=t.parameters;if(n==null||n.length===0)return[];let i=[];for(let o of n){if(o.typeReference.type==="optional"||o.typeReference.type==="literal")continue;let s=o.name.wireValue,a=r.values?.[s]??o.name.name.originalName,u=this.context.dynamicTypeInstantiationMapper.convert({typeReference:o.typeReference,value:a});Ht.TypeInstantiation.isNop(u)||i.push(Ht.codeblock(c=>{c.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:`With${o.name.name.pascalCase.unsafeName}`,importPath:this.context.getOptionImportPath()}),arguments_:[u]}))}))}return i}getConstructorHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getConstructorHeaderArg({header:i,value:o});s!=null&&n.push(s)}return n}getConstructorHeaderArg({header:t,value:r}){let n=this.context.dynamicTypeInstantiationMapper.convert({typeReference:t.typeReference,value:r});if(!Ht.TypeInstantiation.isNop(n))return Ht.codeblock(i=>{i.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:`With${t.name.name.pascalCase.unsafeName}`,importPath:this.context.getOptionImportPath()}),arguments_:[n]}))})}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];i.length>0&&n.push(...this.getPathParameters({namedParameters:i,snippet:r}).map(s=>s.value)),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let o=t.body!=null?this.getBodyRequestArg({body:t.body,value:r.requestBody}):void 0;return this.context.errors.unscope(),{otherArgs:n,requestArg:o}}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeInstantiationMapper.convertToPointerIfPossible({typeReference:t.value,value:r});default:Be(t)}}getBytesBodyRequestArg({value:t}){let r=typeof t=="string"?t:"";return Ht.TypeInstantiation.reference(Ht.invokeFunc({func:Ht.typeReference({name:"NewReader",importPath:"bytes"}),arguments_:[Ht.TypeInstantiation.bytes(r)]}))}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[],{inlinePathParameters:i,inlineFileProperties:o}={inlinePathParameters:this.context.customConfig?.inlinePathParameters??!0,inlineFileProperties:this.context.customConfig?.inlineFileProperties??!0};this.context.errors.scope(Lo.PathParameters);let s=[],a=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];a.length>0&&s.push(...this.getPathParameters({namedParameters:a,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let u=this.getFilePropertyInfo({request:t,snippet:r});this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})||n.push(...s.map(l=>l.value)),o||n.push(...u.fileFields.map(l=>l.value));let c=this.context.needsRequestParameter({request:t,inlinePathParameters:i,inlineFileProperties:o})?this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})?s:[],filePropertyInfo:u}):void 0;return{otherArgs:n,requestArg:c}}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Lo.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(l=>({name:l.name.name.pascalCase.unsafeName,value:this.context.dynamicTypeInstantiationMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.Headers);let u=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(l=>({name:l.name.name.pascalCase.unsafeName,value:this.context.dynamicTypeInstantiationMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let c=t.body!=null?this.getInlinedRequestBodyStructFields({body:t.body,value:r.requestBody,filePropertyInfo:i}):[];return this.context.errors.unscope(),Ht.TypeInstantiation.structPointer({typeReference:Ht.typeReference({name:this.context.getMethodName(t.declaration.name),importPath:this.context.getImportPathForRequest(t.declaration.fernFilepath)}),fields:[...n,...s,...u,...c]})}getInlinedRequestBodyStructFields({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyStructFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyStructField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyStructFields({filePropertyInfo:n});default:Be(t)}}getFileUploadRequestBodyStructFields({filePropertyInfo:t}){return this.context.customConfig?.inlineFileProperties??!0?[...t.fileFields,...t.bodyPropertyFields]:t.bodyPropertyFields}getReferencedRequestBodyPropertyStructField({body:t,value:r}){return{name:this.context.getTypeName(t.bodyKey),value:this.getReferencedRequestBodyPropertyTypeInstantiation({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyTypeInstantiation({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeInstantiationMapper.convert({typeReference:t.value,value:r});default:Be(t)}}getInlinedRequestBodyPropertyStructFields({parameters:t,value:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}});for(let o of i)n.push({name:this.context.getFieldName(o.name.name),value:this.context.dynamicTypeInstantiationMapper.convert(o)});return n}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValueOrDefault({parameters:t,values:r.pathParameters??{}});for(let o of i)n.push({name:this.context.getTypeName(o.name.name),value:this.context.dynamicTypeInstantiationMapper.convertToPointerIfPossible(o)});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getMethodName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getRootClientFuncInvocation(t){return Ht.invokeFunc({func:Ht.typeReference({name:this.context.getClientConstructorName(),importPath:this.context.getClientImportPath()}),arguments_:t})}buildWiremockTestSetup({endpoint:t,errorCase:r}){let n="stub";return[]}callClientMethodAndAssert({endpoint:t,snippet:r,includeTestIdHeader:n}){return Ht.codeblock(i=>{this.writeMethodInvocation({writer:i,endpoint:t,snippet:r,includeTestIdHeader:!0}),i.writeLine(),i.writeLine(),i.write("ok, countErr := "),i.writeNode(Ht.invokeMethod({on:Ht.codeblock(CPm),method:"Verify",arguments_:[Ht.invokeMethod({on:Ht.codeblock("stub"),method:"Request",arguments_:[],multiline:!1}),Ht.codeblock("1")],multiline:!1})),i.writeLine(),i.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"NoError",importPath:"github.com/stretchr/testify/require"}),arguments_:[Ht.codeblock("t"),Ht.codeblock("countErr"),Ht.TypeInstantiation.string("Failed to verify WireMock request was matched")],multiline:!1})),i.writeLine(),i.writeNode(Ht.invokeFunc({func:Ht.typeReference({name:"True",importPath:"github.com/stretchr/testify/require"}),arguments_:[Ht.codeblock("t"),Ht.codeblock("ok"),Ht.TypeInstantiation.string("WireMock request was not matched")],multiline:!1})),i.writeLine()})}};var SLt=class extends Wv{formatter;constructor({ir:t,config:r,formatter:n}){super(new uMn({ir:t,config:r})),this.formatter=n}async generate(t,r){return super.generate(t,r)}generateSync(t,r){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new cMn({context:t,formatter:this.formatter})}};var pMn=require("fs/promises"),mYu=Ae(require("path"),1);var lMn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new SLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");for(let[n,{endpointId:i,request:o}]of r.entries())try{let s=pS(o);if(s==null)continue;let a=await this.dynamicSnippetsGenerator.generate(s,{endpointId:i}),u=this.getTestFilePath({outputDir:t,idx:n});await(0,pMn.mkdir)(mYu.default.dirname(u),{recursive:!0}),await(0,pMn.writeFile)(u,a.snippet)}catch(s){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(o.endpoint)}: ${s}`),s instanceof Error&&s.stack&&this.context.logger.error(s.stack)}this.context.logger.debug("Done generating dynamic snippet tests")}getTestFilePath({outputDir:t,idx:r}){return Ge(t,Se.of(`dynamic-snippets/example${r}/snippet.go`))}};qt();St();var vMe=class extends wC{packageName;customConfig;formatter;imports=new Set;constructor({packageName:t,customConfig:r,formatter:n}){super(),this.packageName=t,this.customConfig=r,this.formatter=n??new B7}addImport(t){this.imports.add(t)}getImports(){return new Set(this.imports)}};var BLt=class extends vMe{constructor({packageName:t,customConfig:r,formatter:n}){super({packageName:t,customConfig:r,formatter:n})}async toStringAsync(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.format(t)}catch(r){throw new Error(`Failed to format Java file: ${r}
2521
2521
  ${t}`)}return t}toString(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.formatSync(t)}catch(r){throw new Error(`Failed to format Java file: ${r}
2522
2522
  ${t}`)}return t}getContent(){let t=`package ${this.packageName};
2523
2523
 
@@ -2530,7 +2530,7 @@ Value: ${JSON.stringify(r)}
2530
2530
  Attempted ${n.length} variants:
2531
2531
  ${s}
2532
2532
 
2533
- This prevents invalid snippet code generation that would cause formatter errors.`)}getUndiscriminatedUnionFieldName({typeReference:t}){switch(t.type){case"list":return this.getUndiscriminatedUnionFieldNameForList({list:t});case"literal":return this.getUndiscriminatedUnionFieldNameForLiteral({literal:t.value});case"map":return this.getUndiscriminatedUnionFieldNameForMap({map:t});case"named":{let r=this.context.resolveNamedType({typeId:t.value});return r==null?void 0:this.context.getClassName(r.declaration.name)}case"optional":return this.getUndiscriminatedUnionFieldNameForOptional({typeReference:t});case"nullable":return this.getUndiscriminatedUnionFieldNameForNullable({typeReference:t});case"primitive":return this.getUndiscriminatedUnionFieldNameForPrimitive({primitive:t.value});case"set":return this.getUndiscriminatedUnionFieldNameForSet({set:t});case"unknown":return"Unknown";default:Be(t)}}getUndiscriminatedUnionFieldNameForList({list:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`ListOf${r}`}getUndiscriminatedUnionFieldNameForMap({map:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t.key});if(r==null)return;let n=this.getUndiscriminatedUnionFieldName({typeReference:t.value});if(n!=null)return`MapOf${r}To${n}`}getUndiscriminatedUnionFieldNameForOptional({typeReference:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`Optional${r}`}getUndiscriminatedUnionFieldNameForNullable({typeReference:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`Nullable${r}`}getUndiscriminatedUnionFieldNameForSet({set:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`SetOf${r}`}getUndiscriminatedUnionFieldNameForLiteral({literal:t}){}getUndiscriminatedUnionFieldNameForPrimitive({primitive:t}){switch(t){case"INTEGER":case"UINT":return"Integer";case"LONG":case"UINT_64":return"Long";case"FLOAT":return"Float";case"DOUBLE":return"Double";case"BOOLEAN":return"Boolean";case"BIG_INTEGER":return"BigInteger";case"STRING":return"String";case"UUID":return"Uuid";case"DATE":return"Date";case"DATE_TIME":return"DateTime";case"BASE_64":return"Base64";default:{if(t==="DATE_TIME_RFC_2822")return"DateTimeRfc2822";Be(t)}}}convertUnknown({value:t}){return this.context.customConfig?.["generate-unknown-as-json-node"]===!0?this.convertToJsonNode({value:t}):Kt.TypeLiteral.unknown(t)}convertToJsonNode({value:t}){let r=Kt.classReference({name:"ObjectMappers",packageName:this.context.getCorePackageName()});return typeof t=="string"?Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[Kt.TypeLiteral.string(t)]})):typeof t=="number"?Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[Kt.TypeLiteral.integer(t)]})):typeof t=="boolean"?Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[Kt.TypeLiteral.boolean(t)]})):t===null?Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[Kt.TypeLiteral.raw(Kt.codeblock("null"))]})):Array.isArray(t)?Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[Kt.TypeLiteral.list({valueType:Kt.Type.object(),values:t.map(n=>Kt.TypeLiteral.unknown(n)),isParameter:!0})]})):typeof t=="object"&&t!==null?Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[Kt.TypeLiteral.unknown(t)]})):Kt.TypeLiteral.unknown(t)}convertPrimitive({primitive:t,value:r,as:n}){switch(t){case"INTEGER":case"UINT":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.integer(i)}case"LONG":case"UINT_64":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.long(i)}case"FLOAT":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.float(i)}case"DOUBLE":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.double(i)}case"BOOLEAN":{let i=this.getValueAsBoolean({value:r,as:n});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.boolean(i)}case"STRING":{let i=this.context.getValueAsString({value:r});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.string(i)}case"DATE":{let i=this.context.getValueAsString({value:r});return i==null?Kt.TypeLiteral.nop():this.context.customConfig?.["use-local-date-for-dates"]===!0?Kt.TypeLiteral.date(i):Kt.TypeLiteral.string(i)}case"DATE_TIME":{let i=this.context.getValueAsString({value:r});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.dateTime(i)}case"UUID":{let i=this.context.getValueAsString({value:r});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.uuid(i)}case"BASE_64":{let i=this.context.getValueAsString({value:r});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.bytes(i)}case"BIG_INTEGER":{let i=this.context.getValueAsString({value:r});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.bigInteger(i)}default:{if(t==="DATE_TIME_RFC_2822"){let o=this.context.getValueAsString({value:r});return o==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.dateTime(o)}Be(t)}}}getValueAsNumber({value:t,as:r}){let n=r==="mapKey"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="mapKey"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:n})}};St();var gMn=class{context;constructor({context:t}){this.context=t}convert(t){switch(t.typeReference.type){case"list":return Kt.Type.list(this.convert({typeReference:t.typeReference}));case"literal":return this.convertLiteral({literal:t.typeReference.value});case"map":return Kt.Type.map(this.convert({typeReference:t.typeReference.key}),this.convert({typeReference:t.typeReference.value}));case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.convertUnknown():this.convertNamed({named:r})}case"optional":case"nullable":return Kt.Type.optional(this.convert({typeReference:t.typeReference.value}));case"primitive":return this.convertPrimitive({primitive:t.typeReference.value});case"set":return Kt.Type.set(this.convert({typeReference:t.typeReference}));case"unknown":return this.convertUnknown();default:Be(t.typeReference)}}convertNamed({named:t}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference});case"enum":case"discriminatedUnion":case"object":case"undiscriminatedUnion":return Kt.Type.reference(Kt.classReference({name:this.context.getClassName(t.declaration.name),packageName:this.context.getTypesPackageName(t.declaration.fernFilepath)}));default:Be(t)}}convertLiteral({literal:t}){switch(t.type){case"boolean":return Kt.Type.boolean();case"string":return Kt.Type.string()}}convertUnknown(){return this.context.customConfig?.["generate-unknown-as-json-node"]===!0?Kt.Type.reference(Kt.classReference({name:"JsonNode",packageName:"com.fasterxml.jackson.databind"})):Kt.Type.object()}convertPrimitive({primitive:t}){switch(t){case"INTEGER":return Kt.Type.integer();case"UINT":return Kt.Type.integer();case"LONG":return Kt.Type.long();case"UINT_64":return Kt.Type.long();case"FLOAT":return Kt.Type.float();case"DOUBLE":return Kt.Type.double();case"BOOLEAN":return Kt.Type.boolean();case"STRING":return Kt.Type.string();case"DATE":return Kt.Type.date();case"DATE_TIME":return Kt.Type.dateTime();case"UUID":return Kt.Type.uuid();case"BASE_64":return Kt.Type.bytes();case"BIG_INTEGER":return Kt.Type.bigInteger();default:{if(t==="DATE_TIME_RFC_2822")return Kt.Type.dateTime();Be(t)}}}};St();var AMn=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({body:t,value:r}){let n={fileFields:[],bodyPropertyFields:[]},i=this.context.getRecord(r)??{};for(let o of t.properties)switch(o.type){case"file":n.fileFields.push({name:this.context.getMethodName(o.name),value:this.getSingleFileProperty({property:o,record:i})});break;case"fileArray":n.fileFields.push({name:this.context.getMethodName(o.name),value:this.getArrayFileProperty({property:o,record:i})});break;case"bodyProperty":n.bodyPropertyFields.push({name:this.context.getMethodName(o.name.name),value:this.getBodyProperty({property:o,record:i})});break;default:Be(o)}return n}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r});return n==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.reference(this.context.getFileStreamFromString(n))}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});if(n==null)return Kt.TypeLiteral.nop();for(let i of n)return Kt.TypeLiteral.reference(this.context.getFileStreamFromString(i));return Kt.TypeLiteral.nop()}getBodyProperty({property:t,record:r}){let n=r[t.name.wireValue];return n==null?Kt.TypeLiteral.nop():this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:n})}};var YPm=new Set(["enum","extends","package","void","short","class","abstract","return","import","for","assert","switch"]),XPm=new Set(["getClass","notify","notifyAll","wait"]),yMn=class e extends $v{ir;customConfig;dynamicTypeMapper;dynamicTypeLiteralMapper;filePropertyMapper;constructor({ir:t,config:r,options:n}){super({ir:t,config:r,options:n}),this.ir=t,this.customConfig=pmo.parse(r.customConfig??{}),this.dynamicTypeMapper=new gMn({context:this}),this.dynamicTypeLiteralMapper=new hMn({context:this}),this.filePropertyMapper=new AMn({context:this})}clone(){return new e({ir:this.ir,config:this.config,options:this.options})}getClassName(t){return this.getName(t.pascalCase.safeName)}getEnumName(t){return this.getName(t.screamingSnakeCase.safeName)}getPropertyName(t){return this.getName(t.camelCase.safeName)}getMethodName(t){let r=t.camelCase.safeName;return this.isReservedMethodName(r)?r+"_":this.getName(r)}getRootClientClassReference(){return Kt.classReference({name:this.getRootClientClassName(),packageName:this.getRootPackageName()})}getRootClientClassName(){return this.customConfig?.["client-class-name"]??`${this.getBaseNamePrefix()}Client`}getEnvironmentClassName(){return"Environment"}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return Kt.codeblock(n=>{n.writeNode(this.getEnvironmentClassReference()),n.write("."),n.write(this.getEnumName(r))})}getEnvironmentClassReference(){return Kt.classReference({name:this.getEnvironmentClassName(),packageName:this.getCorePackageName()})}getJavaClassReferenceFromDeclaration({declaration:t}){return Kt.classReference({name:t.name.pascalCase.unsafeName,packageName:this.getTypesPackageName(t.fernFilepath)})}getNullableClassReference(){return Kt.classReference({name:"Nullable",packageName:this.getCorePackageName()})}getNullableOfNull(){return Kt.TypeLiteral.reference(Kt.invokeMethod({on:this.getNullableClassReference(),method:"ofNull",arguments_:[]}))}getOptionalNullableClassReference(){return Kt.classReference({name:"OptionalNullable",packageName:this.getCorePackageName()})}getOptionalNullableAbsent(){return Kt.TypeLiteral.reference(Kt.invokeMethod({on:this.getOptionalNullableClassReference(),method:"absent",arguments_:[]}))}getOptionalNullableOf(t){return Kt.TypeLiteral.reference(Kt.invokeMethod({on:this.getOptionalNullableClassReference(),method:"of",arguments_:[t]}))}getFileStreamFromString(t){return Kt.TypeLiteral.reference(Kt.codeblock(r=>{r.write("new "),r.writeNode(this.getFileStreamClassReference()),r.write("("),r.writeNode(this.getByteArrayInputStreamClassReference()),r.write("("),r.writeNode(Kt.TypeLiteral.string(t)),r.write(".getBytes("),r.writeNode(this.getStandardCharsetsClassReference()),r.write(".UTF_8)))")}))}getFileStreamClassReference(){return Kt.classReference({name:"FileStream",packageName:this.getCorePackageName()})}getByteArrayInputStreamClassReference(){return Kt.classReference({name:"ByteArrayInputStream",packageName:"java.io"})}getStandardCharsetsClassReference(){return Kt.classReference({name:"StandardCharsets",packageName:"java.nio.charset"})}isPrimitive(t){switch(t.type){case"primitive":return!0;case"optional":case"nullable":return this.isPrimitive(t.value);case"named":{let r=this.resolveNamedType({typeId:t.value});if(r==null)return!1;switch(r.type){case"alias":return this.isPrimitive(r.typeReference);case"discriminatedUnion":case"undiscriminatedUnion":case"object":case"enum":return!1;default:Be(r)}break}case"list":case"set":case"map":case"literal":case"unknown":return!1;default:Be(t)}}isDirectLiteral(t){return t.type==="literal"}sortTypeInstancesByRequiredFirst(t,r){let n=new Map;r.forEach((s,a)=>{n.set(s.name.wireValue,a)});let i=[],o=[];for(let s of t)this.isOptional(s.typeReference)?o.push(s):i.push(s);return i.sort((s,a)=>(n.get(s.name.wireValue)??0)-(n.get(a.name.wireValue)??0)),[...i,...o]}associateByWireValue({parameters:t,values:r,ignoreMissingParameters:n}){let i=super.associateByWireValue({parameters:t,values:r,ignoreMissingParameters:n}),o=new Map;for(let a of i)o.set(a.name.wireValue,a);let s=[];for(let a of t){let u=o.get(a.name.wireValue);u!=null&&s.push(u)}return s}getRootPackageName(){let t=this.getPackagePrefixTokens();return this.joinPackageTokens(t)}getCorePackageName(){let t=this.getPackagePrefixTokens();return t.push("core"),this.joinPackageTokens(t)}getTypesPackageName(t){return this.getResourcesPackage(t,"types")}getRequestsPackageName(t){return this.getPackageLayout()==="flat"?this.getTypesPackageName(t):this.getResourcesPackage(t,"requests")}getResourcesPackage(t,r){let n=this.getPackagePrefixTokens();return this.getPackageLayout()==="flat"?t!=null&&n.push(...t.packagePath.map(i=>this.getPackageNameSegment(i))):(t!=null&&t.allParts.length>0&&n.push("resources"),t!=null&&n.push(...t.allParts.map(i=>this.getPackageNameSegment(i)))),r!=null&&n.push(r),this.joinPackageTokens(n)}getPackageName(t,r){let n=this.getPackageNameSegments(t);return n=r!=null?[...n,r]:n,[...this.getPackagePrefixTokens(),...n].join(".")}getPackageLayout(){return this.customConfig?.["package-layout"]??"nested"}shouldInlinePathParameters(){return this.customConfig?.["inline-path-parameters"]??!1}shouldInlineFileProperties(){return this.customConfig?.["inline-file-properties"]??!1}getPackageNameSegments(t){return t.packagePath.map(r=>this.getPackageNameSegment(r))}getPackageNameSegment(t){return t.camelCase.safeName.toLowerCase()}getPackagePrefixTokens(){if(this.customConfig?.["package-prefix"]!=null)return this.customConfig["package-prefix"].split(".");let t=[];return t.push("com"),t.push(...this.splitOnNonAlphaNumericChar(this.config.organization)),t.push(...this.splitOnNonAlphaNumericChar(this.getApiName())),t}getBaseNamePrefix(){return this.convertKebabCaseToUpperCamelCase(this.config.organization)+this.convertKebabCaseToUpperCamelCase(this.getApiName())}getApiName(){return qn(this.config.workspaceName)}startsWithNumber(t){return/^\d/.test(t)}splitOnNonAlphaNumericChar(t){return t.split(/[^a-zA-Z0-9]/)}convertKebabCaseToUpperCamelCase(t){return t.replace(/-([a-z])/g,(r,n)=>n.toUpperCase()).replace(/^[a-z]/,r=>r.toUpperCase())}joinPackageTokens(t){return t.map(n=>this.startsWithNumber(n)?"_"+n:n).join(".")}getName(t){return this.isReservedName(t)?"_"+t:t}isReservedName(t){return YPm.has(t)}isReservedMethodName(t){return XPm.has(t)}};St();var AYu="com.example.usage",ZPm="Example",eDm="main",tDm="args",yYu="client",rDm={type:"primitive",value:"STRING"};function nDm(e){if(e.type==="optional"&&e.value.type==="list"){let r=e.value.value;if(r.type==="optional")return{type:"optional",value:{type:"list",value:r.value}}}if(e.type==="list"){let t=e.value;if(t.type==="optional")return{type:"list",value:t.value}}return e}var bMn=class{context;formatter;constructor({context:t,formatter:r}){this.context=t,this.formatter=r}async generateSnippet({endpoint:t,request:r,options:n}){let i=this.getConfig(n);return await this.buildCodeBlock({endpoint:t,snippet:r,options:n}).toStringAsync({packageName:i.fullStylePackageName??AYu,customConfig:this.context.customConfig,formatter:this.formatter})}generateSnippetSync({endpoint:t,request:r,options:n}){let i=this.getConfig(n);return this.buildCodeBlock({endpoint:t,snippet:r,options:n}).toString({packageName:i.fullStylePackageName??AYu,customConfig:this.context.customConfig,formatter:this.formatter})}async generateSnippetAst({endpoint:t,request:r,options:n}){throw new Error("Unsupported")}buildCodeBlock({endpoint:t,snippet:r,options:n}){let i=Kt.codeblock(s=>{s.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),s.newLine(),s.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))}),o=this.getStyle(n);switch(o){case CC.Concise:return i;case CC.Full:return this.buildFullCodeBlock({body:i,options:n});default:Be(o)}}constructClient({endpoint:t,snippet:r}){let n=t.auth?.type==="oauth";return Kt.codeblock(i=>{if(i.writeNode(this.context.getRootClientClassReference()),i.write(` ${yYu} = `),n&&r.auth?.type==="oauth"){let o=r.auth;i.writeNode(this.context.getRootClientClassReference()),i.write(`.withCredentials("${o.clientId}", "${o.clientSecret}")`),i.writeNewLineIfLastLineNot(),i.indent();let s=this.getRootClientBuilderArgsExcludingAuth({endpoint:t,snippet:r});for(let a of s)i.write(`.${a.name}(`),a.value.shouldWriteInLine()||i.newLine(),i.writeNode(a.value),a.value.shouldWriteInLine()||i.newLine(),i.writeLine(")");i.writeLine(".build()"),i.dedent()}else i.writeNode(Kt.TypeLiteral.builder({classReference:this.context.getRootClientClassReference(),parameters:this.getRootClientBuilderArgs({endpoint:t,snippet:r})}))})}getRootClientBuilderArgsExcludingAuth({endpoint:t,snippet:r}){let n=[],i=this.getRootClientBaseUrlArg({baseUrl:r.baseURL,environment:r.environment});i!=null&&n.push(i),this.context.errors.scope(Lo.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope();let o=new Set;if([...this.context.ir.pathParameters??[],...t.request.pathParameters??[]].forEach(a=>{a.variable!=null&&o.add(a.variable)}),this.context.ir.variables!=null&&this.context.ir.variables.length>0){for(let a of this.context.ir.variables)if(o.has(a.id)){let u=a.name.camelCase.unsafeName;n.push({name:u,value:Kt.TypeLiteral.string(`YOUR_${a.name.screamingSnakeCase.unsafeName}`)})}}if(this.context.errors.scope(Lo.PathParameters),this.context.ir.pathParameters!=null&&this.context.ir.pathParameters.length>0){let a=this.context.ir.pathParameters.filter(u=>u.variable==null);a.length>0&&n.push(...this.getPathParameters({namedParameters:a,snippet:r}))}return this.context.errors.unscope(),n}buildFullCodeBlock({body:t,options:r}){let n=this.getConfig(r),i=Kt.class_({name:n.fullStyleClassName??ZPm,access:Kt.Access.Public}),o=Kt.parameter({name:tDm,type:Kt.Type.array(Kt.Type.string())});return i.addMethod(Kt.method({name:eDm,access:Kt.Access.Public,static_:!0,parameters:[o],body:t})),i}getRootClientBuilderArgs({endpoint:t,snippet:r}){let n=[];t.auth!=null&&(r.auth!=null?n.push(...this.getRootClientAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Ir.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`}));let i=this.getRootClientBaseUrlArg({baseUrl:r.baseURL,environment:r.environment});i!=null&&n.push(i),this.context.errors.scope(Lo.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope();let o=new Set;if([...this.context.ir.pathParameters??[],...t.request.pathParameters??[]].forEach(a=>{a.variable!=null&&o.add(a.variable)}),this.context.ir.variables!=null&&this.context.ir.variables.length>0){for(let a of this.context.ir.variables)if(o.has(a.id)){let u=a.name.camelCase.unsafeName;n.push({name:u,value:Kt.TypeLiteral.string(`YOUR_${a.name.screamingSnakeCase.unsafeName}`)})}}if(this.context.errors.scope(Lo.PathParameters),this.context.ir.pathParameters!=null&&this.context.ir.pathParameters.length>0){let a=this.context.ir.pathParameters.filter(u=>u.variable==null);a.length>0&&n.push(...this.getPathParameters({namedParameters:a,snippet:r}))}return this.context.errors.unscope(),n}getRootClientBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null){if(this.context.ir.environments?.environments.type==="multipleBaseUrls"){this.context.errors.add({severity:Ir.Critical,message:"The Java SDK doesn't support a baseUrl when multiple URL environments are configured"});return}return{name:"url",value:Kt.TypeLiteral.string(t)}}if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);if(n==null){this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return{name:"environment",value:Kt.TypeLiteral.reference(n)}}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?{name:"environment",value:Kt.TypeLiteral.reference(Kt.instantiateClass({classReference:this.context.getEnvironmentClassReference(),arguments_:Object.values(r).map(n=>this.context.dynamicTypeLiteralMapper.convert({typeReference:rDm,value:n}))}))}:void 0}}getRootClientAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?this.getRootClientBasicAuthArgs({auth:t,values:r}):[];case"bearer":return r.type==="bearer"?this.getRootClientBearerAuthArgs({auth:t,values:r}):[];case"header":return r.type==="header"?this.getRootClientHeaderAuthArgs({auth:t,values:r}):[];case"oauth":return r.type==="oauth"?this.getRootClientOAuthArgs({auth:t,values:r}):[];case"inferred":return this.addWarning("The Java SDK Generator does not support Inferred auth scheme yet"),[];default:Be(t)}}addError(t){this.context.errors.add({severity:Ir.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getRootClientBasicAuthArgs({auth:t,values:r}){return[{name:"credentials",value:Kt.TypeLiteral.raw(`"${r.username}", "${r.password}"`)}]}getRootClientBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getMethodName(t.token),value:Kt.TypeLiteral.string(r.token)}]}getRootClientHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getMethodName(t.header.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value})}]}getRootClientOAuthArgs({auth:t,values:r}){return[{name:this.context.getMethodName(t.clientId),value:Kt.TypeLiteral.string(r.clientId)},{name:this.context.getMethodName(t.clientSecret),value:Kt.TypeLiteral.string(r.clientSecret)}]}getRootClientHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getRootClientHeaderArg({header:i,value:o});s!=null&&n.push({name:this.context.getMethodName(i.name.name),value:s})}return n}getRootClientHeaderArg({header:t,value:r}){let n=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:r});if(!Kt.TypeLiteral.isNop(n))return n}callMethod({endpoint:t,snippet:r}){return Kt.invokeMethod({on:Kt.codeblock(yYu),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:r})})}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=(t.pathParameters??[]).filter(s=>s.variable==null);i.length>0&&n.push(...this.getPathParameters({namedParameters:i,snippet:r}).map(s=>s.value)),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),t.body!=null&&n.push(this.getBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope();let o=this.getRequestOptionsArg({request:t,snippet:r});return o!=null&&n.push(o),n}usesOptionalNullable(){return this.context.customConfig?.["collapse-optional-nullable"]===!0}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":{if(t.value.type==="optional"){let n=this.usesOptionalNullable()&&(t.value.value.type==="optional"||t.value.value.type==="nullable");if(r==null)return n?this.context.getOptionalNullableAbsent():Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.classReference({name:"Optional",packageName:"java.util"}),method:"empty",arguments_:[]}));let i=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value.value,value:r,as:"request",isCollapsedOptionalNullable:n}),o=i.toString({packageName:"com.example",customConfig:this.context.customConfig});return o.includes("Optional.empty()")||o.includes("OptionalNullable.absent()")?i:n?this.context.getOptionalNullableOf(i):Kt.TypeLiteral.optional({value:i,useOf:!0})}return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,as:"request"})}default:Be(t)}}getBytesBodyRequestArg({value:t}){return t==null?Kt.TypeLiteral.bytes(""):typeof t!="string"?(this.context.errors.add({severity:Ir.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),Kt.TypeLiteral.nop()):Kt.TypeLiteral.bytes(t)}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[],{inlinePathParameters:i,inlineFileProperties:o}={inlinePathParameters:this.context.shouldInlinePathParameters(),inlineFileProperties:this.context.shouldInlineFileProperties()};this.context.errors.scope(Lo.PathParameters);let s=[],a=(t.pathParameters??[]).filter(c=>c.variable==null);a.length>0&&s.push(...this.getPathParameters({namedParameters:a,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let u=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})||n.push(...s.map(c=>c.value)),o||n.push(...u.fileFields.map(c=>c.value)),n.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})?s:[],filePropertyInfo:u})),n}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Lo.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).filter(m=>!this.context.isDirectLiteral(m.typeReference)),u=this.context.sortTypeInstancesByRequiredFirst(s,t.queryParameters??[]).map(m=>({name:this.context.getMethodName(m.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:nDm(m.typeReference),value:m.value,as:"request"})}));this.context.errors.unscope(),this.context.errors.scope(Lo.Headers);let l=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).filter(m=>!this.context.isDirectLiteral(m.typeReference)),d=this.context.sortTypeInstancesByRequiredFirst(l,t.headers??[]).map(m=>({name:this.context.getMethodName(m.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:m.typeReference,value:m.value,as:"request"})}));this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let f=t.body!=null?this.getInlinedRequestBodyBuilderParameters({body:t.body,value:r.requestBody,filePropertyInfo:i}):[];return this.context.errors.unscope(),Kt.TypeLiteral.builder({classReference:Kt.classReference({name:this.context.getClassName(t.declaration.name),packageName:this.context.getRequestsPackageName(t.declaration.fernFilepath)}),parameters:[...n,...d,...u,...f]})}getRequestOptionsArg({request:t,snippet:r}){let n="headers"in t?t.headers??[]:[];if(n.length===0||Object.keys(r.headers??{}).length===0)return;this.context.errors.scope(Lo.Headers);let i=this.context.associateByWireValue({parameters:n,values:r.headers??{}});if(this.context.errors.unscope(),i.length===0)return;let o=Kt.classReference({name:"RequestOptions",packageName:this.context.getCorePackageName()}),s=Kt.invokeMethod({on:o,method:"builder",arguments_:[]});for(let u of i)s=Kt.invokeMethod({on:s,method:"addHeader",arguments_:[Kt.TypeLiteral.string(u.name.wireValue),this.context.dynamicTypeLiteralMapper.convert(u)]});let a=Kt.invokeMethod({on:s,method:"build",arguments_:[]});return Kt.TypeLiteral.reference(a)}getInlinedRequestBodyBuilderParameters({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyBuilderParameters({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyBuilderParameter({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyBuilderParameters({filePropertyInfo:n});default:Be(t)}}getFileUploadRequestBodyBuilderParameters({filePropertyInfo:t}){return this.context.shouldInlineFileProperties()?[...t.fileFields,...t.bodyPropertyFields]:t.bodyPropertyFields}getReferencedRequestBodyPropertyBuilderParameter({body:t,value:r}){return{name:this.context.getMethodName(t.bodyKey),value:this.getReferencedRequestBodyPropertyTypeLiteral({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyTypeLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,as:"request"});default:Be(t)}}getInlinedRequestBodyPropertyBuilderParameters({parameters:t,value:r}){let i=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}}).filter(s=>!this.context.isDirectLiteral(s.typeReference));return this.context.sortTypeInstancesByRequiredFirst(i,t).map(s=>({name:this.context.getMethodName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:s.typeReference,value:s.value,as:"request"})}))}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:r.pathParameters??{}});for(let o of i)n.push({name:this.context.getMethodName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert(o)});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>`${this.context.getMethodName(r)}()`).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getStyle(t){return t.style??this.context.options.style??CC.Full}getConfig(t){return t.config??this.context.options.config??{}}};var TLt=class extends Wv{constructor({ir:t,config:r,options:n={}}){super(new yMn({ir:t,config:r,options:n}))}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new bMn({context:t})}};var BMe=require("fs/promises"),bYu=Ae(require("path"),1);var EMn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new TLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");let n=await this.initializeProject(t);for(let[s,a]of r.entries())try{let u=pS(a);if(u==null)continue;let c=await this.dynamicSnippetsGenerator.generate(u,{config:{fullStyleClassName:`Example${s}`,fullStylePackageName:"com.snippets"},style:CC.Full}),l=this.getTestFilePath({absolutePathToOutputDir:n,idx:s});await(0,BMe.mkdir)(bYu.default.dirname(l),{recursive:!0}),await(0,BMe.writeFile)(l,c.snippet)}catch(u){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(a.endpoint)}: ${u}`)}this.context.logger.debug("Dynamic snippets test files generated, running spotlessApply...");let i=Ge(t,Se.of("gradlew"));if(await er(i,"file"))try{let a=this.generatorConfig.customConfig?.["enable-gradle-profiling"]===!0,u=[":spotlessApply"];if(a&&(u.push("--profile"),this.context.logger.info("Running spotlessApply with profiling enabled")),await Bc(this.context.logger,"./gradlew",u,{doNotPipeOutput:!1,cwd:t}),this.context.logger.debug("Successfully ran spotlessApply"),a){let c=Ge(t,Se.of("build/reports")),l=Ge(t,Se.of("reports"));await er(c,"directory")?(await(0,BMe.cp)(c,l,{recursive:!0}),this.context.logger.info("Gradle profiling report copied to reports/")):this.context.logger.info("No profiling report found in build/reports/")}}catch(s){this.context.failAndThrow("Failed to run spotlessApply",s)}this.context.logger.debug("Done generating dynamic snippet tests")}async initializeProject(t){let r=Ge(t,Se.of("src/main/java/com/snippets"));return await(0,BMe.mkdir)(r,{recursive:!0}),r}getTestFilePath({absolutePathToOutputDir:t,idx:r}){return Ge(t,Se.of(`Example${r}.java`))}};qt();var EYu="self",vYu="static";var IYu=new Set(["abstract","and","array","as","break","callable","case","catch","class","clone","const","continue","declare","default","die","do","echo","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","eval","exit","extends","final","finally","fn","for","foreach","function","global","goto","if","implements","include","include_once","instanceof","insteadof","interface","isset","list","match","namespace","new","or","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","unset","use","var","while","xor","yield","yield_from","__halt_compiler"]);var rn={};Z(rn,{Access:()=>MSe,Array:()=>TMe,AstNode:()=>El,Attribute:()=>PMe,Class:()=>pfe,ClassInstantiation:()=>Dne,ClassReference:()=>xC,CodeBlock:()=>uP,DataClass:()=>OMe,Enum:()=>DMe,Field:()=>RMe,Interface:()=>FMe,Map:()=>NMe,Method:()=>mfe,MethodInvocation:()=>dfe,Parameter:()=>ffe,Trait:()=>kMe,Type:()=>N7,TypeLiteral:()=>F7,Writer:()=>Pne,array:()=>pDm,assignVariable:()=>_Dm,attribute:()=>fDm,classReference:()=>gDm,class_:()=>dDm,codeblock:()=>QMe,dataClass:()=>ADm,enum_:()=>yDm,escapePhpString:()=>gmo,field:()=>bDm,instantiateClass:()=>BYu,interface_:()=>hDm,invokeMethod:()=>EDm,map:()=>IDm,mergeArrays:()=>ODm,method:()=>wDm,parameter:()=>CDm,string:()=>BDm,ternary:()=>xDm,this_:()=>TDm,throwException:()=>vDm,trait:()=>mDm,variable:()=>SDm});function wYu(e){return{namespace:e.substring(0,e.lastIndexOf("\\")),name:e.substring(e.lastIndexOf("\\")+1)}}var Pne=class extends wC{namespace;rootNamespace;customConfig;references={};constructor({namespace:t,rootNamespace:r,customConfig:n}){super(),this.namespace=t,this.rootNamespace=r,this.customConfig=n}addReference(t){if(t.namespace==null)return;if(Object.keys(this.references).filter(o=>{let s=wYu(o);return s.namespace!==t.namespace&&s.name===t.name}).length>0){t.requireFullyQualified();return}let n=t.namespace===""?t.name:`${t.namespace}\\${t.name}`;(this.references[n]??=[]).push(t)}toString(t=!1){if(t)return this.buffer;let r=`namespace ${this.namespace};`,n=this.stringifyImports();return n.length>0?`${r}
2533
+ This prevents invalid snippet code generation that would cause formatter errors.`)}getUndiscriminatedUnionFieldName({typeReference:t}){switch(t.type){case"list":return this.getUndiscriminatedUnionFieldNameForList({list:t});case"literal":return this.getUndiscriminatedUnionFieldNameForLiteral({literal:t.value});case"map":return this.getUndiscriminatedUnionFieldNameForMap({map:t});case"named":{let r=this.context.resolveNamedType({typeId:t.value});return r==null?void 0:this.context.getClassName(r.declaration.name)}case"optional":return this.getUndiscriminatedUnionFieldNameForOptional({typeReference:t});case"nullable":return this.getUndiscriminatedUnionFieldNameForNullable({typeReference:t});case"primitive":return this.getUndiscriminatedUnionFieldNameForPrimitive({primitive:t.value});case"set":return this.getUndiscriminatedUnionFieldNameForSet({set:t});case"unknown":return"Unknown";default:Be(t)}}getUndiscriminatedUnionFieldNameForList({list:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`ListOf${r}`}getUndiscriminatedUnionFieldNameForMap({map:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t.key});if(r==null)return;let n=this.getUndiscriminatedUnionFieldName({typeReference:t.value});if(n!=null)return`MapOf${r}To${n}`}getUndiscriminatedUnionFieldNameForOptional({typeReference:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`Optional${r}`}getUndiscriminatedUnionFieldNameForNullable({typeReference:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`Nullable${r}`}getUndiscriminatedUnionFieldNameForSet({set:t}){let r=this.getUndiscriminatedUnionFieldName({typeReference:t});if(r!=null)return`SetOf${r}`}getUndiscriminatedUnionFieldNameForLiteral({literal:t}){}getUndiscriminatedUnionFieldNameForPrimitive({primitive:t}){switch(t){case"INTEGER":case"UINT":return"Integer";case"LONG":case"UINT_64":return"Long";case"FLOAT":return"Float";case"DOUBLE":return"Double";case"BOOLEAN":return"Boolean";case"BIG_INTEGER":return"BigInteger";case"STRING":return"String";case"UUID":return"Uuid";case"DATE":return"Date";case"DATE_TIME":return"DateTime";case"BASE_64":return"Base64";default:{if(t==="DATE_TIME_RFC_2822")return"DateTimeRfc2822";Be(t)}}}convertUnknown({value:t}){return this.context.customConfig?.["generate-unknown-as-json-node"]===!0?this.convertToJsonNode({value:t}):Kt.TypeLiteral.unknown(t)}convertToJsonNode({value:t}){let r=Kt.classReference({name:"ObjectMappers",packageName:this.context.getCorePackageName()});return typeof t=="string"?Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[Kt.TypeLiteral.string(t)]})):typeof t=="number"?Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[Kt.TypeLiteral.integer(t)]})):typeof t=="boolean"?Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[Kt.TypeLiteral.boolean(t)]})):t===null?Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[Kt.TypeLiteral.raw(Kt.codeblock("null"))]})):Array.isArray(t)?Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[Kt.TypeLiteral.list({valueType:Kt.Type.object(),values:t.map(n=>Kt.TypeLiteral.unknown(n)),isParameter:!0})]})):typeof t=="object"&&t!==null?Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.codeblock(n=>{n.writeNode(r),n.write(".JSON_MAPPER")}),method:"valueToTree",arguments_:[Kt.TypeLiteral.unknown(t)]})):Kt.TypeLiteral.unknown(t)}convertPrimitive({primitive:t,value:r,as:n}){switch(t){case"INTEGER":case"UINT":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.integer(i)}case"LONG":case"UINT_64":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.long(i)}case"FLOAT":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.float(i)}case"DOUBLE":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.double(i)}case"BOOLEAN":{let i=this.getValueAsBoolean({value:r,as:n});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.boolean(i)}case"STRING":{let i=this.context.getValueAsString({value:r});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.string(i)}case"DATE":{let i=this.context.getValueAsString({value:r});return i==null?Kt.TypeLiteral.nop():this.context.customConfig?.["use-local-date-for-dates"]===!0?Kt.TypeLiteral.date(i):Kt.TypeLiteral.string(i)}case"DATE_TIME":{let i=this.context.getValueAsString({value:r});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.dateTime(i)}case"UUID":{let i=this.context.getValueAsString({value:r});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.uuid(i)}case"BASE_64":{let i=this.context.getValueAsString({value:r});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.bytes(i)}case"BIG_INTEGER":{let i=this.context.getValueAsString({value:r});return i==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.bigInteger(i)}default:{if(t==="DATE_TIME_RFC_2822"){let o=this.context.getValueAsString({value:r});return o==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.dateTime(o)}Be(t)}}}getValueAsNumber({value:t,as:r}){let n=r==="mapKey"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="mapKey"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:n})}};St();var gMn=class{context;constructor({context:t}){this.context=t}convert(t){switch(t.typeReference.type){case"list":return Kt.Type.list(this.convert({typeReference:t.typeReference}));case"literal":return this.convertLiteral({literal:t.typeReference.value});case"map":return Kt.Type.map(this.convert({typeReference:t.typeReference.key}),this.convert({typeReference:t.typeReference.value}));case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?this.convertUnknown():this.convertNamed({named:r})}case"optional":case"nullable":return Kt.Type.optional(this.convert({typeReference:t.typeReference.value}));case"primitive":return this.convertPrimitive({primitive:t.typeReference.value});case"set":return Kt.Type.set(this.convert({typeReference:t.typeReference}));case"unknown":return this.convertUnknown();default:Be(t.typeReference)}}convertNamed({named:t}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference});case"enum":case"discriminatedUnion":case"object":case"undiscriminatedUnion":return Kt.Type.reference(Kt.classReference({name:this.context.getClassName(t.declaration.name),packageName:this.context.getTypesPackageName(t.declaration.fernFilepath)}));default:Be(t)}}convertLiteral({literal:t}){switch(t.type){case"boolean":return Kt.Type.boolean();case"string":return Kt.Type.string()}}convertUnknown(){return this.context.customConfig?.["generate-unknown-as-json-node"]===!0?Kt.Type.reference(Kt.classReference({name:"JsonNode",packageName:"com.fasterxml.jackson.databind"})):Kt.Type.object()}convertPrimitive({primitive:t}){switch(t){case"INTEGER":return Kt.Type.integer();case"UINT":return Kt.Type.integer();case"LONG":return Kt.Type.long();case"UINT_64":return Kt.Type.long();case"FLOAT":return Kt.Type.float();case"DOUBLE":return Kt.Type.double();case"BOOLEAN":return Kt.Type.boolean();case"STRING":return Kt.Type.string();case"DATE":return Kt.Type.date();case"DATE_TIME":return Kt.Type.dateTime();case"UUID":return Kt.Type.uuid();case"BASE_64":return Kt.Type.bytes();case"BIG_INTEGER":return Kt.Type.bigInteger();default:{if(t==="DATE_TIME_RFC_2822")return Kt.Type.dateTime();Be(t)}}}};St();var AMn=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({body:t,value:r}){let n={fileFields:[],bodyPropertyFields:[]},i=this.context.getRecord(r)??{};for(let o of t.properties)switch(o.type){case"file":n.fileFields.push({name:this.context.getMethodName(o.name),value:this.getSingleFileProperty({property:o,record:i})});break;case"fileArray":n.fileFields.push({name:this.context.getMethodName(o.name),value:this.getArrayFileProperty({property:o,record:i})});break;case"bodyProperty":n.bodyPropertyFields.push({name:this.context.getMethodName(o.name.name),value:this.getBodyProperty({property:o,record:i})});break;default:Be(o)}return n}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r});return n==null?Kt.TypeLiteral.nop():Kt.TypeLiteral.reference(this.context.getFileStreamFromString(n))}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});if(n==null)return Kt.TypeLiteral.nop();for(let i of n)return Kt.TypeLiteral.reference(this.context.getFileStreamFromString(i));return Kt.TypeLiteral.nop()}getBodyProperty({property:t,record:r}){let n=r[t.name.wireValue];return n==null?Kt.TypeLiteral.nop():this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:n})}};var YPm=new Set(["enum","extends","package","void","short","class","abstract","return","import","for","assert","switch"]),XPm=new Set(["getClass","notify","notifyAll","wait"]),yMn=class e extends $v{ir;customConfig;dynamicTypeMapper;dynamicTypeLiteralMapper;filePropertyMapper;constructor({ir:t,config:r,options:n}){super({ir:t,config:r,options:n}),this.ir=t,this.customConfig=pmo.parse(r.customConfig??{}),this.dynamicTypeMapper=new gMn({context:this}),this.dynamicTypeLiteralMapper=new hMn({context:this}),this.filePropertyMapper=new AMn({context:this})}clone(){return new e({ir:this.ir,config:this.config,options:this.options})}getClassName(t){return this.getName(t.pascalCase.safeName)}getEnumName(t){return this.getName(t.screamingSnakeCase.safeName)}getPropertyName(t){return this.getName(t.camelCase.safeName)}getMethodName(t){let r=t.camelCase.safeName;return this.isReservedMethodName(r)?r+"_":this.getName(r)}getRootClientClassReference(){return Kt.classReference({name:this.getRootClientClassName(),packageName:this.getRootPackageName()})}getRootClientClassName(){return this.customConfig?.["client-class-name"]??`${this.getBaseNamePrefix()}Client`}getEnvironmentClassName(){return"Environment"}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return Kt.codeblock(n=>{n.writeNode(this.getEnvironmentClassReference()),n.write("."),n.write(this.getEnumName(r))})}getEnvironmentClassReference(){return Kt.classReference({name:this.getEnvironmentClassName(),packageName:this.getCorePackageName()})}getJavaClassReferenceFromDeclaration({declaration:t}){return Kt.classReference({name:t.name.pascalCase.unsafeName,packageName:this.getTypesPackageName(t.fernFilepath)})}getNullableClassReference(){return Kt.classReference({name:"Nullable",packageName:this.getCorePackageName()})}getNullableOfNull(){return Kt.TypeLiteral.reference(Kt.invokeMethod({on:this.getNullableClassReference(),method:"ofNull",arguments_:[]}))}getOptionalNullableClassReference(){return Kt.classReference({name:"OptionalNullable",packageName:this.getCorePackageName()})}getOptionalNullableAbsent(){return Kt.TypeLiteral.reference(Kt.invokeMethod({on:this.getOptionalNullableClassReference(),method:"absent",arguments_:[]}))}getOptionalNullableOf(t){return Kt.TypeLiteral.reference(Kt.invokeMethod({on:this.getOptionalNullableClassReference(),method:"of",arguments_:[t]}))}getFileStreamFromString(t){return Kt.TypeLiteral.reference(Kt.codeblock(r=>{r.write("new "),r.writeNode(this.getFileStreamClassReference()),r.write("("),r.writeNode(this.getByteArrayInputStreamClassReference()),r.write("("),r.writeNode(Kt.TypeLiteral.string(t)),r.write(".getBytes("),r.writeNode(this.getStandardCharsetsClassReference()),r.write(".UTF_8)))")}))}getFileStreamClassReference(){return Kt.classReference({name:"FileStream",packageName:this.getCorePackageName()})}getByteArrayInputStreamClassReference(){return Kt.classReference({name:"ByteArrayInputStream",packageName:"java.io"})}getStandardCharsetsClassReference(){return Kt.classReference({name:"StandardCharsets",packageName:"java.nio.charset"})}isPrimitive(t){switch(t.type){case"primitive":return!0;case"optional":case"nullable":return this.isPrimitive(t.value);case"named":{let r=this.resolveNamedType({typeId:t.value});if(r==null)return!1;switch(r.type){case"alias":return this.isPrimitive(r.typeReference);case"discriminatedUnion":case"undiscriminatedUnion":case"object":case"enum":return!1;default:Be(r)}break}case"list":case"set":case"map":case"literal":case"unknown":return!1;default:Be(t)}}isDirectLiteral(t){return t.type==="literal"}sortTypeInstancesByRequiredFirst(t,r){let n=new Map;r.forEach((s,a)=>{n.set(s.name.wireValue,a)});let i=[],o=[];for(let s of t)this.isOptional(s.typeReference)?o.push(s):i.push(s);return i.sort((s,a)=>(n.get(s.name.wireValue)??0)-(n.get(a.name.wireValue)??0)),[...i,...o]}associateByWireValue({parameters:t,values:r,ignoreMissingParameters:n}){let i=super.associateByWireValue({parameters:t,values:r,ignoreMissingParameters:n}),o=new Map;for(let a of i)o.set(a.name.wireValue,a);let s=[];for(let a of t){let u=o.get(a.name.wireValue);u!=null&&s.push(u)}return s}getRootPackageName(){let t=this.getPackagePrefixTokens();return this.joinPackageTokens(t)}getCorePackageName(){let t=this.getPackagePrefixTokens();return t.push("core"),this.joinPackageTokens(t)}getTypesPackageName(t){return this.getResourcesPackage(t,"types")}getRequestsPackageName(t){return this.getPackageLayout()==="flat"?this.getTypesPackageName(t):this.getResourcesPackage(t,"requests")}getResourcesPackage(t,r){let n=this.getPackagePrefixTokens();return this.getPackageLayout()==="flat"?t!=null&&n.push(...t.packagePath.map(i=>this.getPackageNameSegment(i))):(t!=null&&t.allParts.length>0&&n.push("resources"),t!=null&&n.push(...t.allParts.map(i=>this.getPackageNameSegment(i)))),r!=null&&n.push(r),this.joinPackageTokens(n)}getPackageName(t,r){let n=this.getPackageNameSegments(t);return n=r!=null?[...n,r]:n,[...this.getPackagePrefixTokens(),...n].join(".")}getPackageLayout(){return this.customConfig?.["package-layout"]??"nested"}shouldInlinePathParameters(){return this.customConfig?.["inline-path-parameters"]??!1}shouldInlineFileProperties(){return this.customConfig?.["inline-file-properties"]??!1}getPackageNameSegments(t){return t.packagePath.map(r=>this.getPackageNameSegment(r))}getPackageNameSegment(t){return t.camelCase.safeName.toLowerCase()}getPackagePrefixTokens(){if(this.customConfig?.["package-prefix"]!=null)return this.customConfig["package-prefix"].split(".");let t=[];return t.push("com"),t.push(...this.splitOnNonAlphaNumericChar(this.config.organization)),t.push(...this.splitOnNonAlphaNumericChar(this.getApiName())),t}getBaseNamePrefix(){return this.convertKebabCaseToUpperCamelCase(this.config.organization)+this.convertKebabCaseToUpperCamelCase(this.getApiName())}getApiName(){return qn(this.config.workspaceName)}startsWithNumber(t){return/^\d/.test(t)}splitOnNonAlphaNumericChar(t){return t.split(/[^a-zA-Z0-9]/)}convertKebabCaseToUpperCamelCase(t){return t.replace(/-([a-z])/g,(r,n)=>n.toUpperCase()).replace(/^[a-z]/,r=>r.toUpperCase())}joinPackageTokens(t){return t.map(n=>this.startsWithNumber(n)?"_"+n:n).join(".")}getName(t){return this.isReservedName(t)?"_"+t:t}isReservedName(t){return YPm.has(t)}isReservedMethodName(t){return XPm.has(t)}};St();var AYu="com.example.usage",ZPm="Example",eDm="main",tDm="args",yYu="client",rDm={type:"primitive",value:"STRING"};function nDm(e){if(e.type==="optional"&&e.value.type==="list"){let r=e.value.value;if(r.type==="optional")return{type:"optional",value:{type:"list",value:r.value}}}if(e.type==="list"){let t=e.value;if(t.type==="optional")return{type:"list",value:t.value}}return e}var bMn=class{context;formatter;constructor({context:t,formatter:r}){this.context=t,this.formatter=r}async generateSnippet({endpoint:t,request:r,options:n}){let i=this.getConfig(n);return await this.buildCodeBlock({endpoint:t,snippet:r,options:n}).toStringAsync({packageName:i.fullStylePackageName??AYu,customConfig:this.context.customConfig,formatter:this.formatter})}generateSnippetSync({endpoint:t,request:r,options:n}){let i=this.getConfig(n);return this.buildCodeBlock({endpoint:t,snippet:r,options:n}).toString({packageName:i.fullStylePackageName??AYu,customConfig:this.context.customConfig,formatter:this.formatter})}async generateSnippetAst({endpoint:t,request:r,options:n}){throw new Error("Unsupported")}buildCodeBlock({endpoint:t,snippet:r,options:n}){let i=Kt.codeblock(s=>{s.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),s.newLine(),s.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))}),o=this.getStyle(n);switch(o){case CC.Concise:return i;case CC.Full:return this.buildFullCodeBlock({body:i,options:n});default:Be(o)}}constructClient({endpoint:t,snippet:r}){let n=t.auth?.type==="oauth";return Kt.codeblock(i=>{if(i.writeNode(this.context.getRootClientClassReference()),i.write(` ${yYu} = `),n&&r.auth?.type==="oauth"){let o=r.auth;i.writeNode(this.context.getRootClientClassReference()),i.write(`.withCredentials("${o.clientId}", "${o.clientSecret}")`),i.writeNewLineIfLastLineNot(),i.indent();let s=this.getRootClientBuilderArgsExcludingAuth({endpoint:t,snippet:r});for(let a of s)i.write(`.${a.name}(`),a.value.shouldWriteInLine()||i.newLine(),i.writeNode(a.value),a.value.shouldWriteInLine()||i.newLine(),i.writeLine(")");i.writeLine(".build()"),i.dedent()}else i.writeNode(Kt.TypeLiteral.builder({classReference:this.context.getRootClientClassReference(),parameters:this.getRootClientBuilderArgs({endpoint:t,snippet:r})}))})}getRootClientBuilderArgsExcludingAuth({endpoint:t,snippet:r}){let n=[],i=this.getRootClientBaseUrlArg({baseUrl:r.baseURL,environment:r.environment});i!=null&&n.push(i),this.context.errors.scope(Lo.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope();let o=new Set;if([...this.context.ir.pathParameters??[],...t.request.pathParameters??[]].forEach(a=>{a.variable!=null&&o.add(a.variable)}),this.context.ir.variables!=null&&this.context.ir.variables.length>0){for(let a of this.context.ir.variables)if(o.has(a.id)){let u=a.name.camelCase.unsafeName;n.push({name:u,value:Kt.TypeLiteral.string(`YOUR_${a.name.screamingSnakeCase.unsafeName}`)})}}if(this.context.errors.scope(Lo.PathParameters),this.context.ir.pathParameters!=null&&this.context.ir.pathParameters.length>0){let a=this.context.ir.pathParameters.filter(u=>u.variable==null);a.length>0&&n.push(...this.getPathParameters({namedParameters:a,snippet:r}))}return this.context.errors.unscope(),n}buildFullCodeBlock({body:t,options:r}){let n=this.getConfig(r),i=Kt.class_({name:n.fullStyleClassName??ZPm,access:Kt.Access.Public}),o=Kt.parameter({name:tDm,type:Kt.Type.array(Kt.Type.string())});return i.addMethod(Kt.method({name:eDm,access:Kt.Access.Public,static_:!0,parameters:[o],body:t})),i}getRootClientBuilderArgs({endpoint:t,snippet:r}){let n=[];t.auth!=null&&(r.auth!=null?n.push(...this.getRootClientAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Ir.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`}));let i=this.getRootClientBaseUrlArg({baseUrl:r.baseURL,environment:r.environment});i!=null&&n.push(i),this.context.errors.scope(Lo.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope();let o=new Set;if([...this.context.ir.pathParameters??[],...t.request.pathParameters??[]].forEach(a=>{a.variable!=null&&o.add(a.variable)}),this.context.ir.variables!=null&&this.context.ir.variables.length>0){for(let a of this.context.ir.variables)if(o.has(a.id)){let u=a.name.camelCase.unsafeName;n.push({name:u,value:Kt.TypeLiteral.string(`YOUR_${a.name.screamingSnakeCase.unsafeName}`)})}}if(this.context.errors.scope(Lo.PathParameters),this.context.ir.pathParameters!=null&&this.context.ir.pathParameters.length>0){let a=this.context.ir.pathParameters.filter(u=>u.variable==null);a.length>0&&n.push(...this.getPathParameters({namedParameters:a,snippet:r}))}return this.context.errors.unscope(),n}getRootClientBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null){if(this.context.ir.environments?.environments.type==="multipleBaseUrls"){this.context.errors.add({severity:Ir.Critical,message:"The Java SDK doesn't support a baseUrl when multiple URL environments are configured"});return}return{name:"url",value:Kt.TypeLiteral.string(t)}}if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);if(n==null){this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return{name:"environment",value:Kt.TypeLiteral.reference(n)}}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?{name:"environment",value:Kt.TypeLiteral.reference(Kt.instantiateClass({classReference:this.context.getEnvironmentClassReference(),arguments_:Object.values(r).map(n=>this.context.dynamicTypeLiteralMapper.convert({typeReference:rDm,value:n}))}))}:void 0}}getRootClientAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?this.getRootClientBasicAuthArgs({auth:t,values:r}):[];case"bearer":return r.type==="bearer"?this.getRootClientBearerAuthArgs({auth:t,values:r}):[];case"header":return r.type==="header"?this.getRootClientHeaderAuthArgs({auth:t,values:r}):[];case"oauth":return r.type==="oauth"?this.getRootClientOAuthArgs({auth:t,values:r}):[];case"inferred":return this.addWarning("The Java SDK Generator does not support Inferred auth scheme yet"),[];default:Be(t)}}addError(t){this.context.errors.add({severity:Ir.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getRootClientBasicAuthArgs({auth:t,values:r}){return[{name:"credentials",value:Kt.TypeLiteral.raw(`"${r.username}", "${r.password}"`)}]}getRootClientBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getMethodName(t.token),value:Kt.TypeLiteral.string(r.token)}]}getRootClientHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getMethodName(t.header.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value})}]}getRootClientOAuthArgs({auth:t,values:r}){return[{name:this.context.getMethodName(t.clientId),value:Kt.TypeLiteral.string(r.clientId)},{name:this.context.getMethodName(t.clientSecret),value:Kt.TypeLiteral.string(r.clientSecret)}]}getRootClientHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getRootClientHeaderArg({header:i,value:o});s!=null&&n.push({name:this.context.getMethodName(i.name.name),value:s})}return n}getRootClientHeaderArg({header:t,value:r}){let n=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:r});if(!Kt.TypeLiteral.isNop(n))return n}callMethod({endpoint:t,snippet:r}){return Kt.invokeMethod({on:Kt.codeblock(yYu),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:r})})}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=(t.pathParameters??[]).filter(s=>s.variable==null);i.length>0&&n.push(...this.getPathParameters({namedParameters:i,snippet:r}).map(s=>s.value)),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),t.body!=null&&n.push(this.getBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope();let o=this.getRequestOptionsArg({request:t,snippet:r});return o!=null&&n.push(o),n}usesOptionalNullable(){return this.context.customConfig?.["collapse-optional-nullable"]===!0}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":{if(t.value.type==="optional"){let n=this.usesOptionalNullable()&&(t.value.value.type==="optional"||t.value.value.type==="nullable");if(r==null)return n?this.context.getOptionalNullableAbsent():Kt.TypeLiteral.reference(Kt.invokeMethod({on:Kt.classReference({name:"Optional",packageName:"java.util"}),method:"empty",arguments_:[]}));let i=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value.value,value:r,as:"request",isCollapsedOptionalNullable:n}),o=i.toString({packageName:"com.example",customConfig:this.context.customConfig});return o.includes("Optional.empty()")||o.includes("OptionalNullable.absent()")?i:n?this.context.getOptionalNullableOf(i):Kt.TypeLiteral.optional({value:i,useOf:!0})}return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,as:"request"})}default:Be(t)}}getBytesBodyRequestArg({value:t}){return t==null?Kt.TypeLiteral.bytes(""):typeof t!="string"?(this.context.errors.add({severity:Ir.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),Kt.TypeLiteral.nop()):Kt.TypeLiteral.bytes(t)}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[],{inlinePathParameters:i,inlineFileProperties:o}={inlinePathParameters:this.context.shouldInlinePathParameters(),inlineFileProperties:this.context.shouldInlineFileProperties()};this.context.errors.scope(Lo.PathParameters);let s=[],a=(t.pathParameters??[]).filter(c=>c.variable==null);a.length>0&&s.push(...this.getPathParameters({namedParameters:a,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let u=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})||n.push(...s.map(c=>c.value)),o||n.push(...u.fileFields.map(c=>c.value)),n.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})?s:[],filePropertyInfo:u})),n}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Lo.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).filter(m=>!this.context.isDirectLiteral(m.typeReference)),u=this.context.sortTypeInstancesByRequiredFirst(s,t.queryParameters??[]).map(m=>({name:this.context.getMethodName(m.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:nDm(m.typeReference),value:m.value,as:"request"})}));this.context.errors.unscope(),this.context.errors.scope(Lo.Headers);let l=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).filter(m=>!this.context.isDirectLiteral(m.typeReference)),d=this.context.sortTypeInstancesByRequiredFirst(l,t.headers??[]).map(m=>({name:this.context.getMethodName(m.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:m.typeReference,value:m.value,as:"request"})}));this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let f=t.body!=null?this.getInlinedRequestBodyBuilderParameters({body:t.body,value:r.requestBody,filePropertyInfo:i}):[];return this.context.errors.unscope(),Kt.TypeLiteral.builder({classReference:Kt.classReference({name:this.context.getClassName(t.declaration.name),packageName:this.context.getRequestsPackageName(t.declaration.fernFilepath)}),parameters:[...n,...d,...u,...f]})}getRequestOptionsArg({request:t,snippet:r}){let n="headers"in t?t.headers??[]:[];if(n.length===0||Object.keys(r.headers??{}).length===0)return;this.context.errors.scope(Lo.Headers);let i=this.context.associateByWireValue({parameters:n,values:r.headers??{}});if(this.context.errors.unscope(),i.length===0)return;let o=Kt.classReference({name:"RequestOptions",packageName:this.context.getCorePackageName()}),s=Kt.invokeMethod({on:o,method:"builder",arguments_:[]});for(let u of i)s=Kt.invokeMethod({on:s,method:"addHeader",arguments_:[Kt.TypeLiteral.string(u.name.wireValue),this.context.dynamicTypeLiteralMapper.convert(u)]});let a=Kt.invokeMethod({on:s,method:"build",arguments_:[]});return Kt.TypeLiteral.reference(a)}getInlinedRequestBodyBuilderParameters({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyBuilderParameters({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyBuilderParameter({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyBuilderParameters({filePropertyInfo:n});default:Be(t)}}getFileUploadRequestBodyBuilderParameters({filePropertyInfo:t}){return this.context.shouldInlineFileProperties()?[...t.fileFields,...t.bodyPropertyFields]:t.bodyPropertyFields}getReferencedRequestBodyPropertyBuilderParameter({body:t,value:r}){return{name:this.context.getMethodName(t.bodyKey),value:this.getReferencedRequestBodyPropertyTypeLiteral({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyTypeLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,as:"request"});default:Be(t)}}getInlinedRequestBodyPropertyBuilderParameters({parameters:t,value:r}){let i=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}}).filter(s=>!this.context.isDirectLiteral(s.typeReference));return this.context.sortTypeInstancesByRequiredFirst(i,t).map(s=>({name:this.context.getMethodName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:s.typeReference,value:s.value,as:"request"})}))}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:r.pathParameters??{}});for(let o of i)n.push({name:this.context.getMethodName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert(o)});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>`${this.context.getMethodName(r)}()`).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getStyle(t){return t.style??this.context.options.style??CC.Full}getConfig(t){return t.config??this.context.options.config??{}}};var TLt=class extends Wv{constructor({ir:t,config:r,options:n={}}){super(new yMn({ir:t,config:r,options:n}))}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new bMn({context:t})}};var BMe=require("fs/promises"),bYu=Ae(require("path"),1);var EMn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new TLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");let n=await this.initializeProject(t);for(let[s,{endpointId:a,request:u}]of r.entries())try{let c=pS(u);if(c==null)continue;let l=await this.dynamicSnippetsGenerator.generate(c,{config:{fullStyleClassName:`Example${s}`,fullStylePackageName:"com.snippets"},style:CC.Full,endpointId:a}),p=this.getTestFilePath({absolutePathToOutputDir:n,idx:s});await(0,BMe.mkdir)(bYu.default.dirname(p),{recursive:!0}),await(0,BMe.writeFile)(p,l.snippet)}catch(c){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(u.endpoint)}: ${c}`)}this.context.logger.debug("Dynamic snippets test files generated, running spotlessApply...");let i=Ge(t,Se.of("gradlew"));if(await er(i,"file"))try{let a=this.generatorConfig.customConfig?.["enable-gradle-profiling"]===!0,u=[":spotlessApply"];if(a&&(u.push("--profile"),this.context.logger.info("Running spotlessApply with profiling enabled")),await Bc(this.context.logger,"./gradlew",u,{doNotPipeOutput:!1,cwd:t}),this.context.logger.debug("Successfully ran spotlessApply"),a){let c=Ge(t,Se.of("build/reports")),l=Ge(t,Se.of("reports"));await er(c,"directory")?(await(0,BMe.cp)(c,l,{recursive:!0}),this.context.logger.info("Gradle profiling report copied to reports/")):this.context.logger.info("No profiling report found in build/reports/")}}catch(s){this.context.failAndThrow("Failed to run spotlessApply",s)}this.context.logger.debug("Done generating dynamic snippet tests")}async initializeProject(t){let r=Ge(t,Se.of("src/main/java/com/snippets"));return await(0,BMe.mkdir)(r,{recursive:!0}),r}getTestFilePath({absolutePathToOutputDir:t,idx:r}){return Ge(t,Se.of(`Example${r}.java`))}};qt();var EYu="self",vYu="static";var IYu=new Set(["abstract","and","array","as","break","callable","case","catch","class","clone","const","continue","declare","default","die","do","echo","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","eval","exit","extends","final","finally","fn","for","foreach","function","global","goto","if","implements","include","include_once","instanceof","insteadof","interface","isset","list","match","namespace","new","or","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","unset","use","var","while","xor","yield","yield_from","__halt_compiler"]);var rn={};Z(rn,{Access:()=>MSe,Array:()=>TMe,AstNode:()=>El,Attribute:()=>PMe,Class:()=>pfe,ClassInstantiation:()=>Dne,ClassReference:()=>xC,CodeBlock:()=>uP,DataClass:()=>OMe,Enum:()=>DMe,Field:()=>RMe,Interface:()=>FMe,Map:()=>NMe,Method:()=>mfe,MethodInvocation:()=>dfe,Parameter:()=>ffe,Trait:()=>kMe,Type:()=>N7,TypeLiteral:()=>F7,Writer:()=>Pne,array:()=>pDm,assignVariable:()=>_Dm,attribute:()=>fDm,classReference:()=>gDm,class_:()=>dDm,codeblock:()=>QMe,dataClass:()=>ADm,enum_:()=>yDm,escapePhpString:()=>gmo,field:()=>bDm,instantiateClass:()=>BYu,interface_:()=>hDm,invokeMethod:()=>EDm,map:()=>IDm,mergeArrays:()=>ODm,method:()=>wDm,parameter:()=>CDm,string:()=>BDm,ternary:()=>xDm,this_:()=>TDm,throwException:()=>vDm,trait:()=>mDm,variable:()=>SDm});function wYu(e){return{namespace:e.substring(0,e.lastIndexOf("\\")),name:e.substring(e.lastIndexOf("\\")+1)}}var Pne=class extends wC{namespace;rootNamespace;customConfig;references={};constructor({namespace:t,rootNamespace:r,customConfig:n}){super(),this.namespace=t,this.rootNamespace=r,this.customConfig=n}addReference(t){if(t.namespace==null)return;if(Object.keys(this.references).filter(o=>{let s=wYu(o);return s.namespace!==t.namespace&&s.name===t.name}).length>0){t.requireFullyQualified();return}let n=t.namespace===""?t.name:`${t.namespace}\\${t.name}`;(this.references[n]??=[]).push(t)}toString(t=!1){if(t)return this.buffer;let r=`namespace ${this.namespace};`,n=this.stringifyImports();return n.length>0?`${r}
2534
2534
 
2535
2535
  ${n}
2536
2536
 
@@ -2542,12 +2542,12 @@ ${this.buffer}`:r+`
2542
2542
  `):void 0;n!=null&&n.length>1&&(n.forEach(i=>{t.writeLine(` * ${i}`)}),t.writeLine(" *")),t.write(` * @${r.tagType} `),r.type.write(t,{comment:!0}),r.name!=null&&t.write(` ${r.name}`),n!=null&&n.length===1&&t.write(` ${n[0]}`),t.newLine()}};var MSe={Public:"public",PublicReadonly:"public readonly",Protected:"protected",Private:"private"};function LSe(e){return iDm(e,[MSe.Public,MSe.PublicReadonly,MSe.Protected,MSe.Private])}function iDm(e,t){return t.reduce((r,n)=>[...r,...e.filter(i=>i.access===n)],[])}var pfe=class extends El{name;namespace;abstract;docs;parentClassReference;traits;interfaceReferences;fields=[];methods=[];constructor_;constructor({name:t,namespace:r,abstract:n,docs:i,parentClassReference:o,traits:s,interfaceReferences:a}){super(),this.name=t,this.namespace=r,this.abstract=n??!1,this.docs=i,this.parentClassReference=o,this.traits=s??[],this.interfaceReferences=a??[]}addConstructor(t){this.constructor_=t}addField(t){this.fields.push(t)}addMethod(t){this.methods.push(t)}addMethods(t){this.methods.push(...t)}addTrait(t){this.traits.push(t)}write(t){t.addReference(new xC({name:this.name,namespace:this.namespace})),this.abstract&&t.write("abstract "),this.writeComment(t),t.write(`class ${this.name} `),this.parentClassReference!=null&&(t.write("extends "),this.parentClassReference.write(t)),this.interfaceReferences.length>0&&(this.parentClassReference!=null&&t.write(" "),t.write("implements "),this.interfaceReferences.forEach((r,n)=>{n>0&&t.write(", "),t.writeNode(r)})),t.newLine(),t.writeLine("{"),t.indent(),this.traits.length>0&&(t.write("use "),this.traits.forEach((r,n)=>{n>0&&t.write(","),t.writeNode(r)}),t.writeTextStatement(""),t.newLine()),this.writeFields({writer:t,fields:LSe(this.fields)}),(this.constructor!=null||this.methods.length>0)&&t.newLine(),this.constructor_!=null&&(this.writeConstructor({writer:t,constructor:this.constructor_}),this.methods.length>0&&t.newLine()),this.writeMethods({writer:t,methods:LSe(this.methods)}),t.dedent(),t.writeLine("}")}writeComment(t){if(this.docs==null)return;new tF({docs:this.docs}).write(t)}writeConstructor({writer:t,constructor:r}){this.writeConstructorComment({writer:t,constructor:r}),r.access!=null&&t.write(`${r.access} `),t.write("function __construct("),t.indent(),r.parameters.forEach((n,i)=>{i===0&&t.newLine(),n.write(t),t.writeLine(",")}),t.dedent(),t.writeLine(")"),t.writeLine("{"),t.indent(),r.body?.write(t),t.writeNewLineIfLastLineNot(),t.dedent(),t.writeLine("}")}writeConstructorComment({writer:t,constructor:r}){if(r.parameters.length===0)return;let n=new tF;for(let i of r.parameters)n.addTag(i.getCommentTag());n.write(t)}writeFields({writer:t,fields:r}){r.filter(n=>!n.inherited).forEach((n,i)=>{i>0&&t.newLine(),n.write(t),t.writeNewLineIfLastLineNot()})}writeMethods({writer:t,methods:r}){r.forEach((n,i)=>{i>0&&t.newLine(),n.write(t),t.writeNewLineIfLastLineNot()})}};var uP=class extends El{arg;constructor(t){super(),this.arg=t}write(t){return new Ly(this.arg).write(t)}};var ffe=class extends El{name;type;docs;initializer;access;readonly_;constructor({name:t,type:r,docs:n,initializer:i,access:o,readonly_:s}){super(),this.name=jSe(t),this.type=r,this.docs=n,this.initializer=i,this.access=o,this.readonly_=s??!1}getCommentTag(){return{tagType:"param",type:this.type,name:this.name,docs:this.docs}}write(t){this.access!=null&&t.write(`${this.access} `),this.readonly_&&t.write("readonly "),this.type.write(t),t.write(` ${this.name}`),this.initializer!=null?(t.write(" = "),this.initializer.write(t)):this.type.isOptional()&&t.write(" = null")}};St();Bi();St();function Xft({writer:e,arguments_:t,multiline:r}){if(t.length===0){e.write("()");return}if(r){oDm({writer:e,arguments_:t});return}sDm({writer:e,arguments_:t})}function oDm({writer:e,arguments_:t}){e.writeLine("("),e.indent();for(let r of t)xYu({writer:e,argument:r,writeCompact:!1}),e.writeLine(",");e.dedent(),e.write(")")}function sDm({writer:e,arguments_:t}){e.write("("),t.forEach((r,n)=>{n>0&&e.write(", "),xYu({writer:e,argument:r,writeCompact:!0})}),e.write(")")}function xYu({writer:e,argument:t,writeCompact:r}){ISe(t)?(t.docs&&(r?e.write(`/* ${t.docs} */ `):e.writeLine(`/* ${t.docs} */`)),e.write(`${t.name}: `),e.writeNodeOrString(t.assignment)):t.write(e)}var Dne=class extends El{classReference;arguments_;multiline;constructor({classReference:t,arguments_:r,multiline:n}){super(),this.classReference=t,this.arguments_=r,this.multiline=n??!1}write(t){t.write("new "),t.writeNode(this.classReference),Xft({writer:t,arguments_:this.arguments_,multiline:this.multiline})}};var dfe=class extends El{method;arguments_;multiline;static_;on;constructor({method:t,arguments_:r,static_:n,multiline:i,on:o}){super(),this.method=t,this.arguments_=r,this.static_=n??!1,this.multiline=i??!1,this.on=o}write(t){this.on!=null&&(this.on.write(t),t.write(this.getMethodAccessor())),t.write(this.method),Xft({writer:t,arguments_:this.arguments_,multiline:this.multiline})}getMethodAccessor(){return this.static_?"::":"->"}};var F7=class e extends El{internalType;constructor(t){super(),this.internalType=t}write(t){switch(this.internalType.type){case"list":{this.writeList({writer:t,list:this.internalType});break}case"boolean":{t.write(this.internalType.value.toString());break}case"class":{this.writeClass({writer:t,class_:this.internalType});break}case"file":{t.writeNode(uDm({writer:t,value:this.internalType.value,namespace:this.internalType.namespace}));break}case"float":{t.write(this.internalType.value.toString());break}case"number":{t.write(this.internalType.value.toString());break}case"map":{this.writeMap({writer:t,map:this.internalType});break}case"reference":{t.writeNode(this.internalType.value);break}case"datetime":{t.writeNode(aDm({writer:t,value:this.internalType.value}));break}case"string":{if(this.internalType.value.includes(`
2543
2543
  `)){this.writeStringWithHeredoc({writer:t,value:this.internalType.value});break}if(this.internalType.value.includes("'")){t.write(`"${this.internalType.value.replaceAll('"','\\"')}"`);break}t.write(`'${this.internalType.value}'`);break}case"unknown":{this.writeUnknown({writer:t,value:this.internalType.value});break}case"null":{t.write("null");break}case"nop":break;default:Be(this.internalType)}}isClass(){return this.internalType.type==="class"}asClassOrThrow(){if(this.isClass())return this.internalType;throw new Error("Internal error; ts.TypeLiteral is not a class")}writeStringWithHeredoc({writer:t,value:r}){t.writeLine("<<<EOT"),t.writeNoIndent(r),t.newLine(),t.writeNoIndent("EOT")}writeClass({writer:t,class_:r}){t.writeNode(new Dne({classReference:r.reference,arguments_:[e.map({entries:r.fields.map(n=>({key:e.string(n.name),value:n.value}))})]}))}writeList({writer:t,list:r}){let n=lDm({values:r.values});if(n.length===0){t.write("[]");return}t.writeLine("["),t.indent();for(let i of n)i.write(t),t.writeLine(",");t.dedent(),t.write("]")}writeMap({writer:t,map:r}){let n=cDm({entries:r.entries});if(n.length===0){t.write("[]");return}t.writeLine("["),t.indent();for(let i of n)i.key.write(t),t.write(" => "),i.value.write(t),t.writeLine(",");t.dedent(),t.write("]")}static list({values:t}){return new this({type:"list",values:t})}static boolean(t){return new this({type:"boolean",value:t})}static class_({reference:t,fields:r}){return new this({type:"class",reference:t,fields:r})}static file(t,r){return new this({type:"file",value:t,namespace:r})}static float(t){return new this({type:"float",value:t})}static datetime(t){return new this({type:"datetime",value:t})}static number(t){return new this({type:"number",value:t})}static map({entries:t}){return new this({type:"map",entries:t})}static reference(t){return new this({type:"reference",value:t})}static string(t){return new this({type:"string",value:t})}static unknown(t){return new this({type:"unknown",value:t})}static null(){return new this({type:"null"})}static nop(){return new this({type:"nop"})}static isNop(t){return t.internalType.type==="nop"}writeUnknown({writer:t,value:r}){switch(typeof r){case"boolean":t.write(r.toString());return;case"string":t.write(r.includes('"')?`\`${r}\``:`"${r}"`);return;case"number":t.write(r.toString());return;case"object":if(r==null){t.write("null");return}if(Array.isArray(r)){this.writeUnknownArray({writer:t,value:r});return}this.writeUnknownMap({writer:t,value:r});return;default:throw new Error(`Internal error; unsupported unknown type: ${typeof r}`)}}writeUnknownArray({writer:t,value:r}){if(r.length===0){t.write("[]");return}t.writeLine("["),t.indent();for(let n of r)t.writeNode(e.unknown(n)),t.writeLine(",");t.dedent(),t.write("]")}writeUnknownMap({writer:t,value:r}){let n=Object.entries(r);if(n.length===0){t.write("[]");return}t.writeLine("["),t.indent();for(let[i,o]of n)t.write(`'${i}' => `),t.writeNode(e.unknown(o)),t.writeLine(",");t.dedent(),t.write("]")}};function aDm({writer:e,value:t}){return new Dne({classReference:new xC({name:"DateTime",namespace:""}),arguments_:[new uP(`'${t}'`)]})}function uDm({writer:e,value:t,namespace:r}){return new dfe({on:new xC({name:"File",namespace:r!=null?`${r}\\Utils`:`${e.rootNamespace}\\Utils`}),method:"createFromString",arguments_:[new uP(`"${t}"`),new uP(`"${t}"`)],static_:!0})}function cDm({entries:e}){return e.filter(t=>!F7.isNop(t.key)&&!F7.isNop(t.value))}function lDm({values:e}){return e.filter(t=>!F7.isNop(t))}var N7=class e extends El{internalType;constructor(t){super(),this.internalType=t}write(t,{comment:r}={}){switch(this.internalType.type){case"int":t.write("int");break;case"string":t.write("string");break;case"bool":t.write("bool");break;case"float":t.write("float");break;case"date":t.addReference(_Yu),t.write("DateTime");break;case"dateTime":t.addReference(_Yu),t.write("DateTime");break;case"mixed":t.write("mixed");break;case"object":t.write("object");break;case"array":if(!r){t.write("array");break}t.write("array<"),this.internalType.value.write(t,{comment:r}),t.write(">");break;case"map":{if(!r){t.write("array");break}t.write("array<"),this.internalType.keyType.write(t,{comment:r}),t.write(", "),this.internalType.valueType.write(t,{comment:r}),t.write(">");break}case"null":{t.write("null");break}case"typeDict":{if(!r){t.write("array");break}if(this.internalType.multiline){t.writeLine("array{");let n=this.internalType.entries.filter(s=>!s.valueType.isOptional()),i=this.internalType.entries.filter(s=>s.valueType.isOptional()),o=[...n,...i];for(let s of o)t.write(" * "),this.writeTypeDictEntry({writer:t,entry:s,comment:r}),t.writeLine(",");t.write(" * }");break}t.write("array{"),this.internalType.entries.forEach((n,i)=>{i>0&&t.write(", "),this.writeTypeDictEntry({writer:t,entry:n,comment:r})}),t.write("}");break}case"union":{this.writeUnion({writer:t,unionTypes:this.internalType.types,comment:r});break}case"optional":{let n=this.internalType.value.internalType,i=n.type==="mixed",o=n.type==="union";!o&&!i&&t.write("?"),this.internalType.value.write(t,{comment:r}),o&&!this.unionHasOptional(n.types)&&(t.write("|"),t.writeNode(e.null()));break}case"reference":if(r){t.writeNode(this.internalType.value);let n=this.internalType.value.generics;n&&n.length>0&&(t.write("<"),n.forEach((i,o)=>{o>0&&t.write(", "),i.write(t,{comment:r})}),t.write(">"))}else t.writeNode(this.internalType.value);break;case"enumString":r?(t.write("value-of<"),t.writeNode(this.internalType.value),t.write(">")):t.write("string");break;case"literal":if(r)t.writeNode(this.internalType.value);else switch(this.internalType.value.internalType.type){case"string":t.write("string");break;case"boolean":t.write("bool");break;default:Be(this.internalType.value.internalType)}break;default:Be(this.internalType)}}toOptionalIfNotAlready(){return this.internalType.type==="optional"?this:e.optional(this)}underlyingTypeIfOptional(){if(this.internalType.type==="optional")return this.internalType.value}underlyingType(){return this.underlyingTypeIfOptional()??this}isOptional(){return this.internalType.type==="optional"}getClassReference(){switch(this.internalType.type){case"date":case"dateTime":return new xC({name:"DateTime",namespace:""});case"enumString":case"reference":return this.internalType.value;case"int":case"string":case"bool":case"float":case"object":case"map":case"array":case"null":case"mixed":case"optional":case"typeDict":case"union":case"literal":throw new Error("Cannot get class reference for "+this.internalType.type);default:Be(this.internalType)}}static int(){return new this({type:"int"})}static string(){return new this({type:"string"})}static bool(){return new this({type:"bool"})}static float(){return new this({type:"float"})}static date(){return new this({type:"date"})}static dateTime(){return new this({type:"dateTime"})}static mixed(){return new this({type:"mixed"})}static object(){return new this({type:"object"})}static array(t){return new this({type:"array",value:t})}static map(t,r){return new this({type:"map",keyType:t,valueType:r})}static typeDict(t,{multiline:r}={}){return new this({type:"typeDict",entries:t,multiline:r})}static union(t){let r=this.flattenUnionTypes(t),n=uze(r,z0);return new this({type:"union",types:n})}static flattenUnionTypes(t){let r=[];for(let n of t)n.internalType.type==="union"?r.push(...this.flattenUnionTypes(n.internalType.types)):r.push(n);return r}static optional(t){return this.isAlreadyOptional(t)?t:new this({type:"optional",value:t})}static null(){return new this({type:"null"})}static reference(t){return new this({type:"reference",value:t})}static enumString(t){return new this({type:"enumString",value:t})}static literalString(t){return new this({type:"literal",value:F7.string(t)})}static literalBoolean(t){return new this({type:"literal",value:F7.boolean(t)})}static isAlreadyOptional(t){return t.internalType.type==="optional"}writeUnion({writer:t,unionTypes:r,comment:n}){let i=this.getUniqueTypes({types:r,comment:n,writer:t}),o=this.unwrapOptionalTypes(i),s=o.filter(a=>a.underlyingType().internalType.type==="mixed").length>0;if(s&&!n){t.write("mixed");return}if(o.length>0&&n){t.writeLine("("),o.forEach((a,u)=>{u>0?t.write(" * |"):t.write(" * "),s&&(a=a.underlyingType()),a.write(t,{comment:n}),t.writeLine(),u++}),t.write(" * )");return}o.forEach((a,u)=>{u>0&&t.write("|"),s&&(a=a.underlyingType()),a.write(t,{comment:n}),u++})}writeTypeDictEntry({writer:t,entry:r,comment:n}){t.write(r.key),r.optional&&t.write("?"),t.write(": "),r.valueType.write(t,{comment:n})}getUniqueTypes({writer:t,types:r,comment:n}){let i=uze(r,z0),o=new Set;return i.filter(s=>{let a=s.toString({namespace:t.namespace,rootNamespace:t.rootNamespace,customConfig:t.customConfig,comment:n});return o.has(a)?!1:(o.add(a),!0)})}unwrapOptionalTypes(t){let r=!1,n=t.map(i=>i.internalType.type==="optional"?(r=!0,i.internalType.value):i);return r&&n.push(e.null()),n}unionHasOptional(t){return t.filter(r=>r.internalType.type==="optional").length>0}toString({namespace:t,rootNamespace:r,customConfig:n,comment:i}){let o=new Pne({namespace:t,rootNamespace:r,customConfig:n});return this.write(o,{comment:i??!1}),o.toString()}},_Yu=new xC({namespace:"",name:"DateTime"});function SYu(e){return e.startsWith("$")?e.slice(1):e}var hmo="values",OMe=class extends El{name;namespace;constructorAccess;class_;constructor({name:t,namespace:r,abstract:n,docs:i,parentClassReference:o,traits:s,constructorAccess:a}){super(),this.name=t,this.namespace=r,this.constructorAccess=a??"public",this.class_=new pfe({name:t,namespace:r,abstract:n,docs:i,parentClassReference:o,traits:s})}addField(t){this.class_.addField(t)}addMethod(t){this.class_.addMethod(t)}addTrait(t){this.class_.addTrait(t)}write(t){let r=LSe(this.class_.fields).map(n=>({...n,name:SYu(n.name)}));this.class_.addConstructor({access:this.constructorAccess,parameters:this.getConstructorParameters({orderedFields:r}),body:rn.codeblock(n=>{if(r.length>0)for(let i of r)n.write(`$this->${i.name} = $${hmo}['${i.name}']`),i.type.isOptional()?n.write(" ?? null"):i.initializer!=null&&(n.write(" ?? "),i.initializer.write(n)),n.write(";");else n.writeLine(`unset($${hmo});`)})}),this.class_.write(t)}allFieldsAreOptional(){return this.class_.fields.every(t=>t.type.isOptional()||t.initializer!=null)}getConstructorParameters({orderedFields:t}){return[new ffe({name:hmo,type:N7.typeDict(t.map(r=>({key:r.name,valueType:r.type,optional:r.type.isOptional()||r.initializer!=null})),{multiline:!0}),initializer:this.allFieldsAreOptional()?new uP("[]"):void 0})]}};var TMe=class extends El{entries;constructor({entries:t}){super(),this.entries=t??[]}write(t){t.write("["),this.entries.forEach((r,n)=>{n>0&&t.write(", "),r.write(t)}),t.write("]")}};var PMe=class extends El{reference;arguments;constructor(t){super(),this.reference=t.reference,this.arguments=t.arguments??[]}write(t){t.addReference(this.reference),t.write(`${this.reference.name}`),this.arguments.length>0&&(t.write("("),this.arguments.forEach((r,n)=>{n>0&&t.write(","),typeof r=="string"?t.write(r):r.write(t)}),t.write(")"))}};var mfe=class extends El{name;access;parameters;throws;return_;body;docs;classReference;static_;noBody;constructor({name:t,access:r,parameters:n,throws:i,return_:o,body:s,docs:a,classReference:u,static_:c,noBody:l}){super(),this.name=t,this.access=r,this.parameters=n,this.throws=i??[],this.return_=o,this.body=s,this.docs=a,this.classReference=u,this.static_=c??!1,this.noBody=l??!1}write(t){this.writeComment(t),t.write(`${this.access}${this.static_?" static":""} function ${this.name}(`);let r=this.parameters.filter(o=>!o.type.isOptional()),n=this.parameters.filter(o=>o.type.isOptional());[...r,...n].forEach((o,s)=>{s>0&&t.write(", "),o.write(t)}),t.write("): "),this.return_!=null?t.writeNodeOrString(this.return_):t.write("void"),this.noBody?t.writeTextStatement(""):(t.writeLine(" {"),t.indent(),this.body?.write(t),t.dedent(),t.writeLine("}"))}writeComment(t){let r=new tF({docs:this.docs});for(let n of this.parameters)r.addTag({tagType:"param",type:n.type,name:n.name,docs:n.docs});this.return_!=null&&this.return_!==EYu&&this.return_!==vYu&&r.addTag({tagType:"return",type:this.return_});for(let n of this.throws)r.addTag({tagType:"throws",type:N7.reference(n)});t.writeNode(r)}};var DMe=class extends El{name;namespace;backing;docs;members=[];serializable;constructor({name:t,namespace:r,backing:n,docs:i,serializable:o}){super(),this.name=t,this.namespace=r,this.backing=n,this.docs=i,this.serializable=o??!1}addMember(t){this.members.push(t)}write(t){this.writeComment(t),t.write("enum "),t.writeLine(`${this.name}`),this.backing!=null&&t.write(` : ${this.backing}`),this.serializable&&(t.addReference(new xC({name:"JsonSerializable",namespace:""})),t.writeLine(" implements JsonSerializable")),t.writeLine(" {"),t.indent();for(let r of this.members){if(t.write(`case ${r.name}`),r.value!=null)if(typeof r.value=="string"){let n=gmo(r.value);t.write(` = "${n}"`)}else t.write(` = ${r.value}`);t.writeTextStatement("")}this.serializable&&(t.newLine(),t.writeNode(new mfe({name:"jsonSerialize",return_:N7.string(),access:"public",parameters:[],body:new uP("return $this->value;")}))),t.writeNewLineIfLastLineNot(),t.dedent(),t.writeLine("}")}writeComment(t){if(this.docs==null)return;new tF({docs:this.docs}).write(t)}};var RMe=class extends El{name;type;access;readonly_;initializer;docs;inlineDocs;attributes;inherited;constructor({name:t,type:r,access:n,readonly_:i,initializer:o,docs:s,inlineDocs:a,attributes:u,inherited:c}){super(),this.name=jSe(t),this.type=r,this.access=n,this.readonly_=i??!1,this.initializer=o,this.docs=s,this.inlineDocs=a,this.attributes=u??[],this.inherited=c??!1}write(t){this.writeComment(t),this.writeAttributesIfPresent(t),t.write(`${this.access} `),this.readonly_&&t.write("readonly "),this.type.write(t),t.write(` ${this.name}`),this.initializer!=null&&(t.write(" = "),this.initializer.write(t)),t.write(";"),this.inlineDocs!=null&&t.write(` // ${this.inlineDocs}`),t.newLine()}writeComment(t){let r=new tF;r.addTag({tagType:"var",type:this.type,name:this.name,docs:this.docs}),r.write(t)}writeAttributesIfPresent(t){this.attributes.length>0&&(t.write("#["),this.attributes.forEach((r,n)=>{n>0&&t.write(", "),r.write(t)}),t.writeLine("]"))}};var FMe=class extends El{name;namespace;docs;extends_;methods=[];constructor({name:t,namespace:r,docs:n,extends_:i}){super(),this.name=t,this.namespace=r,this.docs=n,this.extends_=i??[]}addMethod(t){this.methods.push(t)}addMethods(t){this.methods.push(...t)}write(t){t.addReference(new xC({name:this.name,namespace:this.namespace})),this.writeComment(t),t.write(`interface ${this.name} `),this.extends_.length>0&&(t.write("extends "),this.extends_.forEach((r,n)=>{n>0&&t.write(", "),t.writeNode(r)}),t.write(" ")),t.newLine(),t.writeLine("{"),t.indent(),this.writeMethods({writer:t,methods:this.methods}),t.dedent(),t.writeLine("}")}writeComment(t){if(this.docs==null)return;new tF({docs:this.docs}).write(t)}writeMethods({writer:t,methods:r}){r.forEach((n,i)=>{i>0&&t.newLine(),n.write(t),t.writeNewLineIfLastLineNot()})}};var NMe=class extends El{entries;multiline;constructor({entries:t,multiline:r}){super(),this.entries=t??[],this.multiline=r??!1}write(t){if(this.multiline){this.writeMultiline(t);return}this.writeCompact(t)}writeMultiline(t){t.writeLine("["),t.indent();for(let{key:r,value:n}of this.entries)r.write(t),t.write(" => "),n.write(t),t.writeLine(",");t.dedent(),t.write("]")}writeCompact(t){t.write("[");for(let[r,{key:n,value:i}]of this.entries.entries())r>0&&t.write(", "),n.write(t),t.write(" => "),i.write(t);t.write("]")}};var kMe=class extends El{name;namespace;docs;traits;fields=[];methods=[];constructor({name:t,namespace:r,docs:n,traits:i}){super(),this.name=t,this.namespace=r,this.docs=n,this.traits=i??[]}addField(t){this.fields.push(t)}addMethod(t){this.methods.push(t)}write(t){this.writeComment(t),t.write(`trait ${this.name} `),t.newLine(),t.writeLine("{"),t.indent(),this.traits.length>0&&(t.write("use "),this.traits.forEach((r,n)=>{n>0&&t.write(","),t.writeNode(r)}),t.writeTextStatement(""),t.newLine()),this.writeFields({writer:t,fields:LSe(this.fields)}),this.fields.length>0&&this.methods.length>0&&t.newLine(),this.writeMethods({writer:t,methods:LSe(this.methods)}),t.dedent(),t.writeLine("}")}writeComment(t){let r=new tF({docs:this.docs});for(let n of this.fields)r.addTag({tagType:"property",type:n.type,name:n.name});r.write(t)}writeFields({writer:t,fields:r}){r.forEach((n,i)=>{i>0&&t.newLine(),n.write(t),t.writeNewLineIfLastLineNot()})}writeMethods({writer:t,methods:r}){r.forEach((n,i)=>{i>0&&t.newLine(),n.write(t),t.writeNewLineIfLastLineNot()})}};var vMn=class extends El{arrays;constructor(t){super(),this.arrays=t}write(t){t.write("array_merge"),Xft({writer:t,arguments_:this.arrays.map(r=>QMe(n=>{if(typeof r=="string"||r instanceof El){n.writeNodeOrString(r);return}n.writeNodeOrString(r.ref),r.fallback&&(n.write(" ?? "),n.writeNodeOrString(r.fallback))}))})}};function pDm(e){return new TMe(e)}function fDm(e){return new PMe(e)}function dDm(e){return new pfe(e)}function mDm(e){return new kMe(e)}function hDm(e){return new FMe(e)}function gDm(e){return new xC(e)}function QMe(e){return new uP(e)}function ADm(e){return new OMe(e)}function yDm(e){return new DMe(e)}function bDm(e){return new RMe(e)}function BYu(e){return new Dne(e)}function EDm(e){return new dfe(e)}function vDm(e){return QMe(t=>{t.write("throw "),t.writeNode(BYu(e))})}function IDm(e){return new NMe(e)}function wDm(e){return new mfe(e)}function CDm(e){return new ffe(e)}function xDm(e){return new eMe(e)}function _Dm(e,t){return QMe(r=>{r.writeNodeOrString(e),r.write(" = "),r.writeNodeOrString(t)})}function SDm(e){return QMe(jSe(e))}function BDm(e){return QMe(`"${e}"`)}function ODm(...e){return new vMn(e)}function gmo(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\$/g,"\\$")}function TDm(){return new uP(e=>{e.write("$this")})}function Amo(e){return IYu.has(e.toLowerCase())?`${e}_`:e}Bi();St();var IMn=class{context;constructor({context:t}){this.context=t}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?rn.TypeLiteral.null():(this.context.errors.add({severity:Ir.Critical,message:"Expected non-null value, but got null"}),rn.TypeLiteral.nop());if(t.value===void 0)return rn.TypeLiteral.nop();switch(t.typeReference.type){case"list":case"set":return this.convertList({list:t.typeReference.value,value:t.value});case"literal":return this.convertLiteral({literalType:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value});case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?rn.TypeLiteral.nop():this.convertNamed({named:r,value:t.value,as:t.as})}case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as});case"unknown":return this.convertUnknown({value:t.value});default:Be(t.typeReference)}}convertLiteral({literalType:t,value:r}){switch(t.type){case"boolean":{let n=this.context.getValueAsBoolean({value:r});return n==null?rn.TypeLiteral.nop():rn.TypeLiteral.boolean(n)}case"string":{let n=this.context.getValueAsString({value:r});return n==null?rn.TypeLiteral.nop():rn.TypeLiteral.string(n)}default:Be(t)}}convertList({list:t,value:r}){return Array.isArray(r)?rn.TypeLiteral.list({values:r.map((n,i)=>{this.context.errors.scope({index:i});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),rn.TypeLiteral.nop())}convertMap({map:t,value:r}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),rn.TypeLiteral.nop()):rn.TypeLiteral.map({entries:Object.entries(r).map(([n,i])=>{this.context.errors.scope(n);try{return{key:this.convert({typeReference:t.key,value:n,as:"key"}),value:this.convert({typeReference:t.value,value:i})}}finally{this.context.errors.unscope()}})})}convertNamed({named:t,value:r,as:n}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference,value:r,as:n});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:r});case"enum":return this.convertEnum({enum_:t,value:r});case"object":return this.convertObject({object_:t,value:r});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r});default:Be(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r}){let n=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(n==null)return rn.TypeLiteral.nop();let i=n.singleDiscriminatedUnionType,o=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:n,unionVariant:i});return o==null?rn.TypeLiteral.nop():rn.TypeLiteral.reference(rn.codeblock(s=>{s.writeNode(rn.invokeMethod({on:rn.classReference({name:this.context.getClassName(t.declaration.name),namespace:this.context.getTypesNamespace(t.declaration.fernFilepath)}),method:this.context.getMethodName(i.discriminantValue.name),arguments_:this.convertDiscriminatedUnionVariantArgs({discriminatedUnionTypeInstance:n,unionVariant:i,unionProperties:o}),static_:!0}))}))}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:t,unionVariant:r}){switch(r.type){case"samePropertiesAsObject":{let n=this.context.resolveNamedType({typeId:r.typeId});if(n==null)return;let i=this.convertNamed({named:n,value:t.value});if(!i.isClass()){this.context.errors.add({severity:Ir.Critical,message:"Internal error; expected union value to be an object"});return}return i.asClassOrThrow().fields}case"singleProperty":try{this.context.errors.scope(r.discriminantValue.wireValue);let n=this.context.getRecord(t.value);return n==null?[{name:this.context.getPropertyName(r.discriminantValue.name),value:this.convert({typeReference:r.typeReference,value:t.value})}]:[{name:this.context.getPropertyName(r.discriminantValue.name),value:this.convert({typeReference:r.typeReference,value:n[r.discriminantValue.wireValue]})}]}finally{this.context.errors.unscope()}case"noProperties":return[];default:Be(r)}}convertDiscriminatedUnionVariantArgs({discriminatedUnionTypeInstance:t,unionVariant:r,unionProperties:n}){let i=this.getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r});if(r.type==="singleProperty"&&this.context.getRecord(t.value)==null&&n.length===1)return[...i,this.convert({typeReference:r.typeReference,value:t.value})];if(r.type==="samePropertiesAsObject"){let o=this.context.resolveNamedType({typeId:r.typeId});return o==null?[]:[...i,rn.TypeLiteral.class_({reference:rn.classReference({name:this.context.getClassName(o.declaration.name),namespace:this.context.getTypesNamespace(o.declaration.fernFilepath)}),fields:n})]}return i}getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r}){return this.context.associateByWireValue({parameters:r.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(i=>{this.context.errors.scope(i.name.wireValue);try{return this.convert(i)}finally{this.context.errors.unscope()}})}convertObject({object_:t,value:r}){let n=this.context.getRecord(r)??{},o=this.context.associateByWireValue({parameters:t.properties,values:n}).map(a=>{this.context.errors.scope(a.name.wireValue);try{return{name:this.context.getPropertyName(a.name.name),value:this.convert(a)}}finally{this.context.errors.unscope()}}),s=new Set(Object.keys(n));for(let a of t.properties)if(!s.has(a.name.wireValue)&&!this.isOptionalOrNullable(a.typeReference)){let u=this.generatePlaceholderValue(a.typeReference);rn.TypeLiteral.isNop(u)||o.push({name:this.context.getPropertyName(a.name.name),value:u})}return rn.TypeLiteral.class_({reference:rn.classReference({name:this.context.getClassName(t.declaration.name),namespace:this.context.getTypesNamespace(t.declaration.fernFilepath)}),fields:o})}isOptionalOrNullable(t){return this.context.isOptional(t)||this.context.isNullable(t)}generatePlaceholderValue(t){switch(t.type){case"primitive":return this.generatePrimitivePlaceholder(t.value);case"list":case"set":{let r=this.generatePlaceholderValue(t.value);return rn.TypeLiteral.isNop(r)?rn.TypeLiteral.list({values:[]}):rn.TypeLiteral.list({values:[r]})}case"map":{let r=this.generatePlaceholderValue(t.key),n=this.generatePlaceholderValue(t.value);return rn.TypeLiteral.isNop(r)||rn.TypeLiteral.isNop(n)?rn.TypeLiteral.map({entries:[]}):rn.TypeLiteral.map({entries:[{key:r,value:n}]})}case"named":{let r=this.context.resolveNamedType({typeId:t.value});return r==null?rn.TypeLiteral.nop():this.generateNamedPlaceholder(r)}case"optional":case"nullable":return rn.TypeLiteral.null();case"literal":return this.generateLiteralPlaceholder(t.value);case"unknown":return rn.TypeLiteral.null();default:Be(t)}}generatePrimitivePlaceholder(t){switch(t){case"INTEGER":case"LONG":case"UINT":case"UINT_64":return rn.TypeLiteral.number(1);case"FLOAT":case"DOUBLE":return rn.TypeLiteral.float(1);case"BOOLEAN":return rn.TypeLiteral.boolean(!0);case"STRING":return rn.TypeLiteral.string("value");case"DATE":return rn.TypeLiteral.datetime("2024-01-01");case"DATE_TIME":return rn.TypeLiteral.datetime("2024-01-01T00:00:00Z");case"UUID":return rn.TypeLiteral.string("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32");case"BASE_64":return rn.TypeLiteral.string("SGVsbG8=");case"BIG_INTEGER":return rn.TypeLiteral.string("1000000");default:Be(t)}}generateNamedPlaceholder(t){switch(t.type){case"alias":return this.generatePlaceholderValue(t.typeReference);case"enum":{let r=t.values[0];return r==null?rn.TypeLiteral.nop():rn.TypeLiteral.reference(rn.codeblock(n=>{n.writeNode(rn.classReference({name:this.context.getClassName(t.declaration.name),namespace:this.context.getTypesNamespace(t.declaration.fernFilepath)})),n.write("::"),n.write(this.context.getClassName(r.name)),n.write("->value")}))}case"object":return this.convertObject({object_:t,value:{}});case"discriminatedUnion":return Object.values(t.types)[0]==null?rn.TypeLiteral.nop():rn.TypeLiteral.nop();case"undiscriminatedUnion":{let r=t.types[0];return r==null?rn.TypeLiteral.nop():this.generatePlaceholderValue(r)}default:Be(t)}}generateLiteralPlaceholder(t){switch(t.type){case"boolean":return rn.TypeLiteral.boolean(t.value);case"string":return rn.TypeLiteral.string(t.value);default:Be(t)}}convertEnum({enum_:t,value:r}){let n=this.getEnumValueName({enum_:t,value:r});return n==null?rn.TypeLiteral.nop():rn.TypeLiteral.reference(rn.codeblock(i=>{i.writeNode(rn.classReference({name:this.context.getClassName(t.declaration.name),namespace:this.context.getTypesNamespace(t.declaration.fernFilepath)})),i.write("::"),i.write(n),i.write("->value")}))}getEnumValueName({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Ir.Critical,message:`Expected enum value string, got: ${typeof r}`});return}let n=t.values.find(i=>i.wireValue===r);if(n==null){this.context.errors.add({severity:Ir.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return this.context.getClassName(n.name)}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r}){let n=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r});return n??rn.TypeLiteral.nop()}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r}){for(let n of t.types){let i=this.context.errors.size();try{let o=this.convert({typeReference:n,value:r});if(rn.TypeLiteral.isNop(o)){this.context.errors.truncate(i);continue}return o}catch{this.context.errors.truncate(i);continue}}this.context.errors.add({severity:Ir.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}convertUnknown({value:t}){return rn.TypeLiteral.unknown(t)}convertPrimitive({primitive:t,value:r,as:n}){switch(t){case"INTEGER":case"LONG":case"UINT":case"UINT_64":{let i=this.getValueAsNumber({value:r,as:n});return i==null?rn.TypeLiteral.nop():rn.TypeLiteral.number(i)}case"FLOAT":case"DOUBLE":{let i=this.getValueAsNumber({value:r});return i==null?rn.TypeLiteral.nop():rn.TypeLiteral.float(i)}case"BOOLEAN":{let i=this.getValueAsBoolean({value:r,as:n});return i==null?rn.TypeLiteral.nop():rn.TypeLiteral.boolean(i)}case"DATE":case"DATE_TIME":{let i=this.context.getValueAsString({value:r});return i==null?rn.TypeLiteral.nop():rn.TypeLiteral.datetime(i)}case"BASE_64":case"UUID":case"BIG_INTEGER":case"STRING":{let i=this.context.getValueAsString({value:r});return i==null?rn.TypeLiteral.nop():rn.TypeLiteral.string(i)}default:Be(t)}}getValueAsNumber({value:t,as:r}){let n=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:n})}};St();var wMn=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({body:t,value:r}){let n={fileFields:[],bodyPropertyFields:[]},i=this.context.getRecord(r)??{};for(let o of t.properties)switch(o.type){case"file":n.fileFields.push({name:this.context.getPropertyName(o.name),value:this.getSingleFileProperty({property:o,record:i})});break;case"fileArray":n.fileFields.push({name:this.context.getPropertyName(o.name),value:this.getArrayFileProperty({property:o,record:i})});break;case"bodyProperty":n.bodyPropertyFields.push({name:this.context.getPropertyName(o.name.name),value:this.getBodyProperty({property:o,record:i})});break;default:Be(o)}return n}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r});return n==null&&(n=`example_${t.wireValue??"file"}`),rn.TypeLiteral.file(n,this.context.rootNamespace)}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});if(n==null){let i=`example_${t.wireValue??"files"}`;return rn.TypeLiteral.list({values:[rn.TypeLiteral.file(i,this.context.rootNamespace)]})}return rn.TypeLiteral.list({values:n.map(i=>rn.TypeLiteral.file(i,this.context.rootNamespace))})}getBodyProperty({property:t,record:r}){let n=r[t.name.wireValue];return n==null?rn.TypeLiteral.nop():this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:n})}};var PDm=["use","clone","list"],DDm="Requests",RDm="Types",CMn=class e extends $v{ir;customConfig;dynamicTypeLiteralMapper;filePropertyMapper;rootNamespace;constructor({ir:t,config:r}){super({ir:t,config:r}),this.ir=t,this.customConfig=r.customConfig!=null?r.customConfig:void 0,this.dynamicTypeLiteralMapper=new IMn({context:this}),this.filePropertyMapper=new wMn({context:this}),this.rootNamespace=FDm({organization:r.organization,namespaceOverride:this.customConfig?.namespace})}clone(){return new e({ir:this.ir,config:this.config})}getParameterName(t){return this.prependUnderscoreIfNeeded(t.camelCase.unsafeName)}getPropertyName(t){return this.prependUnderscoreIfNeeded(t.camelCase.unsafeName)}getMethodName(t){let r=t.camelCase.unsafeName;return PDm.includes(r)?r:t.camelCase.safeName}getClassName(t){return Amo(t.pascalCase.safeName)}getRootClientClassName(){return this.customConfig?.clientName!=null?this.customConfig.clientName:this.customConfig?.["client-class-name"]!=null?this.customConfig?.["client-class-name"]:this.getComputedClientName()}getEnvironmentsClassReference(){return rn.classReference({name:"Environments",namespace:this.rootNamespace})}getRequestNamespace(t){return this.getNamespace(t,DDm)}getTypesNamespace(t){return this.getNamespace(t,RDm)}getNamespace(t,r){let n=t.allParts.map(i=>i.pascalCase.safeName);return n=r!=null?[...n,r]:n,[this.rootNamespace,...n].join("\\")}getEnvironmentClassAccessFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return rn.codeblock(n=>{n.writeNode(this.getEnvironmentClassReference(r)),n.write("::"),n.write(this.getClassName(r))})}getEnvironmentClassReference(t){return rn.classReference({name:"Environments",namespace:this.rootNamespace})}prependUnderscoreIfNeeded(t){return/^[a-zA-Z_]/.test(t)?t:`_${t}`}getComputedClientName(){return`${this.getOrganizationPascalCase()}Client`}getOrganizationPascalCase(){return`${gc(qn(this.config.organization))}`}};function FDm({organization:e,namespaceOverride:t}){return t??`${gc(qn(e))}`}St();var OYu="$client",xMn="Example",TYu=`<?php
2544
2544
 
2545
- `,_Mn=class{context;constructor({context:t}){this.context=t}async generateSnippet({endpoint:t,request:r}){let n=this.buildCodeBlock({endpoint:t,snippet:r});return TYu+await n.toStringAsync({namespace:xMn,rootNamespace:xMn,customConfig:this.context.customConfig??{}})}generateSnippetSync({endpoint:t,request:r}){let n=this.buildCodeBlock({endpoint:t,snippet:r});return TYu+n.toString({namespace:xMn,rootNamespace:xMn,customConfig:this.context.customConfig??{}})}async generateSnippetAst({endpoint:t,request:r,options:n}){return n?.skipClientInstantiation?this.buildCodeBlockWithoutClient({endpoint:t,snippet:r}):this.buildCodeBlock({endpoint:t,snippet:r})}buildCodeBlock({endpoint:t,snippet:r}){return rn.codeblock(n=>{n.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),n.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))})}buildCodeBlockWithoutClient({endpoint:t,snippet:r}){return rn.codeblock(n=>{n.writeNodeStatement(this.callMethodOnExistingClient({endpoint:t,snippet:r}))})}constructClient({endpoint:t,snippet:r}){return rn.codeblock(n=>{n.write(`${OYu} = `),n.writeNode(this.getRootClientClassInstantiation(this.getConstructorArgs({endpoint:t,snippet:r})))})}callMethod({endpoint:t,snippet:r}){return rn.invokeMethod({on:rn.codeblock(OYu),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:r}),multiline:!0})}callMethodOnExistingClient({endpoint:t,snippet:r}){let n=this.getMethodArgs({endpoint:t,snippet:r}),i=this.getRequestOptions({endpoint:t,snippet:r});return rn.TypeLiteral.isNop(i)||n.push(i),rn.invokeMethod({on:rn.codeblock("$this->client"),method:this.getMethod({endpoint:t}),arguments_:n,multiline:!0})}getRequestOptions({endpoint:t,snippet:r}){let n=r.headers??{},i=Object.entries(n);if(i.length===0)return rn.TypeLiteral.nop();let o=new Set;if(this.context.ir.headers!=null)for(let a of this.context.ir.headers)o.add(a.name.wireValue.toLowerCase());if(t.request.type==="inlined"&&t.request.headers!=null)for(let a of t.request.headers)o.add(a.name.wireValue.toLowerCase());let s=i.filter(([a])=>!o.has(a.toLowerCase()));return s.length===0?rn.TypeLiteral.nop():rn.TypeLiteral.map({entries:[{key:rn.TypeLiteral.string("headers"),value:rn.TypeLiteral.map({entries:s.map(([a,u])=>({key:rn.TypeLiteral.string(a),value:rn.TypeLiteral.string(String(u))}))})}]})}getConstructorArgs({endpoint:t,snippet:r}){let n=[];if(t.auth!=null)if(r.auth!=null)n.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth}));else if(t.auth.type==="inferred"){let u={values:void 0};n.push(...this.getConstructorInferredAuthArgs({auth:t.auth,values:u}))}else this.context.errors.add({severity:Ir.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`});let i=this.context.ir.environments?.environments.type==="multipleBaseUrls",o=this.getConstructorEnvironmentArg({environment:r.environment,hasMultiUrlEnvironments:i}),s=[];if(!i){let u=this.getConstructorBaseUrlArgs({baseUrl:r.baseURL,environment:r.environment});u.length>0&&s.push(...u)}this.context.errors.scope(Lo.Headers),this.context.ir.headers!=null&&r.headers!=null&&s.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope();let a=[...n];return o!=null&&a.push(o),s.length>0&&a.push({name:"options",assignment:rn.TypeLiteral.map({entries:s.map(u=>({key:rn.TypeLiteral.string(u.name),value:u.value}))})}),a}getConstructorAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?this.getConstructorBasicAuthArgs({auth:t,values:r}):[];case"bearer":return r.type==="bearer"?this.getConstructorBearerAuthArgs({auth:t,values:r}):[];case"header":return r.type==="header"?this.getConstructorHeaderAuthArgs({auth:t,values:r}):[];case"oauth":return r.type==="oauth"?this.getConstructorOAuthArgs({auth:t,values:r}):[];case"inferred":return r.type==="inferred"?this.getConstructorInferredAuthArgs({auth:t,values:r}):[];default:Be(t)}}addError(t){this.context.errors.add({severity:Ir.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getConstructorBasicAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.username),assignment:rn.TypeLiteral.string(r.username)},{name:this.context.getPropertyName(t.password),assignment:rn.TypeLiteral.string(r.password)}]}getConstructorEnvironmentArg({environment:t,hasMultiUrlEnvironments:r}){if(!r)return;let n=this.context.getEnvironmentsClassReference();if(t!=null){if(this.context.isSingleEnvironmentID(t)){let o=this.context.resolveEnvironmentName(t);if(o==null){this.addWarning(`Environment "${t}" was not found`);return}let s=this.context.getClassName(o);return{name:"environment",assignment:rn.TypeLiteral.reference(rn.codeblock(a=>{a.writeNode(n),a.write("::"),a.write(s),a.write("()")}))}}if(this.context.isMultiEnvironmentValues(t)){let o=this.resolveMultiEnvironmentName(t);if(o==null){this.addWarning("Invalid multi url environment");return}return o.type==="named"?{name:"environment",assignment:rn.TypeLiteral.reference(rn.codeblock(s=>{s.writeNode(n),s.write("::"),s.write(o.name),s.write("()")}))}:{name:"environment",assignment:rn.TypeLiteral.reference(rn.codeblock(s=>{s.writeNode(n),s.write("::custom(");let a=Object.entries(o.urls);a.forEach(([u,c],l)=>{s.write(`${u}: '${c}'`),l<a.length-1&&s.write(", ")}),s.write(")")}))}}}let i=this.getDefaultEnvironmentName();if(i!=null)return{name:"environment",assignment:rn.TypeLiteral.reference(rn.codeblock(o=>{o.writeNode(n),o.write("::"),o.write(i),o.write("()")}))}}getDefaultEnvironmentName(){if(this.context.ir.environments?.environments.type!=="multipleBaseUrls")return;let t=this.context.ir.environments.environments;if(t.type!=="multipleBaseUrls")return;let r=t.environments;if(r.length===0)return;for(let i of r){let o=this.context.getClassName(i.name);if(o==="Production")return o}let n=r[0];if(n!=null)return this.context.getClassName(n.name)}resolveMultiEnvironmentName(t){let r=Object.keys(t);if(r.length===0||!this.context.validateMultiEnvironmentUrlValues(t))return;let n=r[0];if(n==null)return;let i=t[n];if(i==null)return;let o=this.context.resolveEnvironmentName(i);if(o!=null&&r.every(u=>{let c=t[u];return c==null?!1:this.context.resolveEnvironmentName(c)!=null&&c===i}))return{type:"named",name:this.context.getClassName(o)};let s={};for(let a of r){let u=t[a];if(u==null)continue;let c=this.getBaseUrlPropertyName(a);s[c]=u}if(Object.keys(s).length>0)return{type:"custom",urls:s}}getBaseUrlPropertyName(t){if(this.context.ir.environments?.environments.type!=="multipleBaseUrls")return t;let r=this.context.ir.environments.environments;if(r.type!=="multipleBaseUrls")return t;let n=r.baseUrls.find(i=>i.id===t);return n==null?t:n.name.camelCase.safeName}getConstructorBaseUrlArgs({baseUrl:t,environment:r}){let n=this.getBaseUrlArg({baseUrl:t,environment:r});return rn.TypeLiteral.isNop(n)?[]:[{name:"baseUrl",value:n}]}getBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null)return this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"}),rn.TypeLiteral.nop();if(t!=null)return rn.TypeLiteral.string(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentClassAccessFromID(r);return n==null?(this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`}),rn.TypeLiteral.nop()):rn.TypeLiteral.reference(rn.codeblock(i=>{i.writeNode(n),i.write("->value")}))}if(this.context.ir.environments?.environments.type==="multipleBaseUrls")return rn.TypeLiteral.nop()}return rn.TypeLiteral.nop()}getConstructorBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.token),assignment:rn.TypeLiteral.string(r.token)}]}getConstructorHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.header.name.name),assignment:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value})}]}getConstructorOAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.clientId),assignment:rn.TypeLiteral.string(r.clientId)},{name:this.context.getPropertyName(t.clientSecret),assignment:rn.TypeLiteral.string(r.clientSecret)}]}getConstructorInferredAuthArgs({auth:t,values:r}){return[]}getConstructorHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getConstructorHeaderArg({header:i,value:o});s!=null&&n.push({name:this.context.getPropertyName(i.name.name),value:s})}return n}getConstructorHeaderArg({header:t,value:r}){let n=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:r});if(!rn.TypeLiteral.isNop(n))return n}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];return i.length>0&&n.push(...this.getPathParameters({namedParameters:i,snippet:r}).map(o=>o.value)),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),t.body!=null&&n.push(this.getBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope(),n}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r});default:Be(t)}}getBytesBodyRequestArg({value:t}){return this.context.errors.add({severity:Ir.Critical,message:"The PHP SDK doesn't support bytes requests yet"}),rn.TypeLiteral.nop()}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[],i=this.context.customConfig?.inlinePathParameters??!1;this.context.errors.scope(Lo.PathParameters);let o=[],s=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];s.length>0&&o.push(...this.getPathParameters({namedParameters:s,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let a=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})||n.push(...o.map(u=>u.value)),this.context.needsRequestParameter({request:t,inlinePathParameters:i,inlineFileProperties:!0})&&n.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})?o:[],filePropertyInfo:a})),n}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Lo.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicTypeLiteralMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.Headers);let u=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicTypeLiteralMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let c=t.body!=null?this.getInlinedRequestBodyConstructorFields({body:t.body,value:r.requestBody,filePropertyInfo:i}):[];return this.context.errors.unscope(),rn.TypeLiteral.class_({reference:rn.classReference({name:this.context.getClassName(t.declaration.name),namespace:this.context.getRequestNamespace(t.declaration.fernFilepath)}),fields:[...n,...s,...u,...c]})}getInlinedRequestBodyConstructorFields({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyConstructorFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyConstructorField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyConstructorFields({filePropertyInfo:n});default:Be(t)}}getFileUploadRequestBodyConstructorFields({filePropertyInfo:t}){return[...t.fileFields,...t.bodyPropertyFields]}getReferencedRequestBodyPropertyConstructorField({body:t,value:r}){return{name:this.context.getPropertyName(t.bodyKey),value:this.getReferencedRequestBodyPropertyTypeLiteral({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyTypeLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r});default:Be(t)}}getInlinedRequestBodyPropertyConstructorFields({parameters:t,value:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert(o)});return n}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:r.pathParameters??{}});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert(o)});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getPropertyName(r)).join("->")}->${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getRootClientClassInstantiation(t){return rn.instantiateClass({classReference:rn.classReference({name:this.context.getRootClientClassName(),namespace:this.context.rootNamespace}),arguments_:t,multiline:!0})}};var PLt=class extends Wv{constructor({ir:t,config:r}){super(new CMn({ir:t,config:r}))}async generate(t){return super.generate(t)}generateSync(t){return super.generateSync(t)}async generateSnippetAst(t,r){return await super.generateSnippetAst(t,r)}createSnippetGenerator(t){return new _Mn({context:t})}};var BMn=require("fs/promises"),PYu=Ae(require("path"),1);var SMn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new PLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");for(let[n,i]of r.entries())try{let o=pS(i);if(o==null)continue;let s=await this.dynamicSnippetsGenerator.generate(o),a=this.getTestFilePath({outputDir:t,idx:n});await(0,BMn.mkdir)(PYu.default.dirname(a),{recursive:!0}),await(0,BMn.writeFile)(a,s.snippet)}catch(o){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(i.endpoint)}: ${o}`)}this.context.logger.debug("Done generating dynamic snippet tests")}getTestFilePath({outputDir:t,idx:r}){return Ge(t,Se.of(`src/dynamic-snippets/example${r}/snippet.php`))}};qt();St();var fn={};Z(fn,{AccessAttribute:()=>Zft,AstNode:()=>dp,Class:()=>USe,ClassInstantiation:()=>tdt,CodeBlock:()=>hfe,Comment:()=>rdt,Decorator:()=>ndt,Field:()=>zSe,Lambda:()=>idt,LambdaParameter:()=>odt,Method:()=>qSe,MethodArgument:()=>adt,MethodInvocation:()=>udt,ModuleImport:()=>k7,Operator:()=>cdt,Parameter:()=>VSe,PythonFile:()=>ldt,Reference:()=>Fne,StarImport:()=>GSe,Type:()=>TMn,TypeInstantiation:()=>WSe,accessAttribute:()=>QDm,assign:()=>jDm,class_:()=>LDm,codeBlock:()=>WDm,comment:()=>$Dm,decorator:()=>zDm,field:()=>GDm,file:()=>MDm,instantiateClass:()=>UDm,invokeFunction:()=>YDm,invokeMethod:()=>XDm,lambda:()=>HDm,lambdaParameter:()=>KDm,method:()=>JDm,methodArgument:()=>eRm,operator:()=>tRm,parameter:()=>ZDm,reference:()=>VDm,starImport:()=>qDm});var DLt=class extends wC{fullyQualifiedModulePathsToImportedNames={};setRefNameOverrides(t){this.fullyQualifiedModulePathsToImportedNames=t}unsetRefNameOverrides(){this.fullyQualifiedModulePathsToImportedNames={}}getRefNameOverride(t){let r=this.fullyQualifiedModulePathsToImportedNames[t.getFullyQualifiedModulePath()];return r||{name:t.alias??t.name,isAlias:!!t.alias}}toString(){return this.buffer}async toStringFormatted(t){return t.format(this.buffer)}};var dp=class extends O0{references=[];addReference(t){this.references.push(t)}inheritReferences(t){t!==void 0&&t.references.forEach(r=>{this.references.includes(r)||this.addReference(r)})}getReferences(){return this.references}toString(){let t=new DLt;return this.write(t),t.toString()}async toStringFormatted(t){let r=new DLt;return this.write(r),r.toStringFormatted(t)}};var Zft=class extends dp{lhs;rhs;constructor({lhs:t,rhs:r}){super(),this.lhs=t,this.inheritReferences(t),this.rhs=r,this.inheritReferences(r)}write(t){this.lhs.write(t),t.write("."),this.rhs.write(t)}};var OMn=class extends dp{lhs;rhs;constructor({lhs:t,rhs:r}){super(),this.lhs=t,this.inheritReferences(t),this.rhs=r,this.inheritReferences(r)}write(t){this.lhs.write(t),t.write(" = "),this.rhs.write(t)}};var edt=class extends dp{reference;arguments;multiline;constructor({reference:t,arguments_:r,multiline:n}){super(),this.reference=t,this.arguments=r,this.multiline=n??!1,this.inheritReferences(t),this.arguments.forEach(i=>{this.inheritReferences(i)})}write(t){if(this.reference.write(t),this.arguments.length===0){t.write("()");return}t.write("("),this.multiline&&(t.newLine(),t.indent()),this.arguments.forEach((r,n)=>{r.write(t),n<this.arguments.length-1?(t.write(","),this.multiline?t.newLine():t.write(" ")):this.multiline&&t.write(",")}),this.multiline&&(t.newLine(),t.dedent()),t.write(")")}};var USe=class extends dp{name;extends_;decorators;fields=[];docs;statements=[];constructor({docs:t,name:r,extends_:n,decorators:i}){super(),this.name=r,this.extends_=n??[],this.decorators=i??[],this.docs=t,this.extends_.forEach(o=>{this.inheritReferences(o)}),this.decorators.forEach(o=>{this.inheritReferences(o)})}write(t){this.decorators.forEach(r=>{r.write(t)}),t.write(`class ${this.name}`),this.extends_.length>0&&(t.write("("),this.extends_.forEach((r,n)=>{n>0&&t.write(", "),r.write(t)}),t.write(")")),t.write(":"),t.newLine(),t.indent(),this.docs!=null&&(t.write('"""'),t.write(this.docs),t.write('"""')),t.writeNewLineIfLastLineNot(),this.fields.forEach(r=>{r.write(t),t.writeNewLineIfLastLineNot()}),t.dedent(),t.indent(),this.statements.length?this.writeStatements({writer:t}):t.write("pass"),t.dedent()}add(t){this.statements.push(t),this.inheritReferences(t)}writeStatements({writer:t}){this.statements.forEach((r,n)=>{r.write(t),t.writeNewLineIfLastLineNot()})}addField(t){this.add(t)}};var tdt=class extends edt{constructor({classReference:t,...r}){super({reference:t,...r})}};var hfe=class extends dp{arg;constructor(t){super(),this.arg=t}write(t){return new Ly(this.arg).write(t)}};var rdt=class extends dp{docs;constructor({docs:t}){super(),this.docs=t}write(t){this.docs!=null&&this.docs.split(`
2545
+ `,_Mn=class{context;constructor({context:t}){this.context=t}async generateSnippet({endpoint:t,request:r}){let n=this.buildCodeBlock({endpoint:t,snippet:r});return TYu+await n.toStringAsync({namespace:xMn,rootNamespace:xMn,customConfig:this.context.customConfig??{}})}generateSnippetSync({endpoint:t,request:r}){let n=this.buildCodeBlock({endpoint:t,snippet:r});return TYu+n.toString({namespace:xMn,rootNamespace:xMn,customConfig:this.context.customConfig??{}})}async generateSnippetAst({endpoint:t,request:r,options:n}){return n?.skipClientInstantiation?this.buildCodeBlockWithoutClient({endpoint:t,snippet:r}):this.buildCodeBlock({endpoint:t,snippet:r})}buildCodeBlock({endpoint:t,snippet:r}){return rn.codeblock(n=>{n.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),n.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))})}buildCodeBlockWithoutClient({endpoint:t,snippet:r}){return rn.codeblock(n=>{n.writeNodeStatement(this.callMethodOnExistingClient({endpoint:t,snippet:r}))})}constructClient({endpoint:t,snippet:r}){return rn.codeblock(n=>{n.write(`${OYu} = `),n.writeNode(this.getRootClientClassInstantiation(this.getConstructorArgs({endpoint:t,snippet:r})))})}callMethod({endpoint:t,snippet:r}){return rn.invokeMethod({on:rn.codeblock(OYu),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:r}),multiline:!0})}callMethodOnExistingClient({endpoint:t,snippet:r}){let n=this.getMethodArgs({endpoint:t,snippet:r}),i=this.getRequestOptions({endpoint:t,snippet:r});return rn.TypeLiteral.isNop(i)||n.push(i),rn.invokeMethod({on:rn.codeblock("$this->client"),method:this.getMethod({endpoint:t}),arguments_:n,multiline:!0})}getRequestOptions({endpoint:t,snippet:r}){let n=r.headers??{},i=Object.entries(n);if(i.length===0)return rn.TypeLiteral.nop();let o=new Set;if(this.context.ir.headers!=null)for(let a of this.context.ir.headers)o.add(a.name.wireValue.toLowerCase());if(t.request.type==="inlined"&&t.request.headers!=null)for(let a of t.request.headers)o.add(a.name.wireValue.toLowerCase());let s=i.filter(([a])=>!o.has(a.toLowerCase()));return s.length===0?rn.TypeLiteral.nop():rn.TypeLiteral.map({entries:[{key:rn.TypeLiteral.string("headers"),value:rn.TypeLiteral.map({entries:s.map(([a,u])=>({key:rn.TypeLiteral.string(a),value:rn.TypeLiteral.string(String(u))}))})}]})}getConstructorArgs({endpoint:t,snippet:r}){let n=[];if(t.auth!=null)if(r.auth!=null)n.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth}));else if(t.auth.type==="inferred"){let u={values:void 0};n.push(...this.getConstructorInferredAuthArgs({auth:t.auth,values:u}))}else this.context.errors.add({severity:Ir.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`});let i=this.context.ir.environments?.environments.type==="multipleBaseUrls",o=this.getConstructorEnvironmentArg({environment:r.environment,hasMultiUrlEnvironments:i}),s=[];if(!i){let u=this.getConstructorBaseUrlArgs({baseUrl:r.baseURL,environment:r.environment});u.length>0&&s.push(...u)}this.context.errors.scope(Lo.Headers),this.context.ir.headers!=null&&r.headers!=null&&s.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope();let a=[...n];return o!=null&&a.push(o),s.length>0&&a.push({name:"options",assignment:rn.TypeLiteral.map({entries:s.map(u=>({key:rn.TypeLiteral.string(u.name),value:u.value}))})}),a}getConstructorAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?this.getConstructorBasicAuthArgs({auth:t,values:r}):[];case"bearer":return r.type==="bearer"?this.getConstructorBearerAuthArgs({auth:t,values:r}):[];case"header":return r.type==="header"?this.getConstructorHeaderAuthArgs({auth:t,values:r}):[];case"oauth":return r.type==="oauth"?this.getConstructorOAuthArgs({auth:t,values:r}):[];case"inferred":return r.type==="inferred"?this.getConstructorInferredAuthArgs({auth:t,values:r}):[];default:Be(t)}}addError(t){this.context.errors.add({severity:Ir.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getConstructorBasicAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.username),assignment:rn.TypeLiteral.string(r.username)},{name:this.context.getPropertyName(t.password),assignment:rn.TypeLiteral.string(r.password)}]}getConstructorEnvironmentArg({environment:t,hasMultiUrlEnvironments:r}){if(!r)return;let n=this.context.getEnvironmentsClassReference();if(t!=null){if(this.context.isSingleEnvironmentID(t)){let o=this.context.resolveEnvironmentName(t);if(o==null){this.addWarning(`Environment "${t}" was not found`);return}let s=this.context.getClassName(o);return{name:"environment",assignment:rn.TypeLiteral.reference(rn.codeblock(a=>{a.writeNode(n),a.write("::"),a.write(s),a.write("()")}))}}if(this.context.isMultiEnvironmentValues(t)){let o=this.resolveMultiEnvironmentName(t);if(o==null){this.addWarning("Invalid multi url environment");return}return o.type==="named"?{name:"environment",assignment:rn.TypeLiteral.reference(rn.codeblock(s=>{s.writeNode(n),s.write("::"),s.write(o.name),s.write("()")}))}:{name:"environment",assignment:rn.TypeLiteral.reference(rn.codeblock(s=>{s.writeNode(n),s.write("::custom(");let a=Object.entries(o.urls);a.forEach(([u,c],l)=>{s.write(`${u}: '${c}'`),l<a.length-1&&s.write(", ")}),s.write(")")}))}}}let i=this.getDefaultEnvironmentName();if(i!=null)return{name:"environment",assignment:rn.TypeLiteral.reference(rn.codeblock(o=>{o.writeNode(n),o.write("::"),o.write(i),o.write("()")}))}}getDefaultEnvironmentName(){if(this.context.ir.environments?.environments.type!=="multipleBaseUrls")return;let t=this.context.ir.environments.environments;if(t.type!=="multipleBaseUrls")return;let r=t.environments;if(r.length===0)return;for(let i of r){let o=this.context.getClassName(i.name);if(o==="Production")return o}let n=r[0];if(n!=null)return this.context.getClassName(n.name)}resolveMultiEnvironmentName(t){let r=Object.keys(t);if(r.length===0||!this.context.validateMultiEnvironmentUrlValues(t))return;let n=r[0];if(n==null)return;let i=t[n];if(i==null)return;let o=this.context.resolveEnvironmentName(i);if(o!=null&&r.every(u=>{let c=t[u];return c==null?!1:this.context.resolveEnvironmentName(c)!=null&&c===i}))return{type:"named",name:this.context.getClassName(o)};let s={};for(let a of r){let u=t[a];if(u==null)continue;let c=this.getBaseUrlPropertyName(a);s[c]=u}if(Object.keys(s).length>0)return{type:"custom",urls:s}}getBaseUrlPropertyName(t){if(this.context.ir.environments?.environments.type!=="multipleBaseUrls")return t;let r=this.context.ir.environments.environments;if(r.type!=="multipleBaseUrls")return t;let n=r.baseUrls.find(i=>i.id===t);return n==null?t:n.name.camelCase.safeName}getConstructorBaseUrlArgs({baseUrl:t,environment:r}){let n=this.getBaseUrlArg({baseUrl:t,environment:r});return rn.TypeLiteral.isNop(n)?[]:[{name:"baseUrl",value:n}]}getBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null)return this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"}),rn.TypeLiteral.nop();if(t!=null)return rn.TypeLiteral.string(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentClassAccessFromID(r);return n==null?(this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`}),rn.TypeLiteral.nop()):rn.TypeLiteral.reference(rn.codeblock(i=>{i.writeNode(n),i.write("->value")}))}if(this.context.ir.environments?.environments.type==="multipleBaseUrls")return rn.TypeLiteral.nop()}return rn.TypeLiteral.nop()}getConstructorBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.token),assignment:rn.TypeLiteral.string(r.token)}]}getConstructorHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.header.name.name),assignment:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value})}]}getConstructorOAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.clientId),assignment:rn.TypeLiteral.string(r.clientId)},{name:this.context.getPropertyName(t.clientSecret),assignment:rn.TypeLiteral.string(r.clientSecret)}]}getConstructorInferredAuthArgs({auth:t,values:r}){return[]}getConstructorHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getConstructorHeaderArg({header:i,value:o});s!=null&&n.push({name:this.context.getPropertyName(i.name.name),value:s})}return n}getConstructorHeaderArg({header:t,value:r}){let n=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:r});if(!rn.TypeLiteral.isNop(n))return n}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];return i.length>0&&n.push(...this.getPathParameters({namedParameters:i,snippet:r}).map(o=>o.value)),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),t.body!=null&&n.push(this.getBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope(),n}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r});default:Be(t)}}getBytesBodyRequestArg({value:t}){return this.context.errors.add({severity:Ir.Critical,message:"The PHP SDK doesn't support bytes requests yet"}),rn.TypeLiteral.nop()}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[],i=this.context.customConfig?.inlinePathParameters??!1;this.context.errors.scope(Lo.PathParameters);let o=[],s=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];s.length>0&&o.push(...this.getPathParameters({namedParameters:s,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let a=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})||n.push(...o.map(u=>u.value)),this.context.needsRequestParameter({request:t,inlinePathParameters:i,inlineFileProperties:!0})&&n.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})?o:[],filePropertyInfo:a})),n}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Lo.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicTypeLiteralMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.Headers);let u=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicTypeLiteralMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let c=t.body!=null?this.getInlinedRequestBodyConstructorFields({body:t.body,value:r.requestBody,filePropertyInfo:i}):[];return this.context.errors.unscope(),rn.TypeLiteral.class_({reference:rn.classReference({name:this.context.getClassName(t.declaration.name),namespace:this.context.getRequestNamespace(t.declaration.fernFilepath)}),fields:[...n,...s,...u,...c]})}getInlinedRequestBodyConstructorFields({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyConstructorFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyConstructorField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyConstructorFields({filePropertyInfo:n});default:Be(t)}}getFileUploadRequestBodyConstructorFields({filePropertyInfo:t}){return[...t.fileFields,...t.bodyPropertyFields]}getReferencedRequestBodyPropertyConstructorField({body:t,value:r}){return{name:this.context.getPropertyName(t.bodyKey),value:this.getReferencedRequestBodyPropertyTypeLiteral({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyTypeLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r});default:Be(t)}}getInlinedRequestBodyPropertyConstructorFields({parameters:t,value:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert(o)});return n}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:r.pathParameters??{}});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert(o)});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getPropertyName(r)).join("->")}->${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getRootClientClassInstantiation(t){return rn.instantiateClass({classReference:rn.classReference({name:this.context.getRootClientClassName(),namespace:this.context.rootNamespace}),arguments_:t,multiline:!0})}};var PLt=class extends Wv{constructor({ir:t,config:r}){super(new CMn({ir:t,config:r}))}async generate(t,r={}){return super.generate(t,r)}generateSync(t){return super.generateSync(t)}async generateSnippetAst(t,r){return await super.generateSnippetAst(t,r)}createSnippetGenerator(t){return new _Mn({context:t})}};var BMn=require("fs/promises"),PYu=Ae(require("path"),1);var SMn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new PLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");for(let[n,{endpointId:i,request:o}]of r.entries())try{let s=pS(o);if(s==null)continue;let a=await this.dynamicSnippetsGenerator.generate(s,{endpointId:i}),u=this.getTestFilePath({outputDir:t,idx:n});await(0,BMn.mkdir)(PYu.default.dirname(u),{recursive:!0}),await(0,BMn.writeFile)(u,a.snippet)}catch(s){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(o.endpoint)}: ${s}`)}this.context.logger.debug("Done generating dynamic snippet tests")}getTestFilePath({outputDir:t,idx:r}){return Ge(t,Se.of(`src/dynamic-snippets/example${r}/snippet.php`))}};qt();St();var fn={};Z(fn,{AccessAttribute:()=>Zft,AstNode:()=>dp,Class:()=>USe,ClassInstantiation:()=>tdt,CodeBlock:()=>hfe,Comment:()=>rdt,Decorator:()=>ndt,Field:()=>zSe,Lambda:()=>idt,LambdaParameter:()=>odt,Method:()=>qSe,MethodArgument:()=>adt,MethodInvocation:()=>udt,ModuleImport:()=>k7,Operator:()=>cdt,Parameter:()=>VSe,PythonFile:()=>ldt,Reference:()=>Fne,StarImport:()=>GSe,Type:()=>TMn,TypeInstantiation:()=>WSe,accessAttribute:()=>QDm,assign:()=>jDm,class_:()=>LDm,codeBlock:()=>WDm,comment:()=>$Dm,decorator:()=>zDm,field:()=>GDm,file:()=>MDm,instantiateClass:()=>UDm,invokeFunction:()=>YDm,invokeMethod:()=>XDm,lambda:()=>HDm,lambdaParameter:()=>KDm,method:()=>JDm,methodArgument:()=>eRm,operator:()=>tRm,parameter:()=>ZDm,reference:()=>VDm,starImport:()=>qDm});var DLt=class extends wC{fullyQualifiedModulePathsToImportedNames={};setRefNameOverrides(t){this.fullyQualifiedModulePathsToImportedNames=t}unsetRefNameOverrides(){this.fullyQualifiedModulePathsToImportedNames={}}getRefNameOverride(t){let r=this.fullyQualifiedModulePathsToImportedNames[t.getFullyQualifiedModulePath()];return r||{name:t.alias??t.name,isAlias:!!t.alias}}toString(){return this.buffer}async toStringFormatted(t){return t.format(this.buffer)}};var dp=class extends O0{references=[];addReference(t){this.references.push(t)}inheritReferences(t){t!==void 0&&t.references.forEach(r=>{this.references.includes(r)||this.addReference(r)})}getReferences(){return this.references}toString(){let t=new DLt;return this.write(t),t.toString()}async toStringFormatted(t){let r=new DLt;return this.write(r),r.toStringFormatted(t)}};var Zft=class extends dp{lhs;rhs;constructor({lhs:t,rhs:r}){super(),this.lhs=t,this.inheritReferences(t),this.rhs=r,this.inheritReferences(r)}write(t){this.lhs.write(t),t.write("."),this.rhs.write(t)}};var OMn=class extends dp{lhs;rhs;constructor({lhs:t,rhs:r}){super(),this.lhs=t,this.inheritReferences(t),this.rhs=r,this.inheritReferences(r)}write(t){this.lhs.write(t),t.write(" = "),this.rhs.write(t)}};var edt=class extends dp{reference;arguments;multiline;constructor({reference:t,arguments_:r,multiline:n}){super(),this.reference=t,this.arguments=r,this.multiline=n??!1,this.inheritReferences(t),this.arguments.forEach(i=>{this.inheritReferences(i)})}write(t){if(this.reference.write(t),this.arguments.length===0){t.write("()");return}t.write("("),this.multiline&&(t.newLine(),t.indent()),this.arguments.forEach((r,n)=>{r.write(t),n<this.arguments.length-1?(t.write(","),this.multiline?t.newLine():t.write(" ")):this.multiline&&t.write(",")}),this.multiline&&(t.newLine(),t.dedent()),t.write(")")}};var USe=class extends dp{name;extends_;decorators;fields=[];docs;statements=[];constructor({docs:t,name:r,extends_:n,decorators:i}){super(),this.name=r,this.extends_=n??[],this.decorators=i??[],this.docs=t,this.extends_.forEach(o=>{this.inheritReferences(o)}),this.decorators.forEach(o=>{this.inheritReferences(o)})}write(t){this.decorators.forEach(r=>{r.write(t)}),t.write(`class ${this.name}`),this.extends_.length>0&&(t.write("("),this.extends_.forEach((r,n)=>{n>0&&t.write(", "),r.write(t)}),t.write(")")),t.write(":"),t.newLine(),t.indent(),this.docs!=null&&(t.write('"""'),t.write(this.docs),t.write('"""')),t.writeNewLineIfLastLineNot(),this.fields.forEach(r=>{r.write(t),t.writeNewLineIfLastLineNot()}),t.dedent(),t.indent(),this.statements.length?this.writeStatements({writer:t}):t.write("pass"),t.dedent()}add(t){this.statements.push(t),this.inheritReferences(t)}writeStatements({writer:t}){this.statements.forEach((r,n)=>{r.write(t),t.writeNewLineIfLastLineNot()})}addField(t){this.add(t)}};var tdt=class extends edt{constructor({classReference:t,...r}){super({reference:t,...r})}};var hfe=class extends dp{arg;constructor(t){super(),this.arg=t}write(t){return new Ly(this.arg).write(t)}};var rdt=class extends dp{docs;constructor({docs:t}){super(),this.docs=t}write(t){this.docs!=null&&this.docs.split(`
2546
2546
  `).forEach(r=>{t.writeLine(`# ${r}`)})}};var ndt=class extends dp{callable;constructor({callable:t}){super(),this.callable=t,this.inheritReferences(t)}write(t){t.write("@"),this.callable.write(t),t.newLine()}};var zSe=class extends dp{name;type;initializer;docs;constructor({name:t,type:r,initializer:n,docs:i}){super(),this.name=t,this.type=r,this.initializer=n,this.docs=i,this.inheritReferences(this.type),this.inheritReferences(this.initializer)}write(t){t.write(this.name),this.type!==void 0&&(t.write(": "),this.type.write(t)),this.initializer!==void 0&&(t.write(" = "),this.initializer.write(t)),this.docs!=null&&(t.newLine(),t.write('"""'),t.newLine(),t.write(this.docs),t.newLine(),t.write('"""'))}};var idt=class extends dp{parameters;body;constructor({parameters:t,body:r}){super(),this.parameters=t??[],this.body=r,this.inheritReferences(r)}write(t){t.write("lambda"),this.parameters&&this.parameters.length&&(t.write(" "),this.parameters.forEach((r,n)=>{r.write(t),n<this.parameters.length-1&&t.write(", ")})),t.write(": "),this.body.write(t)}};var VSe=class extends dp{name;initializer;type;constructor({name:t,type:r,initializer:n}){super(),this.name=t,this.type=r,this.initializer=n}write(t){t.write(this.name),this.type&&(t.write(": "),this.type.write(t)),this.initializer!==void 0&&(t.write(" = "),this.initializer.write(t))}};var odt=class extends VSe{constructor({name:t,initializer:r}){super({name:t,initializer:r,type:void 0})}};var sdt;(function(e){e[e.STATIC=0]="STATIC",e[e.INSTANCE=1]="INSTANCE",e[e.CLASS=2]="CLASS"})(sdt||(sdt={}));var qSe=class extends dp{name;return;docstring;type;parameters;decorators;statements=[];static_;constructor({static_:t,name:r,parameters:n,return_:i,docstring:o,type:s,decorators:a}){super(),this.name=r,this.parameters=n??[],this.return=i,this.docstring=o,this.type=s,this.decorators=a??[],this.static_=t??!1,this.parameters.forEach(u=>{this.inheritReferences(u)}),this.inheritReferences(this.return),this.decorators.forEach(u=>{this.inheritReferences(u)}),this.statements.forEach(u=>{this.inheritReferences(u)})}addStatement(t){this.statements.push(t),this.inheritReferences(t)}write(t){this.static_&&this.decorators.push(fn.decorator({callable:fn.codeBlock("staticmethod")})),this.decorators.forEach(i=>{i.write(t)}),this.type===sdt.CLASS?fn.decorator({callable:new hfe("classmethod")}).write(t):this.type===sdt.STATIC&&fn.decorator({callable:new hfe("staticmethod")}).write(t),t.write(`def ${this.name}(`);let n=this.parameters.length>3;n&&(t.newLine(),t.indent()),this.type===sdt.INSTANCE?(t.write("self"),this.parameters.length>0&&(t.write(n?",":", "),n&&t.newLine())):this.type===sdt.CLASS&&(t.write("cls"),this.parameters.length>0&&(t.write(n?",":", "),n&&t.newLine())),this.parameters.forEach((i,o)=>{i.write(t),o<this.parameters.length-1&&(t.write(n?",":", "),n&&t.newLine())}),n&&(t.write(","),t.dedent(),t.newLine()),t.write(")"),this.return&&(t.write(" -> "),this.return.write(t)),t.write(":"),t.newLine(),this.docstring&&(t.indent(),t.write('"""'),t.write(this.docstring),t.write('"""'),t.newLine(),t.dedent()),this.statements.length?(t.indent(),this.statements.forEach((i,o)=>{i.write(t),o<this.statements.length-1&&t.newLine()}),t.dedent()):(t.indent(),t.write("pass"),t.dedent()),t.newLine()}};var adt=class extends dp{name;value;constructor({name:t,value:r}){super(),this.name=t,this.value=r,this.inheritReferences(this.value)}write(t){this.name!==void 0&&(t.write(this.name),t.write("=")),this.value.write(t)}};var udt=class extends dp{on;method;arguments;multiline;constructor({on:t,method:r,arguments_:n,multiline:i}){super(),this.on=t,this.method=r,this.arguments=n,this.multiline=i??!1,this.inheritReferences(t),this.arguments.forEach(o=>{this.inheritReferences(o)})}write(t){if(this.on.write(t),t.write("."),t.write(this.method),this.arguments.length===0){t.write("()");return}t.write("("),this.multiline&&(t.newLine(),t.indent()),this.arguments.forEach((r,n)=>{r.write(t),n<this.arguments.length-1?(t.write(","),this.multiline?t.newLine():t.write(" ")):this.multiline&&t.write(",")}),this.multiline&&(t.newLine(),t.dedent()),t.write(")")}};St();var Rne={Or:"or",And:"and",Add:"add",Subtract:"subtract",Multiply:"multiple",Divide:"divide",Modulo:"modulo",LeftShift:"leftShift",RightShift:"rightShift"};var cdt=class extends dp{operator;lhs;rhs;constructor({operator:t,lhs:r,rhs:n}){super(),this.operator=t,this.lhs=r,this.inheritReferences(r),this.rhs=n,this.inheritReferences(n)}getOperatorString(){switch(this.operator){case Rne.Or:return"or";case Rne.And:return"and";case Rne.Add:return"+";case Rne.Subtract:return"-";case Rne.Multiply:return"*";case Rne.Divide:return"/";case Rne.Modulo:return"%";case Rne.LeftShift:return"<<";case Rne.RightShift:return">>";default:Be(this.operator)}}write(t){this.lhs.write(t),t.write(" "),t.write(this.getOperatorString()),t.write(" "),this.rhs.write(t)}};function DYu(e){if(!e)return"Class";let t=e.replace(/[^a-zA-Z0-9\s_-]/g," ").replace(/[-_\s]+/g," ").trim();return!t||/^\d+$/.test(t)?"Class"+(t||""):(/^\d/.test(t)&&(t="Class"+t),t.split(/(?=[A-Z])|[-_\s]+/).filter(n=>n.length>0).map(n=>n.split(/(?<=\d)(?=[a-zA-Z])|(?<=[a-zA-Z])(?=\d)/).filter(i=>i.length>0)).flat().map((n,i)=>i===0&&/^\d/.test(n)?"Class"+n.charAt(0).toUpperCase()+n.slice(1).toLowerCase():n.length>1&&n===n.toUpperCase()&&!/^\d+$/.test(n)?n:n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(""))}var Fne=class extends dp{name;modulePath;genericTypes;alias;attribute;constructor({name:t,modulePath:r,genericTypes:n,alias:i,attribute:o}){super(),this.name=t,this.modulePath=r??[],this.genericTypes=n??[],this.alias=i,this.attribute=o??[],this.references.push(this),this.genericTypes.forEach(s=>{this.inheritReferences(s)})}write(t){let r=t.getRefNameOverride(this);t.write(r.name),this.genericTypes.length>0&&(t.write("["),this.genericTypes.forEach((n,i)=>{i>0&&t.write(", "),n.write(t)}),t.write("]")),this.attribute.length>0&&(t.write("."),this.attribute.forEach((n,i)=>{i>0&&t.write("."),t.write(n)}))}getFullyQualifiedPath(){return this.modulePath.join(".")}getFullyQualifiedModulePath(){return`${this.getFullyQualifiedPath()}.${this.name}`}};var k7=class extends Fne{constructor({module:t}){super({name:t,modulePath:[t]})}write(t){throw new Error("Not intended to be written outside the context of a PythonFile.")}};var GSe=class extends Fne{docs;constructor({modulePath:t}){super({name:"*",modulePath:t})}write(t){throw new Error("Not intended to be written outside the context of a PythonFile.")}};var ldt=class extends dp{path;isInitFile;statements=[];comments;constructor({path:t,statements:r,isInitFile:n=!1,comments:i,imports:o}){super(),this.path=t,this.isInitFile=n,r?.forEach(s=>this.addStatement(s)),this.comments=i??[],o?.forEach(s=>this.addReference(s))}addStatement(t){this.statements.push(t),this.inheritReferences(t)}write(t){let r=this.deduplicateReferences();this.updateWriterRefNameOverrides({writer:t,uniqueReferences:r}),this.writeComments(t),this.writeImports({writer:t,uniqueReferences:r}),this.statements.forEach((n,i)=>{n.write(t),t.newLine(),i<this.statements.length-1&&t.newLine()}),t.unsetRefNameOverrides()}updateWriterRefNameOverrides({writer:t,uniqueReferences:r}){let n=new Map(r),i={},o=this.getInitialUsedNames(),s=this.path.join("."),a=r.get(s);if(a){let{references:c}=a;c.forEach(l=>{let p=l.getFullyQualifiedModulePath(),d=l.name;i[p]={name:d,isAlias:!1},o.add(l.name)}),n.delete(s)}Array.from(n.values()).flatMap(({references:c})=>c).forEach(c=>{if(c instanceof GSe||c instanceof k7)return;let l=c.alias??c.name,p=c.getFullyQualifiedModulePath(),d=l,f=c.modulePath.length-1,m=!!c.alias;for(;o.has(d);){m=!0;let h=c.modulePath[f];f<0||!h?d=`_${d}`:d=`${DYu(h)}${d}`,f--}o.add(d),i[p]={name:d,isAlias:m}}),t.setRefNameOverrides(i)}getInitialUsedNames(){let t=new Set;return this.statements.forEach(r=>{(r instanceof USe||r instanceof qSe||r instanceof zSe)&&t.add(r.name)}),t}deduplicateReferences(){let t=new Map;for(let r of this.references){let n=r.name,i=r.getFullyQualifiedPath();if(i==="")continue;let o=t.get(i);o?o.referenceNames.has(n)||(o.references.push(r),o.referenceNames.add(n)):t.set(i,{modulePath:r.modulePath,references:[r],referenceNames:new Set([n])})}return t}writeComments(t){this.comments.forEach(r=>{r.write(t)}),this.comments.length>0&&t.newLine()}getImportName({writer:t,reference:r}){let n=t.getRefNameOverride(r),i=r.name,o=n.isAlias?n.name:void 0;return`${i}${o?` as ${o}`:""}`}writeImports({writer:t,uniqueReferences:r}){if(r.size!==0){for(let[n,{modulePath:i,references:o}]of r){let s=i;if(!this.isDefinedInFile(s)){if(o.some(a=>a instanceof k7)){t.write(`import ${n}`),t.newLine();continue}if(s[0]===this.path[0]){let a=0;for(;a<this.path.length&&a<s.length&&this.path[a]===s[a];)a++;let u=this.path.length-a;this.isInitFile&&u++;let c=u>0?".".repeat(u):".";c+=s.slice(a).join("."),t.write(`from ${c} import ${o.map(l=>this.getImportName({writer:t,reference:l})).join(", ")}`)}else t.write(`from ${n} import ${o.map(a=>this.getImportName({writer:t,reference:a})).join(", ")}`);t.newLine()}}t.newLine()}}isDefinedInFile(t){return t.length===this.path.length&&t.every((r,n)=>r===this.path[n])}};St();var TMn=class extends dp{internalType;constructor(t){super(),this.internalType=t}write(t){switch(this.internalType.type){case"int":t.write("int");break;case"float":t.write("float");break;case"bool":t.write("bool");break;case"str":t.write("str");break;case"bytes":t.write("bytes");break;case"list":t.write("List["),this.internalType.value.write(t),t.write("]");break;case"set":t.write("Set["),this.internalType.value.write(t),t.write("]");break;case"tuple":t.write("Tuple["),this.internalType.values.forEach((r,n)=>{n>0&&t.write(", "),r.write(t)}),t.write("]");break;case"dict":t.write("Dict["),this.internalType.keyType.write(t),t.write(", "),this.internalType.valueType.write(t),t.write("]");break;case"none":t.write("None");break;case"uuid":t.write("UUID");break;case"optional":t.write("Optional["),this.internalType.value.write(t),t.write("]");break;case"union":t.write("Union["),this.internalType.values.forEach((r,n)=>{n>0&&t.write(", "),r.write(t)}),t.write("]");break;case"any":t.write("Any");break;case"reference":this.internalType.value.write(t);break;case"datetime":t.write("datetime");break;case"literal":typeof this.internalType.value=="string"?t.write(`Literal["${this.internalType.value}"]`):t.write(`Literal[${this.internalType.value}]`);break;default:Be(this.internalType)}}static int(){return new this({type:"int"})}static float(){return new this({type:"float"})}static bool(){return new this({type:"bool"})}static str(){return new this({type:"str"})}static bytes(){return new this({type:"bytes"})}static list(t){let r=new this({type:"list",value:t});return r.addReference(fn.reference({name:"List",modulePath:["typing"]})),r.inheritReferences(t),r}static set(t){let r=new this({type:"set",value:t});return r.addReference(fn.reference({name:"Set",modulePath:["typing"]})),r.inheritReferences(t),r}static tuple(t){let r=new this({type:"tuple",values:t});return r.addReference(fn.reference({name:"Tuple",modulePath:["typing"]})),t.forEach(n=>r.inheritReferences(n)),r}static dict(t,r){let n=new this({type:"dict",keyType:t,valueType:r});return n.addReference(fn.reference({name:"Dict",modulePath:["typing"]})),n.inheritReferences(t),n.inheritReferences(r),n}static none(){return new this({type:"none"})}static uuid(){let t=new this({type:"uuid"});return t.addReference(fn.reference({name:"UUID",modulePath:["uuid"]})),t}static optional(t){if(this.isAlreadyOptional(t))return t;let r=new this({type:"optional",value:t});return r.addReference(fn.reference({name:"Optional",modulePath:["typing"]})),r.inheritReferences(t),r}static union(t){let r=new this({type:"union",values:t});return r.addReference(fn.reference({name:"Union",modulePath:["typing"]})),t.forEach(n=>r.inheritReferences(n)),r}static any(){let t=new this({type:"any"});return t.addReference(fn.reference({name:"Any",modulePath:["typing"]})),t}static datetime(){let t=new this({type:"datetime"});return t.addReference(fn.reference({name:"datetime",modulePath:["datetime"]})),t}static reference(t){let r=new this({type:"reference",value:t});return r.addReference(t),r}static literal(t){let r=new this({type:"literal",value:t});return r.addReference(fn.reference({name:"Literal",modulePath:["typing"]})),r}static isAlreadyOptional(t){return t.internalType.type==="optional"}};St();var WSe=class e extends dp{internalType;constructor(t){super(),this.internalType=t}static int(t){return new this({type:"int",value:t})}static float(t){return new this({type:"float",value:t})}static bool(t){return new this({type:"bool",value:t})}static str(t,r={multiline:!1,startOnNewLine:!1,endWithNewLine:!1}){return new this({type:"str",value:t,config:r})}static bytes(t){return new this({type:"bytes",value:t})}static list(t,r={endWithComma:!1}){let n=new this({type:"list",values:t,config:r});return t.forEach(i=>n.inheritReferences(i)),n}static set(t,r={endWithComma:!1}){let n=new this({type:"set",values:t,config:r});return t.forEach(i=>n.inheritReferences(i)),n}static tuple(t,r={endWithComma:!1}){let n=new this({type:"tuple",values:t,config:r});return t.forEach(i=>n.inheritReferences(i)),n}static typedDict(t,r={endWithComma:!1}){let n=new this({type:"typedDict",entries:t,config:r});return t.forEach(i=>n.inheritReferences(i.value)),n}static date(t){let r=new this({type:"date",value:t});return r.addReference(new k7({module:"datetime"})),r}static datetime(t){let r=new this({type:"datetime",value:t});return r.addReference(new k7({module:"datetime"})),r}static dict(t,r={endWithComma:!1}){let n=new this({type:"dict",entries:t,config:r});return t.forEach(i=>{n.inheritReferences(i.key),n.inheritReferences(i.value)}),n}static reference(t){let r=new this({type:"reference",value:t});return r.inheritReferences(t),r}static none(){return new this({type:"none"})}static unknown(t){return new this({type:"unknown",value:t})}static uuid(t){let r=new this({type:"uuid",value:t});return r.addReference(new k7({module:"uuid"})),r}static nop(){return new this({type:"nop"})}static isNop(t){return t instanceof e&&t.internalType.type==="nop"}isTypedDict(){return this.internalType.type==="typedDict"}asTypedDictOrThrow(){if(this.isTypedDict())return this.internalType;throw new Error("Internal error; python.TypeInstantiation is not a TypedDict")}write(t){switch(this.internalType.type){case"int":t.write(this.internalType.value.toString());break;case"float":t.write(this.internalType.value.toString());break;case"bool":this.internalType.value?t.write("True"):t.write("False");break;case"str":if(this.internalType.config?.multiline){let{startOnNewLine:r,endWithNewLine:n}=this.internalType.config;this.writeStringWithTripleQuotes({writer:t,value:this.internalType.value,startOnNewLine:r,endWithNewLine:n})}else t.write(`"${this.escapeString(this.internalType.value)}"`);break;case"date":t.write(`datetime.date.fromisoformat("${this.internalType.value}")`);break;case"datetime":{let r=this.internalType.value.replace(/Z$/,"+00:00");t.write(`datetime.datetime.fromisoformat("${r}")`);break}case"bytes":t.write(`b"${this.internalType.value}"`);break;case"list":{let r=this.internalType,n=ymo({values:r.values});if(n.length===0){t.write("[]");break}t.write("["),r.config?.multiline&&(t.newLine(),t.indent()),n.forEach((i,o)=>{o>0&&(t.write(","),r.config?.multiline?t.newLine():t.write(" ")),i.write(t),o===n.length-1&&r.config?.endWithComma&&t.write(",")}),r.config?.multiline&&(t.newLine(),t.dedent()),t.write("]");break}case"set":{let r=this.internalType,n=ymo({values:r.values});if(n.length===0){t.write("{}");break}t.write("{"),r.config?.multiline&&(t.newLine(),t.indent()),n.forEach((i,o)=>{o>0&&(t.write(","),r.config?.multiline?t.newLine():t.write(" ")),i.write(t),o===n.length-1&&r.config?.endWithComma&&t.write(",")}),r.config?.multiline&&(t.newLine(),t.dedent()),t.write("}");break}case"tuple":{let r=this.internalType,n=ymo({values:r.values});if(n.length===0){t.write("()");break}t.write("("),r.config?.multiline&&(t.newLine(),t.indent()),n.forEach((i,o)=>{o>0&&(t.write(","),r.config?.multiline?t.newLine():t.write(" ")),i.write(t),(n.length===1||o===n.length-1&&r.config?.endWithComma)&&t.write(",")}),r.config?.multiline&&(t.newLine(),t.dedent()),t.write(")");break}case"dict":{let r=this.internalType,n=NDm({entries:r.entries});if(n.length===0){t.write("{}");break}t.write("{"),r.config?.multiline&&(t.newLine(),t.indent()),n.forEach((i,o)=>{o>0&&(t.write(","),r.config?.multiline?t.newLine():t.write(" ")),i.key.write(t),t.write(": "),i.value.write(t),o===n.length-1&&r.config?.endWithComma&&t.write(",")}),r.config?.multiline&&(t.newLine(),t.dedent()),t.write("}");break}case"typedDict":{let r=this.internalType,n=kDm({entries:r.entries});if(n.length===0){t.write("{}");break}t.write("{"),r.config?.multiline&&(t.writeLine(),t.indent()),n.forEach((i,o)=>{o>0&&(t.write(","),r.config?.multiline?t.newLine():t.write(" ")),t.write(`"${i.name}": `),i.value.write(t)}),r.config?.multiline&&(t.newLine(),t.dedent()),t.write("}");break}case"reference":{this.internalType.value.write(t);break}case"none":t.write("None");break;case"unknown":this.writeUnknown({writer:t,value:this.internalType.value});break;case"uuid":t.write(`uuid.UUID("${this.internalType.value}")`);break;case"nop":break;default:Be(this.internalType)}}writeStringWithTripleQuotes({writer:t,value:r,startOnNewLine:n,endWithNewLine:i}){t.write('"""');let o=r.split(`
2547
2547
  `);if(o.length<=1){t.write(this.escapeString(o[0]??"")),t.write('"""');return}n&&t.writeNoIndent(`\\
2548
2548
  `),o.forEach((s,a)=>{t.writeNoIndent(this.escapeString(s)),a===o.length-1?i&&t.writeNoIndent(`\\
2549
2549
  `):t.writeNoIndent(`
2550
- `)}),t.writeNoIndent('"""')}escapeString(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/'/g,"\\'").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r")}writeUnknown({writer:t,value:r}){switch(typeof r){case"boolean":t.write(r?"True":"False");return;case"string":t.write(`"${this.escapeString(r)}"`);return;case"number":t.write(r.toString());return;case"object":if(r==null){t.write("None");return}if(Array.isArray(r)){this.writeUnknownArray({writer:t,value:r});return}this.writeUnknownObject({writer:t,value:r});return;default:throw new Error(`Internal error; unsupported unknown type: ${typeof r}`)}}writeUnknownArray({writer:t,value:r}){if(r.length===0){t.write("[]");return}t.write("["),r.forEach((n,i)=>{i>0&&t.write(", "),t.writeNode(e.unknown(n))}),t.write("]")}writeUnknownObject({writer:t,value:r}){let n=Object.entries(r);if(n.length===0){t.write("{}");return}t.write("{"),n.forEach(([i,o],s)=>{s>0&&t.write(", "),t.write(`"${i}": `),t.writeNode(e.unknown(o))}),t.write("}")}};function NDm({entries:e}){return e.filter(t=>!WSe.isNop(t.key)&&!WSe.isNop(t.value))}function kDm({entries:e}){return e.filter(t=>!WSe.isNop(t.value))}function ymo({values:e}){return e.filter(t=>!WSe.isNop(t))}function QDm(e){return new Zft(e)}function jDm(e){return new OMn(e)}function MDm(e){return new ldt(e)}function LDm(e){return new USe(e)}function UDm(e){return new tdt(e)}function zDm(e){return new ndt(e)}function VDm(e){return new Fne(e)}function qDm(e){return new GSe(e)}function GDm(e){return new zSe(e)}function WDm(e){return new hfe(e)}function $Dm(e){return new rdt(e)}function HDm(e){return new idt(e)}function KDm(e){return new odt(e)}function JDm(e){return new qSe(e)}function YDm(e){return new edt(e)}function XDm(e){return new udt(e)}function ZDm(e){return new VSe(e)}function eRm(e){return new adt(e)}function tRm(e){return new cdt(e)}Bi();St();var rRm="value",PMn=class{context;constructor({context:t}){this.context=t}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?fn.TypeInstantiation.none():(this.context.errors.add({severity:Ir.Critical,message:"Expected non-null value, but got null"}),fn.TypeInstantiation.nop());if(t.value===void 0)return fn.TypeInstantiation.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value});case"literal":return this.convertLiteral({literalType:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value});case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?fn.TypeInstantiation.nop():this.convertNamed({named:r,value:t.value,as:t.as})}case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as});case"set":return this.convertSet({set:t.typeReference.value,value:t.value});case"unknown":return fn.TypeInstantiation.unknown(t.value);default:Be(t.typeReference)}}convertLiteral({literalType:t,value:r}){switch(t.type){case"boolean":{let n=this.context.getValueAsBoolean({value:r});return n==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.bool(n)}case"string":{let n=this.context.getValueAsString({value:r});return n==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.str(n)}default:Be(t)}}convertList({list:t,value:r}){return Array.isArray(r)?fn.TypeInstantiation.list(r.map((n,i)=>{this.context.errors.scope({index:i});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}}),{multiline:!0}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),fn.TypeInstantiation.nop())}convertSet({set:t,value:r}){return Array.isArray(r)?fn.TypeInstantiation.list(r.map((n,i)=>{this.context.errors.scope({index:i});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}}),{multiline:!0}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),fn.TypeInstantiation.nop())}convertMap({map:t,value:r}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),fn.TypeInstantiation.nop()):fn.TypeInstantiation.dict(Object.entries(r).map(([n,i])=>{this.context.errors.scope(n);try{return{key:this.convert({typeReference:t.key,value:n,as:"key"}),value:this.convert({typeReference:t.value,value:i})}}finally{this.context.errors.unscope()}}),{multiline:!0})}convertNamed({named:t,value:r,as:n}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference,value:r,as:n});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:r});case"enum":return this.convertEnum({enum_:t,value:r});case"object":return this.convertObject({object_:t,value:r});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r});default:Be(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r}){let n=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(n==null)return fn.TypeInstantiation.nop();let i=n.singleDiscriminatedUnionType,o=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:n,unionVariant:i});if(o==null)return fn.TypeInstantiation.nop();let s={name:this.context.getPropertyName(t.discriminant.name),value:fn.TypeInstantiation.str(i.discriminantValue.wireValue)};return fn.TypeInstantiation.typedDict([s,...o],{multiline:!0})}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:t,unionVariant:r}){let n=this.getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r});switch(r.type){case"samePropertiesAsObject":{let i=this.context.resolveNamedType({typeId:r.typeId});if(i==null)return;if(i.type!=="object"){this.context.errors.add({severity:Ir.Critical,message:"Internal error; expected union value to be an object"});return}let o=this.convertObjectEntries({object_:i,value:t.value});return[...n,...o]}case"singleProperty":try{this.context.errors.scope(r.discriminantValue.wireValue);let i=this.context.getRecord(t.value);return i==null?[...n,{name:rRm,value:this.convert({typeReference:r.typeReference,value:t.value})}]:[...n,{name:this.context.getPropertyName(r.discriminantValue.name),value:this.convert({typeReference:r.typeReference,value:i[r.discriminantValue.wireValue]})}]}finally{this.context.errors.unscope()}case"noProperties":return n;default:Be(r)}}getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r}){return this.context.associateByWireValue({parameters:r.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(i=>{this.context.errors.scope(i.name.wireValue);try{return{name:this.context.getPropertyName(i.name.name),value:this.convert(i)}}finally{this.context.errors.unscope()}})}convertObjectEntries({object_:t,value:r}){let n=this.context.getRecord(r)??{},i=this.context.associateByWireValue({parameters:t.properties,values:n}),o=new Set(Object.keys(n)),s=i.map(a=>{this.context.errors.scope(a.name.wireValue);try{return{name:this.context.getPropertyName(a.name.name),value:this.convert(a)}}finally{this.context.errors.unscope()}});for(let a of t.properties){if(o.has(a.name.wireValue)||this.context.isOptional(a.typeReference)||this.context.isNullable(a.typeReference))continue;let u=this.synthesizeDefaultValue(a.typeReference);fn.TypeInstantiation.isNop(u)||s.push({name:this.context.getPropertyName(a.name.name),value:u})}return s}convertObject({object_:t,value:r}){let n=this.convertObjectEntries({object_:t,value:r});if(this.context.useTypedDictRequests())return fn.TypeInstantiation.typedDict(n,{multiline:!0});let i=this.context.getTypeClassReference(t.declaration);return fn.TypeInstantiation.reference(fn.instantiateClass({classReference:i,arguments_:n.map(o=>fn.methodArgument({name:o.name,value:o.value})),multiline:!0}))}convertEnum({enum_:t,value:r}){let n=this.getEnumValue({enum_:t,value:r});return n==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.str(n)}getEnumValue({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Ir.Critical,message:`Expected enum value string, got: ${typeof r}`});return}if(t.values.find(i=>i.wireValue===r)==null){this.context.errors.add({severity:Ir.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return r}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r}){let n=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r});return n??fn.TypeInstantiation.nop()}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r}){for(let n of t.types){let i=this.context.errors.size();try{let o=this.convert({typeReference:n,value:r});if(fn.TypeInstantiation.isNop(o)){this.context.errors.truncate(i);continue}return o}catch{this.context.errors.truncate(i);continue}}this.context.errors.add({severity:Ir.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}synthesizeDefaultValue(t,r=new Set){switch(t.type){case"optional":case"nullable":return fn.TypeInstantiation.nop();case"primitive":return this.synthesizeDefaultPrimitive(t.value);case"literal":return this.synthesizeDefaultLiteral(t.value);case"list":return fn.TypeInstantiation.list([]);case"set":return fn.TypeInstantiation.list([]);case"map":return fn.TypeInstantiation.dict([]);case"named":{if(r.has(t.value))return fn.TypeInstantiation.nop();let n=this.context.resolveNamedType({typeId:t.value});return n==null?fn.TypeInstantiation.nop():this.synthesizeDefaultNamed({named:n,typeId:t.value,seen:r})}case"unknown":return fn.TypeInstantiation.nop();default:Be(t)}}synthesizeDefaultPrimitive(t){switch(t){case"STRING":case"BASE_64":case"BIG_INTEGER":return fn.TypeInstantiation.str("string");case"INTEGER":case"LONG":case"UINT":case"UINT_64":return fn.TypeInstantiation.int(1);case"FLOAT":case"DOUBLE":return fn.TypeInstantiation.float(1.1);case"BOOLEAN":return fn.TypeInstantiation.bool(!0);case"DATE":return fn.TypeInstantiation.date("2024-01-15");case"DATE_TIME":return fn.TypeInstantiation.datetime("2024-01-15T09:30:00Z");case"UUID":return fn.TypeInstantiation.uuid("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32");default:Be(t)}}synthesizeDefaultLiteral(t){switch(t.type){case"boolean":return fn.TypeInstantiation.bool(t.value);case"string":return fn.TypeInstantiation.str(t.value);default:Be(t)}}synthesizeDefaultNamed({named:t,typeId:r,seen:n}){let i=new Set(n);switch(i.add(r),t.type){case"alias":return this.synthesizeDefaultValue(t.typeReference,i);case"enum":{let o=t.values[0];return o==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.str(o.wireValue)}case"object":{let o=[];for(let a of t.properties){if(this.context.isOptional(a.typeReference)||this.context.isNullable(a.typeReference))continue;let u=this.synthesizeDefaultValue(a.typeReference,i);fn.TypeInstantiation.isNop(u)||o.push({name:this.context.getPropertyName(a.name.name),value:u})}if(this.context.useTypedDictRequests())return fn.TypeInstantiation.typedDict(o,{multiline:!0});let s=this.context.getTypeClassReference(t.declaration);return fn.TypeInstantiation.reference(fn.instantiateClass({classReference:s,arguments_:o.map(a=>fn.methodArgument({name:a.name,value:a.value})),multiline:!0}))}case"discriminatedUnion":case"undiscriminatedUnion":return fn.TypeInstantiation.nop();default:Be(t)}}convertPrimitive({primitive:t,value:r,as:n}){switch(t){case"INTEGER":case"LONG":case"UINT":case"UINT_64":{let i=this.getValueAsNumber({value:r,as:n});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.int(i)}case"FLOAT":case"DOUBLE":{let i=this.getValueAsNumber({value:r});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.float(i)}case"BOOLEAN":{let i=this.getValueAsBoolean({value:r,as:n});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.bool(i)}case"BASE_64":case"BIG_INTEGER":case"STRING":{let i=this.context.getValueAsString({value:r});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.str(i)}case"UUID":{let i=this.context.getValueAsString({value:r});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.uuid(i)}case"DATE":{let i=this.context.getValueAsString({value:r});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.date(i)}case"DATE_TIME":{let i=this.context.getValueAsString({value:r});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.datetime(i)}default:Be(t)}}getValueAsNumber({value:t,as:r}){let n=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:n})}};St();var DMn=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({body:t,value:r}){let n={fileFields:[],bodyPropertyFields:[]},i=this.context.getRecord(r)??{};for(let o of t.properties)switch(o.type){case"file":{let s=this.getSingleFileProperty({property:o,record:i});if(fn.TypeInstantiation.isNop(s))break;n.fileFields.push({name:this.context.getPropertyName(o.name),value:s});break}case"fileArray":{let s=this.getArrayFileProperty({property:o,record:i});if(fn.TypeInstantiation.isNop(s))break;n.fileFields.push({name:this.context.getPropertyName(o.name),value:s});break}case"bodyProperty":{let s=this.getBodyProperty({property:o,record:i});if(fn.TypeInstantiation.isNop(s))break;n.bodyPropertyFields.push({name:this.context.getPropertyName(o.name.name),value:s});break}default:Be(o)}return n}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r});return n==null&&(n=`example_${t.wireValue??"file"}`),this.context.getFileFromString(n)}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});if(n==null){let i=`example_${t.wireValue??"files"}`;return fn.TypeInstantiation.list([this.context.getFileFromString(i)])}return fn.TypeInstantiation.list(n.map(i=>this.context.getFileFromString(i)))}getBodyProperty({property:t,record:r}){let n=r[t.name.wireValue];return n==null?fn.TypeInstantiation.nop():this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:n})}};var nRm=["list","set"],RMn=class e extends $v{ir;customConfig;dynamicTypeLiteralMapper;filePropertyMapper;constructor({ir:t,config:r}){super({ir:t,config:r}),this.ir=t,this.customConfig=r.customConfig??{},this.dynamicTypeLiteralMapper=new PMn({context:this}),this.filePropertyMapper=new DMn({context:this})}clone(){return new e({ir:this.ir,config:this.config})}getClassName(t){let r=t.pascalCase.safeName,n=this.getRootClientClassName();return r===n?`${n}Model`:r}getTypedDictClassName(t){return`${this.getClassName(t)}Params`}getPropertyName(t){let r=t.snakeCase.safeName;return r.startsWith("_")?"f_"+r.substring(r.lastIndexOf("_")+1):r}getMethodName(t){return nRm.includes(t.snakeCase.unsafeName)?t.snakeCase.unsafeName:t.snakeCase.safeName}getRootClientClassReference(){return fn.reference({name:this.getRootClientClassName(),modulePath:this.getRootModulePath()})}getTypeClassReference(t){let r=this.getClassName(t.name),n=[...this.getRootModulePath(),...t.fernFilepath.allParts.map(i=>i.snakeCase.safeName)];return fn.reference({name:r,modulePath:n})}useTypedDictRequests(){return this.customConfig.use_typeddict_requests===!0}getRootClientClassName(){return this.customConfig.client?.exported_class_name!=null?this.customConfig.client.exported_class_name:this.customConfig.client_class_name!=null?this.customConfig.client_class_name:this.customConfig.client?.class_name!=null?this.customConfig.client.class_name:this.pascalCase(this.config.organization)+this.pascalCase(this.config.workspaceName)}getEnvironmentClassName(){return`${this.getRootClientClassName()}Environment`}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return fn.accessAttribute({lhs:this.getEnvironmentClassReference(),rhs:fn.codeBlock(this.getEnvironmentEnumName(r))})}getEnvironmentClassReference(){return fn.reference({name:this.getEnvironmentClassName(),modulePath:this.getEnvironmentModulePath()})}getEnvironmentEnumName(t){return t.screamingSnakeCase.safeName}isPrimitive(t){switch(t.type){case"primitive":return!0;case"optional":case"nullable":return this.isPrimitive(t.value);case"named":{let r=this.resolveNamedType({typeId:t.value});if(r==null)return!1;switch(r.type){case"alias":return this.isPrimitive(r.typeReference);case"discriminatedUnion":case"undiscriminatedUnion":case"object":case"enum":return!1;default:Be(r)}break}case"list":case"set":case"map":case"literal":case"unknown":return!1;default:Be(t)}}getFileFromString(t){return fn.TypeInstantiation.str(t)}getRootModulePath(){if(this.customConfig.package_name!=null)return[this.customConfig.package_name];let t=this.cleanOrganizationName();return this.customConfig.use_api_name_in_package?[t,this.getApiName()]:[t]}getCoreModulePath(){return this.getRootModulePath().concat("core")}getEnvironmentModulePath(){return this.getRootModulePath().concat("environment")}shouldInlinePathParameters(){return!0}cleanOrganizationName(){return this.config.organization.replace(/[^a-zA-Z0-9]/g,"_")}getApiName(){return uOe(this.config.workspaceName)}pascalCase(t){let r=qn(t);return r.charAt(0).toUpperCase()+r.slice(1)}};St();var iRm={type:"primitive",value:"STRING"},oRm=["example"],RYu="client",pdt="request",FMn=class{context;constructor({context:t}){this.context=t}async generateSnippet({endpoint:t,request:r}){return this.buildPythonFile({endpoint:t,snippet:r}).toString()}generateSnippetSync({endpoint:t,request:r}){return this.buildPythonFile({endpoint:t,snippet:r}).toString()}async generateSnippetAst({endpoint:t,request:r}){return this.buildPythonFile({endpoint:t,snippet:r})}generateMethodCallSnippetAst({endpoint:t,request:r}){return this.callMethod({endpoint:t,snippet:r})}buildPythonFile({endpoint:t,snippet:r}){return fn.file({path:oRm,statements:[this.constructClient({endpoint:t,snippet:r}),this.callMethod({endpoint:t,snippet:r})]})}constructClient({endpoint:t,snippet:r}){return fn.assign({lhs:fn.reference({name:RYu}),rhs:fn.instantiateClass({classReference:this.context.getRootClientClassReference(),arguments_:this.getConstructorArgs({endpoint:t,snippet:r}).map(n=>fn.methodArgument({name:n.name,value:n.value})),multiline:!0})})}getConstructorArgs({endpoint:t,snippet:r}){let n=[],i=this.getConstructorEnvironmentArgs({baseUrl:r.baseURL,environment:r.environment});return i.length>0&&n.push(...i),t.auth!=null&&(r.auth!=null?n.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Ir.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`})),this.context.errors.scope(Lo.PathParameters),this.context.ir.pathParameters!=null&&n.push(...this.getPathParameters({namedParameters:this.context.ir.pathParameters,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),n}getConstructorEnvironmentArgs({baseUrl:t,environment:r}){let n=this.getEnvironmentValue({baseUrl:t,environment:r});return n==null?[]:r!=null&&this.context.isMultiEnvironmentValues(r)?[{name:"environment",value:n}]:[{name:this.getEnvironmentOptionName({environment:r}),value:n}]}getEnvironmentValue({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null)return fn.TypeInstantiation.str(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);if(n==null){this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return fn.TypeInstantiation.reference(n)}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?fn.TypeInstantiation.reference(fn.instantiateClass({classReference:this.context.getEnvironmentClassReference(),arguments_:Object.entries(r).map(([n,i])=>({name:n,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:iRm,value:i})})).map(n=>fn.methodArgument({name:n.name,value:n.value})),multiline:!0})):void 0}}getConstructorAuthArgs({auth:t,values:r}){switch(t.type){case"basic":return r.type!=="basic"?(this.addAuthMismatchError(t,r),[]):this.getConstructorBasicAuthArg({auth:t,values:r});case"bearer":return r.type!=="bearer"?(this.addAuthMismatchError(t,r),[]):this.getConstructorBearerAuthArgs({auth:t,values:r});case"header":return r.type!=="header"?(this.addAuthMismatchError(t,r),[]):this.getConstructorHeaderAuthArgs({auth:t,values:r});case"oauth":return r.type!=="oauth"?(this.addAuthMismatchError(t,r),[]):this.getConstructorOAuthArgs({auth:t,values:r});case"inferred":return r.type!=="inferred"?(this.addAuthMismatchError(t,r),[]):this.getConstructorInferredAuthArgs({auth:t,values:r});default:Be(t)}}addAuthMismatchError(t,r){this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:r}).message})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:r}){return[{name:this.context.getPropertyName(t.username),value:fn.TypeInstantiation.str(r.username)},{name:this.context.getPropertyName(t.password),value:fn.TypeInstantiation.str(r.password)}]}getConstructorBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.token),value:fn.TypeInstantiation.str(r.token)}]}getConstructorHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.header.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value})}]}getConstructorOAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.clientId),value:fn.TypeInstantiation.str(r.clientId)},{name:this.context.getPropertyName(t.clientSecret),value:fn.TypeInstantiation.str(r.clientSecret)}]}getConstructorInferredAuthArgs({auth:t,values:r}){let n=t.parameters??[];if(n.length===0)return this.addWarning("Inferred auth scheme is missing parameters; cannot generate constructor arguments."),[];let i=r.values;if(i==null)return this.addWarning("Inferred auth values were not provided; cannot generate constructor arguments."),[];let o=[];for(let s of n){let a=s.name.wireValue;if(!Object.hasOwn(i,a)){this.addWarning(`Missing inferred auth value for ${a}`);continue}let u=i[a],c=this.context.dynamicTypeLiteralMapper.convert({typeReference:s.typeReference,value:u});fn.TypeInstantiation.isNop(c)||o.push({name:this.context.getPropertyName(s.name.name),value:c})}return o}getConstructorHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getConstructorHeaderArg({header:i,value:o});s!=null&&n.push(s)}return n}getConstructorHeaderArg({header:t,value:r}){let n=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:r});if(!fn.TypeInstantiation.isNop(n))return{name:this.context.getPropertyName(t.name.name),value:n}}callMethod({endpoint:t,snippet:r}){return fn.invokeMethod({on:fn.reference({name:RYu}),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:r}).filter(n=>!fn.TypeInstantiation.isNop(n.value)).map(n=>fn.methodArgument({name:n.name,value:n.value})),multiline:!0})}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[...this.context.ir.pathParameters??[],...t.pathParameters??[]],o=new Set;if(t.body!=null){let s=this.getBodyRequestArgs({body:t.body,value:r.requestBody});if(o=new Set(s.map(a=>a.name)),t.body.type==="typeReference"){let a=t.body.value;if(a.type==="named"){let u=this.context.resolveNamedType({typeId:a.value});if(u!=null&&u.type==="object")for(let c of u.properties)this.resolvesToLiteralType(c.typeReference)||o.add(this.context.getPropertyName(c.name.name))}}}if(i.length>0){let a=this.getPathParameters({namedParameters:i,snippet:r}).map(u=>o.has(u.name)?{...u,name:u.name+"_"}:u);n.push(...a)}return this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),t.body!=null&&n.push(...this.getBodyRequestArgs({body:t.body,value:r.requestBody})),this.context.errors.unscope(),n}getBodyRequestArgs({body:t,value:r}){switch(t.type){case"bytes":return[{name:pdt,value:this.getBytesBodyRequestTypeInstantiation({value:r})}];case"typeReference":return this.getBodyRequestArgsForTypeReference({typeReference:t.value,value:r});default:Be(t)}}getBodyRequestArgsForTypeReference({typeReference:t,value:r}){switch(t.type){case"named":{let n=this.context.resolveNamedType({typeId:t.value});return n==null?[]:this.getBodyRequestArgsForNamedTypeReference({typeReference:t,named:n,value:r})}case"nullable":case"optional":{let n=t.value;return n.type==="named"&&this.context.resolveNamedType({typeId:n.value})?.type==="object"?[{name:pdt,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:n,value:r})}]:this.getBodyRequestArgsForTypeReference({typeReference:t.value,value:r})}case"list":case"map":case"set":case"literal":case"primitive":case"unknown":return[{name:pdt,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t,value:r})}];default:Be(t)}}getBodyRequestArgsForNamedTypeReference({typeReference:t,named:r,value:n}){switch(r.type){case"alias":return this.getBodyRequestArgsForTypeReference({typeReference:r.typeReference,value:n});case"enum":case"discriminatedUnion":case"undiscriminatedUnion":return[{name:pdt,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t,value:n})}];case"object":return this.context.customConfig.inline_request_params===!1?[{name:pdt,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t,value:n})}]:this.context.associateByWireValue({parameters:r.properties,values:this.context.getRecord(n)??{}}).filter(s=>!this.resolvesToLiteralType(s.typeReference)).map(s=>({name:this.context.getPropertyName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert(s)}));default:Be(r)}}resolvesToLiteralType(t){switch(t.type){case"literal":return!0;case"optional":case"nullable":return this.resolvesToLiteralType(t.value);case"named":{let r=this.context.resolveNamedType({typeId:t.value});return r==null?!1:r.type==="alias"?this.resolvesToLiteralType(r.typeReference):!1}case"list":case"map":case"set":case"primitive":case"unknown":return!1;default:Be(t)}}getBodyRequestArgsForBytes({body:t,value:r}){let n=this.getBytesBodyRequestTypeInstantiation({value:r});return fn.TypeInstantiation.isNop(n)?[]:[{name:pdt,value:n}]}getBytesBodyRequestTypeInstantiation({value:t}){return typeof t!="string"?(this.context.errors.add({severity:Ir.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),fn.TypeInstantiation.nop()):fn.TypeInstantiation.bytes(t)}getBodyPropertyNamesForInlinedRequest(t){if(t.body==null)return new Set;switch(t.body.type){case"referenced":{let r=t.body.bodyType;if(r.type!=="typeReference")return new Set;let n=r.value;if(n.type!=="named")return new Set;let i=this.context.resolveNamedType({typeId:n.value});if(i==null||i.type!=="object")return new Set;let o=new Set;for(let s of i.properties)this.resolvesToLiteralType(s.typeReference)||o.add(this.context.getPropertyName(s.name.name));return o}case"properties":return new Set(t.body.value.filter(r=>!this.resolvesToLiteralType(r.typeReference)).map(r=>this.context.getPropertyName(r.name.name)));case"fileUpload":return new Set(t.body.properties.filter(r=>r.type==="bodyProperty").map(r=>this.context.getPropertyName(r.name.name)));default:Be(t.body)}}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[],i=this.context.shouldInlinePathParameters();this.context.errors.scope(Lo.PathParameters);let o=[];t.pathParameters!=null&&o.push(...this.getPathParameters({namedParameters:t.pathParameters,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let s=this.getFilePropertyInfo({request:t,snippet:r});this.context.errors.unscope();let a=this.getBodyPropertyNamesForInlinedRequest(t),u=o.map(c=>a.has(c.name)?{...c,name:`${c.name}_`}:c);return this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})||n.push(...u),this.context.needsRequestParameter({request:t,inlinePathParameters:i,inlineFileProperties:!0})&&n.push(...this.getInlinedRequestArgs({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})?u:[],filePropertyInfo:s})),n}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArgs({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Lo.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicTypeLiteralMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.Headers);let u=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicTypeLiteralMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let c=t.body!=null?this.getInlinedRequestBodyObjectFields({body:t.body,value:r.requestBody,filePropertyInfo:i}):[];return this.context.errors.unscope(),[...n,...s,...u,...c]}getInlinedRequestBodyObjectFields({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyObjectFields({parameters:t.value,value:r});case"referenced":return this.getReferencedRequestBodyPropertyTypeInstantiation({body:t,value:r});case"fileUpload":return this.getFileUploadRequestBodyObjectFields({filePropertyInfo:n});default:Be(t)}}getFileUploadRequestBodyObjectFields({filePropertyInfo:t}){return[...t.fileFields,...t.bodyPropertyFields]}getReferencedRequestBodyPropertyTypeInstantiation({body:t,value:r}){let n=t.bodyType;switch(n.type){case"bytes":return this.getBodyRequestArgsForBytes({body:t,value:r});case"typeReference":return this.getBodyRequestArgsForTypeReference({typeReference:n.value,value:r});default:Be(n)}}getInlinedRequestBodyPropertyObjectFields({parameters:t,value:r}){let n=[],o=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}}).filter(s=>!this.resolvesToLiteralType(s.typeReference));for(let s of o)n.push({name:this.context.getPropertyName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert(s)});return n}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=t.filter(s=>!this.resolvesToLiteralType(s.typeReference)),o=this.context.associateByWireValue({parameters:i,values:r.pathParameters??{},ignoreMissingParameters:!0});for(let s of o)n.push({name:this.context.getPropertyName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert(s)});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getMethodName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getEnvironmentOptionName({environment:t}){return t!=null?"environment":"base_url"}};var RLt=class extends Wv{constructor({ir:t,config:r}){super(new RMn({ir:t,config:r}))}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t,r={}){return super.generateSnippetAst(t,r)}generateMethodCallSnippetAst({request:t,options:r={}}){let n=this.resolveEndpointsForMethodCall({request:t,options:r});if(n.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let i;for(let o of n){let s=this.context.clone(),a=this.createSnippetGenerator(s);try{return a.generateMethodCallSnippetAst({endpoint:o,request:t})}catch(u){i=u}}throw i??new Error(`Failed to generate method call snippet AST for endpoint: ${t.endpoint.method} ${t.endpoint.path}`)}resolveEndpointsForMethodCall({request:t,options:r}){if(r.endpointId!=null){let n=this.context.resolveEndpointById(r.endpointId);if(n==null)throw new Error(`No endpoint found with ID "${r.endpointId}"`);return[n]}return this.context.resolveEndpointLocationOrThrow(t.endpoint)}createSnippetGenerator(t){return new FMn({context:t})}};var kMn=require("fs/promises"),FYu=Ae(require("path"),1);var NMn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new RLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");for(let[n,i]of r.entries())try{let o=pS(i);if(o==null)continue;let s=await this.dynamicSnippetsGenerator.generate(o),a=this.getTestFilePath({outputDir:t,idx:n});await(0,kMn.mkdir)(FYu.default.dirname(a),{recursive:!0}),await(0,kMn.writeFile)(a,s.snippet)}catch(o){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(i.endpoint)}: ${o}`)}this.context.logger.debug("Done generating dynamic snippet tests")}getTestFilePath({outputDir:t,idx:r}){return Ge(t,Se.of(`dynamic_snippets/example${r}.py`))}};qt();var sRm=2,BV=class extends wC{customConfig;formatter;requires=new Set;_indentLevel=0;constructor({customConfig:t,formatter:r}){super(),this.customConfig=t,this.formatter=r??new B7}addRequire(t){this.requires.add(t)}get currentIndentLevel(){return this._indentLevel}indent(){this._indentLevel++,super.indent()}dedent(){this._indentLevel--,super.dedent()}writeNodeStatement(t){this.writeNode(t),this.writeNewLineIfLastLineNot()}getTabSize(){return sRm}};var fdt=class extends BV{constructor({customConfig:t,formatter:r}){super({customConfig:t,formatter:r})}async toStringAsync(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.format(t)}catch(r){throw new Error(`Failed to format Ruby file: ${r}
2550
+ `)}),t.writeNoIndent('"""')}escapeString(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/'/g,"\\'").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r")}writeUnknown({writer:t,value:r}){switch(typeof r){case"boolean":t.write(r?"True":"False");return;case"string":t.write(`"${this.escapeString(r)}"`);return;case"number":t.write(r.toString());return;case"object":if(r==null){t.write("None");return}if(Array.isArray(r)){this.writeUnknownArray({writer:t,value:r});return}this.writeUnknownObject({writer:t,value:r});return;default:throw new Error(`Internal error; unsupported unknown type: ${typeof r}`)}}writeUnknownArray({writer:t,value:r}){if(r.length===0){t.write("[]");return}t.write("["),r.forEach((n,i)=>{i>0&&t.write(", "),t.writeNode(e.unknown(n))}),t.write("]")}writeUnknownObject({writer:t,value:r}){let n=Object.entries(r);if(n.length===0){t.write("{}");return}t.write("{"),n.forEach(([i,o],s)=>{s>0&&t.write(", "),t.write(`"${i}": `),t.writeNode(e.unknown(o))}),t.write("}")}};function NDm({entries:e}){return e.filter(t=>!WSe.isNop(t.key)&&!WSe.isNop(t.value))}function kDm({entries:e}){return e.filter(t=>!WSe.isNop(t.value))}function ymo({values:e}){return e.filter(t=>!WSe.isNop(t))}function QDm(e){return new Zft(e)}function jDm(e){return new OMn(e)}function MDm(e){return new ldt(e)}function LDm(e){return new USe(e)}function UDm(e){return new tdt(e)}function zDm(e){return new ndt(e)}function VDm(e){return new Fne(e)}function qDm(e){return new GSe(e)}function GDm(e){return new zSe(e)}function WDm(e){return new hfe(e)}function $Dm(e){return new rdt(e)}function HDm(e){return new idt(e)}function KDm(e){return new odt(e)}function JDm(e){return new qSe(e)}function YDm(e){return new edt(e)}function XDm(e){return new udt(e)}function ZDm(e){return new VSe(e)}function eRm(e){return new adt(e)}function tRm(e){return new cdt(e)}Bi();St();var rRm="value",PMn=class{context;constructor({context:t}){this.context=t}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?fn.TypeInstantiation.none():(this.context.errors.add({severity:Ir.Critical,message:"Expected non-null value, but got null"}),fn.TypeInstantiation.nop());if(t.value===void 0)return fn.TypeInstantiation.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value});case"literal":return this.convertLiteral({literalType:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value});case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?fn.TypeInstantiation.nop():this.convertNamed({named:r,value:t.value,as:t.as})}case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as});case"set":return this.convertSet({set:t.typeReference.value,value:t.value});case"unknown":return fn.TypeInstantiation.unknown(t.value);default:Be(t.typeReference)}}convertLiteral({literalType:t,value:r}){switch(t.type){case"boolean":{let n=this.context.getValueAsBoolean({value:r});return n==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.bool(n)}case"string":{let n=this.context.getValueAsString({value:r});return n==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.str(n)}default:Be(t)}}convertList({list:t,value:r}){return Array.isArray(r)?fn.TypeInstantiation.list(r.map((n,i)=>{this.context.errors.scope({index:i});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}}),{multiline:!0}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),fn.TypeInstantiation.nop())}convertSet({set:t,value:r}){return Array.isArray(r)?fn.TypeInstantiation.list(r.map((n,i)=>{this.context.errors.scope({index:i});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}}),{multiline:!0}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),fn.TypeInstantiation.nop())}convertMap({map:t,value:r}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),fn.TypeInstantiation.nop()):fn.TypeInstantiation.dict(Object.entries(r).map(([n,i])=>{this.context.errors.scope(n);try{return{key:this.convert({typeReference:t.key,value:n,as:"key"}),value:this.convert({typeReference:t.value,value:i})}}finally{this.context.errors.unscope()}}),{multiline:!0})}convertNamed({named:t,value:r,as:n}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference,value:r,as:n});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:r});case"enum":return this.convertEnum({enum_:t,value:r});case"object":return this.convertObject({object_:t,value:r});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r});default:Be(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r}){let n=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(n==null)return fn.TypeInstantiation.nop();let i=n.singleDiscriminatedUnionType,o=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:n,unionVariant:i});if(o==null)return fn.TypeInstantiation.nop();let s={name:this.context.getPropertyName(t.discriminant.name),value:fn.TypeInstantiation.str(i.discriminantValue.wireValue)};return fn.TypeInstantiation.typedDict([s,...o],{multiline:!0})}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:t,unionVariant:r}){let n=this.getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r});switch(r.type){case"samePropertiesAsObject":{let i=this.context.resolveNamedType({typeId:r.typeId});if(i==null)return;if(i.type!=="object"){this.context.errors.add({severity:Ir.Critical,message:"Internal error; expected union value to be an object"});return}let o=this.convertObjectEntries({object_:i,value:t.value});return[...n,...o]}case"singleProperty":try{this.context.errors.scope(r.discriminantValue.wireValue);let i=this.context.getRecord(t.value);return i==null?[...n,{name:rRm,value:this.convert({typeReference:r.typeReference,value:t.value})}]:[...n,{name:this.context.getPropertyName(r.discriminantValue.name),value:this.convert({typeReference:r.typeReference,value:i[r.discriminantValue.wireValue]})}]}finally{this.context.errors.unscope()}case"noProperties":return n;default:Be(r)}}getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r}){return this.context.associateByWireValue({parameters:r.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(i=>{this.context.errors.scope(i.name.wireValue);try{return{name:this.context.getPropertyName(i.name.name),value:this.convert(i)}}finally{this.context.errors.unscope()}})}convertObjectEntries({object_:t,value:r}){let n=this.context.getRecord(r)??{},i=this.context.associateByWireValue({parameters:t.properties,values:n}),o=new Set(Object.keys(n)),s=i.map(a=>{this.context.errors.scope(a.name.wireValue);try{return{name:this.context.getPropertyName(a.name.name),value:this.convert(a)}}finally{this.context.errors.unscope()}});for(let a of t.properties){if(o.has(a.name.wireValue)||this.context.isOptional(a.typeReference)||this.context.isNullable(a.typeReference))continue;let u=this.synthesizeDefaultValue(a.typeReference);fn.TypeInstantiation.isNop(u)||s.push({name:this.context.getPropertyName(a.name.name),value:u})}return s}convertObject({object_:t,value:r}){let n=this.convertObjectEntries({object_:t,value:r});if(this.context.useTypedDictRequests())return fn.TypeInstantiation.typedDict(n,{multiline:!0});let i=this.context.getTypeClassReference(t.declaration);return fn.TypeInstantiation.reference(fn.instantiateClass({classReference:i,arguments_:n.map(o=>fn.methodArgument({name:o.name,value:o.value})),multiline:!0}))}convertEnum({enum_:t,value:r}){let n=this.getEnumValue({enum_:t,value:r});return n==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.str(n)}getEnumValue({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Ir.Critical,message:`Expected enum value string, got: ${typeof r}`});return}if(t.values.find(i=>i.wireValue===r)==null){this.context.errors.add({severity:Ir.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return r}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r}){let n=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r});return n??fn.TypeInstantiation.nop()}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r}){for(let n of t.types){let i=this.context.errors.size();try{let o=this.convert({typeReference:n,value:r});if(fn.TypeInstantiation.isNop(o)){this.context.errors.truncate(i);continue}return o}catch{this.context.errors.truncate(i);continue}}this.context.errors.add({severity:Ir.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}synthesizeDefaultValue(t,r=new Set){switch(t.type){case"optional":case"nullable":return fn.TypeInstantiation.nop();case"primitive":return this.synthesizeDefaultPrimitive(t.value);case"literal":return this.synthesizeDefaultLiteral(t.value);case"list":return fn.TypeInstantiation.list([]);case"set":return fn.TypeInstantiation.list([]);case"map":return fn.TypeInstantiation.dict([]);case"named":{if(r.has(t.value))return fn.TypeInstantiation.nop();let n=this.context.resolveNamedType({typeId:t.value});return n==null?fn.TypeInstantiation.nop():this.synthesizeDefaultNamed({named:n,typeId:t.value,seen:r})}case"unknown":return fn.TypeInstantiation.nop();default:Be(t)}}synthesizeDefaultPrimitive(t){switch(t){case"STRING":case"BASE_64":case"BIG_INTEGER":return fn.TypeInstantiation.str("string");case"INTEGER":case"LONG":case"UINT":case"UINT_64":return fn.TypeInstantiation.int(1);case"FLOAT":case"DOUBLE":return fn.TypeInstantiation.float(1.1);case"BOOLEAN":return fn.TypeInstantiation.bool(!0);case"DATE":return fn.TypeInstantiation.date("2024-01-15");case"DATE_TIME":return fn.TypeInstantiation.datetime("2024-01-15T09:30:00Z");case"UUID":return fn.TypeInstantiation.uuid("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32");default:Be(t)}}synthesizeDefaultLiteral(t){switch(t.type){case"boolean":return fn.TypeInstantiation.bool(t.value);case"string":return fn.TypeInstantiation.str(t.value);default:Be(t)}}synthesizeDefaultNamed({named:t,typeId:r,seen:n}){let i=new Set(n);switch(i.add(r),t.type){case"alias":return this.synthesizeDefaultValue(t.typeReference,i);case"enum":{let o=t.values[0];return o==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.str(o.wireValue)}case"object":{let o=[];for(let a of t.properties){if(this.context.isOptional(a.typeReference)||this.context.isNullable(a.typeReference))continue;let u=this.synthesizeDefaultValue(a.typeReference,i);fn.TypeInstantiation.isNop(u)||o.push({name:this.context.getPropertyName(a.name.name),value:u})}if(this.context.useTypedDictRequests())return fn.TypeInstantiation.typedDict(o,{multiline:!0});let s=this.context.getTypeClassReference(t.declaration);return fn.TypeInstantiation.reference(fn.instantiateClass({classReference:s,arguments_:o.map(a=>fn.methodArgument({name:a.name,value:a.value})),multiline:!0}))}case"discriminatedUnion":case"undiscriminatedUnion":return fn.TypeInstantiation.nop();default:Be(t)}}convertPrimitive({primitive:t,value:r,as:n}){switch(t){case"INTEGER":case"LONG":case"UINT":case"UINT_64":{let i=this.getValueAsNumber({value:r,as:n});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.int(i)}case"FLOAT":case"DOUBLE":{let i=this.getValueAsNumber({value:r});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.float(i)}case"BOOLEAN":{let i=this.getValueAsBoolean({value:r,as:n});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.bool(i)}case"BASE_64":case"BIG_INTEGER":case"STRING":{let i=this.context.getValueAsString({value:r});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.str(i)}case"UUID":{let i=this.context.getValueAsString({value:r});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.uuid(i)}case"DATE":{let i=this.context.getValueAsString({value:r});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.date(i)}case"DATE_TIME":{let i=this.context.getValueAsString({value:r});return i==null?fn.TypeInstantiation.nop():fn.TypeInstantiation.datetime(i)}default:Be(t)}}getValueAsNumber({value:t,as:r}){let n=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:n})}};St();var DMn=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({body:t,value:r}){let n={fileFields:[],bodyPropertyFields:[]},i=this.context.getRecord(r)??{};for(let o of t.properties)switch(o.type){case"file":{let s=this.getSingleFileProperty({property:o,record:i});if(fn.TypeInstantiation.isNop(s))break;n.fileFields.push({name:this.context.getPropertyName(o.name),value:s});break}case"fileArray":{let s=this.getArrayFileProperty({property:o,record:i});if(fn.TypeInstantiation.isNop(s))break;n.fileFields.push({name:this.context.getPropertyName(o.name),value:s});break}case"bodyProperty":{let s=this.getBodyProperty({property:o,record:i});if(fn.TypeInstantiation.isNop(s))break;n.bodyPropertyFields.push({name:this.context.getPropertyName(o.name.name),value:s});break}default:Be(o)}return n}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r});return n==null&&(n=`example_${t.wireValue??"file"}`),this.context.getFileFromString(n)}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});if(n==null){let i=`example_${t.wireValue??"files"}`;return fn.TypeInstantiation.list([this.context.getFileFromString(i)])}return fn.TypeInstantiation.list(n.map(i=>this.context.getFileFromString(i)))}getBodyProperty({property:t,record:r}){let n=r[t.name.wireValue];return n==null?fn.TypeInstantiation.nop():this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:n})}};var nRm=["list","set"],RMn=class e extends $v{ir;customConfig;dynamicTypeLiteralMapper;filePropertyMapper;constructor({ir:t,config:r}){super({ir:t,config:r}),this.ir=t,this.customConfig=r.customConfig??{},this.dynamicTypeLiteralMapper=new PMn({context:this}),this.filePropertyMapper=new DMn({context:this})}clone(){return new e({ir:this.ir,config:this.config})}getClassName(t){let r=t.pascalCase.safeName,n=this.getRootClientClassName();return r===n?`${n}Model`:r}getTypedDictClassName(t){return`${this.getClassName(t)}Params`}getPropertyName(t){let r=t.snakeCase.safeName;return r.startsWith("_")?"f_"+r.substring(r.lastIndexOf("_")+1):r}getMethodName(t){return nRm.includes(t.snakeCase.unsafeName)?t.snakeCase.unsafeName:t.snakeCase.safeName}getRootClientClassReference(){return fn.reference({name:this.getRootClientClassName(),modulePath:this.getRootModulePath()})}getTypeClassReference(t){let r=this.getClassName(t.name),n=[...this.getRootModulePath(),...t.fernFilepath.allParts.map(i=>i.snakeCase.safeName)];return fn.reference({name:r,modulePath:n})}useTypedDictRequests(){return this.customConfig.use_typeddict_requests===!0}getRootClientClassName(){return this.customConfig.client?.exported_class_name!=null?this.customConfig.client.exported_class_name:this.customConfig.client_class_name!=null?this.customConfig.client_class_name:this.customConfig.client?.class_name!=null?this.customConfig.client.class_name:this.pascalCase(this.config.organization)+this.pascalCase(this.config.workspaceName)}getEnvironmentClassName(){return`${this.getRootClientClassName()}Environment`}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return fn.accessAttribute({lhs:this.getEnvironmentClassReference(),rhs:fn.codeBlock(this.getEnvironmentEnumName(r))})}getEnvironmentClassReference(){return fn.reference({name:this.getEnvironmentClassName(),modulePath:this.getEnvironmentModulePath()})}getEnvironmentEnumName(t){return t.screamingSnakeCase.safeName}isPrimitive(t){switch(t.type){case"primitive":return!0;case"optional":case"nullable":return this.isPrimitive(t.value);case"named":{let r=this.resolveNamedType({typeId:t.value});if(r==null)return!1;switch(r.type){case"alias":return this.isPrimitive(r.typeReference);case"discriminatedUnion":case"undiscriminatedUnion":case"object":case"enum":return!1;default:Be(r)}break}case"list":case"set":case"map":case"literal":case"unknown":return!1;default:Be(t)}}getFileFromString(t){return fn.TypeInstantiation.str(t)}getRootModulePath(){if(this.customConfig.package_name!=null)return[this.customConfig.package_name];let t=this.cleanOrganizationName();return this.customConfig.use_api_name_in_package?[t,this.getApiName()]:[t]}getCoreModulePath(){return this.getRootModulePath().concat("core")}getEnvironmentModulePath(){return this.getRootModulePath().concat("environment")}shouldInlinePathParameters(){return!0}cleanOrganizationName(){return this.config.organization.replace(/[^a-zA-Z0-9]/g,"_")}getApiName(){return uOe(this.config.workspaceName)}pascalCase(t){let r=qn(t);return r.charAt(0).toUpperCase()+r.slice(1)}};St();var iRm={type:"primitive",value:"STRING"},oRm=["example"],RYu="client",pdt="request",FMn=class{context;constructor({context:t}){this.context=t}async generateSnippet({endpoint:t,request:r}){return this.buildPythonFile({endpoint:t,snippet:r}).toString()}generateSnippetSync({endpoint:t,request:r}){return this.buildPythonFile({endpoint:t,snippet:r}).toString()}async generateSnippetAst({endpoint:t,request:r}){return this.buildPythonFile({endpoint:t,snippet:r})}generateMethodCallSnippetAst({endpoint:t,request:r}){return this.callMethod({endpoint:t,snippet:r})}buildPythonFile({endpoint:t,snippet:r}){return fn.file({path:oRm,statements:[this.constructClient({endpoint:t,snippet:r}),this.callMethod({endpoint:t,snippet:r})]})}constructClient({endpoint:t,snippet:r}){return fn.assign({lhs:fn.reference({name:RYu}),rhs:fn.instantiateClass({classReference:this.context.getRootClientClassReference(),arguments_:this.getConstructorArgs({endpoint:t,snippet:r}).map(n=>fn.methodArgument({name:n.name,value:n.value})),multiline:!0})})}getConstructorArgs({endpoint:t,snippet:r}){let n=[],i=this.getConstructorEnvironmentArgs({baseUrl:r.baseURL,environment:r.environment});return i.length>0&&n.push(...i),t.auth!=null&&(r.auth!=null?n.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Ir.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`})),this.context.errors.scope(Lo.PathParameters),this.context.ir.pathParameters!=null&&n.push(...this.getPathParameters({namedParameters:this.context.ir.pathParameters,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),n}getConstructorEnvironmentArgs({baseUrl:t,environment:r}){let n=this.getEnvironmentValue({baseUrl:t,environment:r});return n==null?[]:r!=null&&this.context.isMultiEnvironmentValues(r)?[{name:"environment",value:n}]:[{name:this.getEnvironmentOptionName({environment:r}),value:n}]}getEnvironmentValue({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null)return fn.TypeInstantiation.str(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);if(n==null){this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return fn.TypeInstantiation.reference(n)}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?fn.TypeInstantiation.reference(fn.instantiateClass({classReference:this.context.getEnvironmentClassReference(),arguments_:Object.entries(r).map(([n,i])=>({name:n,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:iRm,value:i})})).map(n=>fn.methodArgument({name:n.name,value:n.value})),multiline:!0})):void 0}}getConstructorAuthArgs({auth:t,values:r}){switch(t.type){case"basic":return r.type!=="basic"?(this.addAuthMismatchError(t,r),[]):this.getConstructorBasicAuthArg({auth:t,values:r});case"bearer":return r.type!=="bearer"?(this.addAuthMismatchError(t,r),[]):this.getConstructorBearerAuthArgs({auth:t,values:r});case"header":return r.type!=="header"?(this.addAuthMismatchError(t,r),[]):this.getConstructorHeaderAuthArgs({auth:t,values:r});case"oauth":return r.type!=="oauth"?(this.addAuthMismatchError(t,r),[]):this.getConstructorOAuthArgs({auth:t,values:r});case"inferred":return r.type!=="inferred"?(this.addAuthMismatchError(t,r),[]):this.getConstructorInferredAuthArgs({auth:t,values:r});default:Be(t)}}addAuthMismatchError(t,r){this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:r}).message})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:r}){return[{name:this.context.getPropertyName(t.username),value:fn.TypeInstantiation.str(r.username)},{name:this.context.getPropertyName(t.password),value:fn.TypeInstantiation.str(r.password)}]}getConstructorBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.token),value:fn.TypeInstantiation.str(r.token)}]}getConstructorHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.header.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value})}]}getConstructorOAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.clientId),value:fn.TypeInstantiation.str(r.clientId)},{name:this.context.getPropertyName(t.clientSecret),value:fn.TypeInstantiation.str(r.clientSecret)}]}getConstructorInferredAuthArgs({auth:t,values:r}){let n=t.parameters??[];if(n.length===0)return this.addWarning("Inferred auth scheme is missing parameters; cannot generate constructor arguments."),[];let i=r.values;if(i==null)return this.addWarning("Inferred auth values were not provided; cannot generate constructor arguments."),[];let o=[];for(let s of n){let a=s.name.wireValue;if(!Object.hasOwn(i,a)){this.addWarning(`Missing inferred auth value for ${a}`);continue}let u=i[a],c=this.context.dynamicTypeLiteralMapper.convert({typeReference:s.typeReference,value:u});fn.TypeInstantiation.isNop(c)||o.push({name:this.context.getPropertyName(s.name.name),value:c})}return o}getConstructorHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getConstructorHeaderArg({header:i,value:o});s!=null&&n.push(s)}return n}getConstructorHeaderArg({header:t,value:r}){let n=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:r});if(!fn.TypeInstantiation.isNop(n))return{name:this.context.getPropertyName(t.name.name),value:n}}callMethod({endpoint:t,snippet:r}){return fn.invokeMethod({on:fn.reference({name:RYu}),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:r}).filter(n=>!fn.TypeInstantiation.isNop(n.value)).map(n=>fn.methodArgument({name:n.name,value:n.value})),multiline:!0})}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[...this.context.ir.pathParameters??[],...t.pathParameters??[]],o=new Set;if(t.body!=null){let s=this.getBodyRequestArgs({body:t.body,value:r.requestBody});if(o=new Set(s.map(a=>a.name)),t.body.type==="typeReference"){let a=t.body.value;if(a.type==="named"){let u=this.context.resolveNamedType({typeId:a.value});if(u!=null&&u.type==="object")for(let c of u.properties)this.resolvesToLiteralType(c.typeReference)||o.add(this.context.getPropertyName(c.name.name))}}}if(i.length>0){let a=this.getPathParameters({namedParameters:i,snippet:r}).map(u=>o.has(u.name)?{...u,name:u.name+"_"}:u);n.push(...a)}return this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),t.body!=null&&n.push(...this.getBodyRequestArgs({body:t.body,value:r.requestBody})),this.context.errors.unscope(),n}getBodyRequestArgs({body:t,value:r}){switch(t.type){case"bytes":return[{name:pdt,value:this.getBytesBodyRequestTypeInstantiation({value:r})}];case"typeReference":return this.getBodyRequestArgsForTypeReference({typeReference:t.value,value:r});default:Be(t)}}getBodyRequestArgsForTypeReference({typeReference:t,value:r}){switch(t.type){case"named":{let n=this.context.resolveNamedType({typeId:t.value});return n==null?[]:this.getBodyRequestArgsForNamedTypeReference({typeReference:t,named:n,value:r})}case"nullable":case"optional":{let n=t.value;return n.type==="named"&&this.context.resolveNamedType({typeId:n.value})?.type==="object"?[{name:pdt,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:n,value:r})}]:this.getBodyRequestArgsForTypeReference({typeReference:t.value,value:r})}case"list":case"map":case"set":case"literal":case"primitive":case"unknown":return[{name:pdt,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t,value:r})}];default:Be(t)}}getBodyRequestArgsForNamedTypeReference({typeReference:t,named:r,value:n}){switch(r.type){case"alias":return this.getBodyRequestArgsForTypeReference({typeReference:r.typeReference,value:n});case"enum":case"discriminatedUnion":case"undiscriminatedUnion":return[{name:pdt,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t,value:n})}];case"object":return this.context.customConfig.inline_request_params===!1?[{name:pdt,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t,value:n})}]:this.context.associateByWireValue({parameters:r.properties,values:this.context.getRecord(n)??{}}).filter(s=>!this.resolvesToLiteralType(s.typeReference)).map(s=>({name:this.context.getPropertyName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert(s)}));default:Be(r)}}resolvesToLiteralType(t){switch(t.type){case"literal":return!0;case"optional":case"nullable":return this.resolvesToLiteralType(t.value);case"named":{let r=this.context.resolveNamedType({typeId:t.value});return r==null?!1:r.type==="alias"?this.resolvesToLiteralType(r.typeReference):!1}case"list":case"map":case"set":case"primitive":case"unknown":return!1;default:Be(t)}}getBodyRequestArgsForBytes({body:t,value:r}){let n=this.getBytesBodyRequestTypeInstantiation({value:r});return fn.TypeInstantiation.isNop(n)?[]:[{name:pdt,value:n}]}getBytesBodyRequestTypeInstantiation({value:t}){return typeof t!="string"?(this.context.errors.add({severity:Ir.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),fn.TypeInstantiation.nop()):fn.TypeInstantiation.bytes(t)}getBodyPropertyNamesForInlinedRequest(t){if(t.body==null)return new Set;switch(t.body.type){case"referenced":{let r=t.body.bodyType;if(r.type!=="typeReference")return new Set;let n=r.value;if(n.type!=="named")return new Set;let i=this.context.resolveNamedType({typeId:n.value});if(i==null||i.type!=="object")return new Set;let o=new Set;for(let s of i.properties)this.resolvesToLiteralType(s.typeReference)||o.add(this.context.getPropertyName(s.name.name));return o}case"properties":return new Set(t.body.value.filter(r=>!this.resolvesToLiteralType(r.typeReference)).map(r=>this.context.getPropertyName(r.name.name)));case"fileUpload":return new Set(t.body.properties.filter(r=>r.type==="bodyProperty").map(r=>this.context.getPropertyName(r.name.name)));default:Be(t.body)}}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[],i=this.context.shouldInlinePathParameters();this.context.errors.scope(Lo.PathParameters);let o=[];t.pathParameters!=null&&o.push(...this.getPathParameters({namedParameters:t.pathParameters,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let s=this.getFilePropertyInfo({request:t,snippet:r});this.context.errors.unscope();let a=this.getBodyPropertyNamesForInlinedRequest(t),u=o.map(c=>a.has(c.name)?{...c,name:`${c.name}_`}:c);return this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})||n.push(...u),this.context.needsRequestParameter({request:t,inlinePathParameters:i,inlineFileProperties:!0})&&n.push(...this.getInlinedRequestArgs({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})?u:[],filePropertyInfo:s})),n}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArgs({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Lo.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicTypeLiteralMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.Headers);let u=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicTypeLiteralMapper.convert(l)}));this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let c=t.body!=null?this.getInlinedRequestBodyObjectFields({body:t.body,value:r.requestBody,filePropertyInfo:i}):[];return this.context.errors.unscope(),[...n,...s,...u,...c]}getInlinedRequestBodyObjectFields({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyObjectFields({parameters:t.value,value:r});case"referenced":return this.getReferencedRequestBodyPropertyTypeInstantiation({body:t,value:r});case"fileUpload":return this.getFileUploadRequestBodyObjectFields({filePropertyInfo:n});default:Be(t)}}getFileUploadRequestBodyObjectFields({filePropertyInfo:t}){return[...t.fileFields,...t.bodyPropertyFields]}getReferencedRequestBodyPropertyTypeInstantiation({body:t,value:r}){let n=t.bodyType;switch(n.type){case"bytes":return this.getBodyRequestArgsForBytes({body:t,value:r});case"typeReference":return this.getBodyRequestArgsForTypeReference({typeReference:n.value,value:r});default:Be(n)}}getInlinedRequestBodyPropertyObjectFields({parameters:t,value:r}){let n=[],o=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}}).filter(s=>!this.resolvesToLiteralType(s.typeReference));for(let s of o)n.push({name:this.context.getPropertyName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert(s)});return n}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=t.filter(s=>!this.resolvesToLiteralType(s.typeReference)),o=this.context.associateByWireValue({parameters:i,values:r.pathParameters??{},ignoreMissingParameters:!0});for(let s of o)n.push({name:this.context.getPropertyName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert(s)});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getMethodName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getEnvironmentOptionName({environment:t}){return t!=null?"environment":"base_url"}};var RLt=class extends Wv{constructor({ir:t,config:r}){super(new RMn({ir:t,config:r}))}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t,r={}){return super.generateSnippetAst(t,r)}generateMethodCallSnippetAst({request:t,options:r={}}){let n=this.resolveEndpointsForMethodCall({request:t,options:r});if(n.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let i;for(let o of n){let s=this.context.clone(),a=this.createSnippetGenerator(s);try{return a.generateMethodCallSnippetAst({endpoint:o,request:t})}catch(u){i=u}}throw i??new Error(`Failed to generate method call snippet AST for endpoint: ${t.endpoint.method} ${t.endpoint.path}`)}resolveEndpointsForMethodCall({request:t,options:r}){if(r.endpointId!=null){let n=this.context.resolveEndpointById(r.endpointId);if(n==null)throw new Error(`No endpoint found with ID "${r.endpointId}"`);return[n]}return this.context.resolveEndpointLocationOrThrow(t.endpoint)}createSnippetGenerator(t){return new FMn({context:t})}};var kMn=require("fs/promises"),FYu=Ae(require("path"),1);var NMn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new RLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");for(let[n,{endpointId:i,request:o}]of r.entries())try{let s=pS(o);if(s==null)continue;let a=await this.dynamicSnippetsGenerator.generate(s,{endpointId:i}),u=this.getTestFilePath({outputDir:t,idx:n});await(0,kMn.mkdir)(FYu.default.dirname(u),{recursive:!0}),await(0,kMn.writeFile)(u,a.snippet)}catch(s){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(o.endpoint)}: ${s}`)}this.context.logger.debug("Done generating dynamic snippet tests")}getTestFilePath({outputDir:t,idx:r}){return Ge(t,Se.of(`dynamic_snippets/example${r}.py`))}};qt();var sRm=2,BV=class extends wC{customConfig;formatter;requires=new Set;_indentLevel=0;constructor({customConfig:t,formatter:r}){super(),this.customConfig=t,this.formatter=r??new B7}addRequire(t){this.requires.add(t)}get currentIndentLevel(){return this._indentLevel}indent(){this._indentLevel++,super.indent()}dedent(){this._indentLevel--,super.dedent()}writeNodeStatement(t){this.writeNode(t),this.writeNewLineIfLastLineNot()}getTabSize(){return sRm}};var fdt=class extends BV{constructor({customConfig:t,formatter:r}){super({customConfig:t,formatter:r})}async toStringAsync(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.format(t)}catch(r){throw new Error(`Failed to format Ruby file: ${r}
2551
2551
  ${t}`)}return t}toString(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.formatSync(t)}catch(r){throw new Error(`Failed to format Ruby file: ${r}
2552
2552
  ${t}`)}return t}getContent(){let t=this.stringifyRequires();return t.length>0?`${t}
2553
2553
 
@@ -2557,7 +2557,7 @@ ${this.buffer}`:this.buffer}stringifyRequires(){return Array.from(this.requires)
2557
2557
  `,`
2558
2558
  `);r.includes('"')&&!r.includes("'")&&!r.includes("#")?t.write(`'${r}'`):t.write(`"${r.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`);break}case"int":{t.write(this.internalType.value.toString());break}case"float":{t.write(this.internalType.value.toString());break}case"bool":{t.write(this.internalType.value?"true":"false");break}case"hash":{let r=this.internalType.entries.filter(n=>!e.isNop(n.key)&&!e.isNop(n.value));if(r.length===0){t.write("{}");break}t.write(`{
2559
2559
  `),r.forEach((n,i)=>{i>0&&t.writeLine(","),t.indent();let o=!1;if(n.key instanceof e&&n.key.internalType.type==="str"){let s=n.key.internalType.value;/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)&&(t.write(`${s}:`),o=!0)}o||(n.key.write(t),t.write(" =>")),t.write(" "),n.value.write(t),t.dedent()}),t.write(`
2560
- }`);break}case"set":{let r=this.internalType.values.filter(n=>!e.isNop(n));if(r.length===0){t.write("Set.new([])");break}t.write("Set.new(["),r.forEach((n,i)=>{i>0&&t.write(", "),n.write(t)}),t.write("])");break}case"list":{let r=this.internalType.values.filter(n=>!e.isNop(n));if(r.length===0){t.write("[]");break}if(r.length>=2&&r.every(n=>n instanceof e&&n.internalType.type==="str"&&!/[\s\\[\]]/.test(n.internalType.value))){let n=r.map(i=>i.internalType.value);t.write(`%w[${n.join(" ")}]`);break}t.write("["),r.forEach((n,i)=>{i>0&&t.write(", "),n.write(t)}),t.write("]");break}case"nop":break;case"nil":t.write("nil");break;default:Be(this.internalType)}}};var MMn;(function(e){e[e.Invariant=0]="Invariant",e.Covariant="out",e.Contravariant="in"})(MMn||(MMn={}));var VMe=class extends df{name;unchecked;bound;variance;defaultType;constructor({name:t,unchecked:r,bound:n,variance:i,defaultType:o}){super(),this.name=t,this.unchecked=r??!1,this.bound=n,this.variance=i??MMn.Invariant,this.defaultType=o}write(t){}writeTypeDefinition(t){this.unchecked&&t.write("unchecked "),this.variance!=MMn.Invariant&&t.write(`${this.variance} `),t.write(this.name),this.bound&&(t.write(" < "),this.bound.writeTypeDefinition(t)),this.defaultType&&(t.write(" = "),this.defaultType.writeTypeDefinition(t))}};var MLt=class extends rF{initializer;write(t){t.write(`&${this.name}`)}};var LMn=class extends df{errorClass;message;constructor({errorClass:t,message:r}){super(),this.errorClass=t,this.message=r}write(t){t.write("raise"),this.errorClass&&(t.write(" "),this.errorClass.write(t)),this.message&&(this.errorClass&&t.write(", "),this.message.write(t))}};function UMn(e){return new MMe(e)}function cRm(){return UMn("true")}function lRm(){return UMn("false")}function pRm(){return UMn("nil")}var fRm={positional(e){return new kLt(e)},keyword(e){return new UMe(e)},positionalSplat(e){return new QLt(e)},keywordSplat(e){return new FLt(e)},yield(e){return new MLt(e)}};function dRm(e){return new vfe(e)}function mRm(e){return new Efe(e)}function hRm(e){return new bfe(e)}function gRm(e){return new Q7(e)}function ARm(e){return new VMe(e)}function yRm(e){return new gfe(e)}function bRm(e){return new jMe(e)}function ERm(e){return new LMe(e)}function vRm(e){return new zMe(e)}function IRm(e){return new NLt(e)}function wRm(e){return new jMn(e)}function CRm(e){return new QMn(e)}function xRm(e){return new LMn(e)}function _Rm(e,t){let r=e;for(let n of t.toReversed())n.addStatement(r),r=n;return r}Bi();St();var zMn=class e{context;constructor({context:t}){this.context=t}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?Zn.TypeLiteral.nil():(this.context.errors.add({severity:Ir.Critical,message:"Expected non-null value, but got null"}),Zn.TypeLiteral.nop());if(t.value===void 0)return Zn.TypeLiteral.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value});case"literal":return this.convertLiteral({literalType:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value});case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?Zn.TypeLiteral.nop():this.convertNamed({named:r,value:t.value,as:t.as})}case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as});case"set":return this.convertSet({set:t.typeReference.value,value:t.value});case"unknown":return Zn.TypeLiteral.nop();default:Be(t.typeReference)}}convertLiteral({literalType:t,value:r}){switch(t.type){case"boolean":{let n=this.context.getValueAsBoolean({value:r});return n==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.boolean(n)}case"string":{let n=this.context.getValueAsString({value:r});return n==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.string(n)}default:Be(t)}}convertList({list:t,value:r}){return Array.isArray(r)?Zn.TypeLiteral.list(r.map((n,i)=>{this.context.errors.scope({index:i});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}})):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),Zn.TypeLiteral.nop())}convertSet({set:t,value:r}){return Array.isArray(r)?Zn.TypeLiteral.set(r.map((n,i)=>{this.context.errors.scope({index:i});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}})):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),Zn.TypeLiteral.nop())}convertMap({map:t,value:r}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),Zn.TypeLiteral.nop()):Zn.TypeLiteral.hash(Object.entries(r).map(([n,i])=>{this.context.errors.scope(n);try{return{key:this.convert({typeReference:t.key,value:n,as:"key"}),value:this.convert({typeReference:t.value,value:i})}}finally{this.context.errors.unscope()}}))}convertNamed({named:t,value:r,as:n}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference,value:r,as:n});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:r});case"object":return this.convertObject({object:t,value:r});case"enum":return this.convertEnum({enum_:t,value:r});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r});default:Be(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r}){let n=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(n==null)return Zn.TypeLiteral.nop();let i=n.singleDiscriminatedUnionType,o=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:n,unionVariant:i});return o==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.hash(o)}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:t,unionVariant:r}){switch(r.type){case"samePropertiesAsObject":{let n=this.context.resolveNamedType({typeId:r.typeId});if(n==null)return;let i=this.convertNamed({named:n,value:t.value});return this.extractHashEntries(i)}case"singleProperty":try{this.context.errors.scope(r.discriminantValue.wireValue);let n=this.context.getRecord(t.value);return n==null?[{key:Zn.TypeLiteral.string(this.context.getPropertyName(r.discriminantValue.name)),value:this.convert({typeReference:r.typeReference,value:t.value})}]:[{key:Zn.TypeLiteral.string(this.context.getPropertyName(r.discriminantValue.name)),value:this.convert({typeReference:r.typeReference,value:n[r.discriminantValue.wireValue]})}]}finally{this.context.errors.unscope()}case"noProperties":return[];default:Be(r)}}extractHashEntries(t){t instanceof Zn.TypeLiteral}convertEnum({enum_:t,value:r}){let n=this.getEnumValueName({enum_:t,value:r});return n==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.string(n)}getEnumValueName({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Ir.Critical,message:`Expected enum value string, got: ${typeof r}`});return}let n=t.values.find(i=>i.wireValue===r);if(n==null){this.context.errors.add({severity:Ir.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return n.wireValue}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r}){let n=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r});return n??Zn.TypeLiteral.nop()}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r}){for(let n of t.types){let i=this.context.clone(),s=new e({context:i}).convert({typeReference:n,value:r});if(i.errors.empty())return s}this.context.errors.add({severity:Ir.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}convertPrimitive({primitive:t,value:r,as:n}){switch(t){case"INTEGER":case"LONG":case"UINT":case"UINT_64":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.integer(i)}case"FLOAT":case"DOUBLE":{let i=this.getValueAsNumber({value:r});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.float(i)}case"BOOLEAN":{let i=this.getValueAsBoolean({value:r,as:n});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.boolean(i)}case"BASE_64":case"BIG_INTEGER":case"STRING":{let i=this.context.getValueAsString({value:r});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.string(i)}case"UUID":{let i=this.context.getValueAsString({value:r});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.string(i)}case"DATE":{let i=this.context.getValueAsString({value:r});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.string(i)}case"DATE_TIME":{let i=this.context.getValueAsString({value:r});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.string(i)}default:Be(t)}}convertObject({object:t,value:r}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),Zn.TypeLiteral.nop()):Zn.TypeLiteral.hash(Object.entries(r).map(([n,i])=>{this.context.errors.scope(n);let o=t.properties.find(c=>c.name.wireValue===n),s=o?.typeReference??{type:"unknown"},a=o?.name.name.snakeCase.safeName??n,u={key:Zn.TypeLiteral.string(a),value:this.convert({typeReference:s,value:i})};return this.context.errors.unscope(),u}))}getValueAsNumber({value:t,as:r}){let n=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="key"?typeof t=="string"?t==="true":!!t:t;return this.context.getValueAsBoolean({value:n})}};var VMn=class e extends $v{ir;customConfig;dynamicTypeLiteralMapper;constructor({ir:t,config:r}){super({ir:t,config:r}),this.ir=t,this.customConfig=r.customConfig!=null?r.customConfig:void 0,this.dynamicTypeLiteralMapper=new zMn({context:this})}clone(){return new e({ir:this.ir,config:this.config})}getRootClientClassReference(){return Zn.classReference({name:this.getRootClientClassName(),modules:[this.getRootModuleName()]})}getRootClientClassName(){return this.customConfig?.clientModuleName??"Client"}getRootModuleName(){return gc(this.customConfig?.moduleName??this.config.organization)}isSingleEnvironmentID(t){return typeof t=="string"}isMultiEnvironmentValues(t){return typeof t=="object"}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return Zn.codeblock(n=>{n.writeNode(this.getEnvironmentClassReference()),n.write("::"),n.write(this.getEnumName(r))})}getEnvironmentClassReference(){return Zn.classReference({name:"Environment",modules:[this.getRootModuleName()]})}getEnumName(t){return this.getName(t.screamingSnakeCase.safeName)}getMethodName(t){return this.getName(t.snakeCase.safeName)}getPropertyName(t){return this.getName(t.snakeCase.safeName)}getName(t){return t}};St();var QYu="client",SRm="@client",qMn=class{context;formatter;constructor({context:t,formatter:r}){this.context=t,this.formatter=r}async generateSnippet({endpoint:t,request:r}){return await this.buildCodeBlock({endpoint:t,snippet:r}).toStringAsync({customConfig:this.context.customConfig??{},formatter:this.formatter})}generateSnippetSync({endpoint:t,request:r}){return this.buildCodeBlock({endpoint:t,snippet:r}).toString({customConfig:this.context.customConfig??{},formatter:this.formatter})}async generateSnippetAst({endpoint:t,request:r,options:n}){return n?.skipClientInstantiation?this.buildCodeBlockWithoutClient({endpoint:t,snippet:r}):this.buildCodeBlock({endpoint:t,snippet:r})}buildCodeBlock({endpoint:t,snippet:r}){return Zn.codeblock(n=>{n.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),n.newLine(),n.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))})}buildCodeBlockWithoutClient({endpoint:t,snippet:r}){return Zn.codeblock(n=>{n.writeNodeStatement(this.callMethodOnExistingClient({endpoint:t,snippet:r}))})}constructClient({endpoint:t,snippet:r}){return Zn.codeblock(n=>{n.addRequire(this.context.getRootModuleName().toLowerCase());let i=this.context.getRootClientClassReference(),o=this.getRootClientBuilderArgs({endpoint:t,snippet:r});n.write(`${QYu} = `),n.writeNode(Zn.instantiateClass({classReference:i,arguments_:o}))})}getRootClientBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null)return this.context.errors.add({severity:"CRITICAL",message:"Cannot specify both baseUrl and environment options"}),[];if(t!=null)return[Zn.keywordArgument({name:"base_url",value:Zn.TypeLiteral.string(t)})];if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);return n==null?(this.context.errors.add({severity:"CRITICAL",message:`Environment ID ${r} not found`}),[]):[Zn.keywordArgument({name:"environment",value:n})]}if(this.context.isMultiEnvironmentValues(r))return this.context.errors.add({severity:"CRITICAL",message:"Multi-environment values are not supported in Ruby snippets yet"}),[]}return[]}getRootClientAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?this.getRootClientBasicAuthArgs({auth:t,values:r}):[];case"bearer":return r.type==="bearer"?this.getRootClientBearerAuthArgs({auth:t,values:r}):[];case"header":return r.type==="header"?this.getRootClientHeaderAuthArgs({auth:t,values:r}):[];case"oauth":return r.type==="oauth"?this.getRootClientOAuthArgs({auth:t,values:r}):[];case"inferred":return[];default:Be(t)}}addError(t){this.context.errors.add({severity:Ir.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getRootClientBasicAuthArgs({auth:t,values:r}){return[Zn.keywordArgument({name:t.username.snakeCase.safeName,value:Zn.TypeLiteral.string(r.username)}),Zn.keywordArgument({name:t.password.snakeCase.safeName,value:Zn.TypeLiteral.string(r.password)})]}getRootClientBearerAuthArgs({auth:t,values:r}){return[Zn.keywordArgument({name:t.token.snakeCase.safeName,value:Zn.TypeLiteral.string(r.token)})]}getRootClientHeaderAuthArgs({auth:t,values:r}){return[Zn.keywordArgument({name:t.header.name.name.snakeCase.safeName,value:Zn.TypeLiteral.string(r.value)})]}getRootClientOAuthArgs({auth:t,values:r}){return[Zn.keywordArgument({name:t.clientId.snakeCase.safeName,value:Zn.TypeLiteral.string(r.clientId)}),Zn.keywordArgument({name:t.clientSecret.snakeCase.safeName,value:Zn.TypeLiteral.string(r.clientSecret)})]}getRootClientHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue];o!=null&&typeof o=="string"&&n.push(Zn.keywordArgument({name:i.name.name.snakeCase.safeName,value:Zn.TypeLiteral.string(o)}))}return n}getRootClientBuilderArgs({endpoint:t,snippet:r}){let n=[];t.auth!=null&&(r.auth!=null?n.push(...this.getRootClientAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:"WARNING",message:`Auth with ${t.auth.type} configuration is required for this endpoint`}));let i=this.getRootClientBaseUrlArg({baseUrl:r.baseURL,environment:r.environment});return i.length>0&&n.push(...i),this.context.errors.scope("Headers"),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),n}callMethod({endpoint:t,snippet:r}){let n={on:Zn.codeblock(QYu),method:this.getMethod({endpoint:t}),arguments_:[]};switch(t.request.type){case"inlined":n.keywordArguments=this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});break;case"body":n.keywordArguments=this.getMethodArgsForBodyRequest({request:t.request,snippet:r});break;default:Be(t.request)}let i=this.getRequestOptions({endpoint:t,snippet:r});return i!=null&&(n.keywordArguments=n.keywordArguments??[],n.keywordArguments.push(i)),Zn.invokeMethod(n)}callMethodOnExistingClient({endpoint:t,snippet:r}){let n={on:Zn.codeblock(SRm),method:this.getMethod({endpoint:t}),arguments_:[]};switch(t.request.type){case"inlined":n.keywordArguments=this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});break;case"body":n.keywordArguments=this.getMethodArgsForBodyRequest({request:t.request,snippet:r});break;default:Be(t.request)}let i=this.getRequestOptions({endpoint:t,snippet:r});return i!=null&&(n.keywordArguments=n.keywordArguments??[],n.keywordArguments.push(i)),Zn.invokeMethod(n)}getRequestOptions({endpoint:t,snippet:r}){let n=r.headers??{},i=Object.entries(n);if(i.length===0)return;let o=new Set;if(this.context.ir.headers!=null)for(let u of this.context.ir.headers)o.add(u.name.wireValue.toLowerCase());if(t.request.type==="inlined"&&t.request.headers!=null)for(let u of t.request.headers)o.add(u.name.wireValue.toLowerCase());let s=i.filter(([u])=>!o.has(u.toLowerCase()));if(s.length===0)return;let a=s.map(([u,c])=>({key:Zn.TypeLiteral.string(u),value:Zn.TypeLiteral.string(String(c))}));return Zn.keywordArgument({name:"request_options",value:Zn.TypeLiteral.hash([{key:Zn.TypeLiteral.string("additional_headers"),value:Zn.TypeLiteral.hash(a)}])})}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[];if(n.push(...this.getNamedParameterArgs({kind:"PathParameters",namedParameters:t.pathParameters,values:r.pathParameters})),n.push(...this.getNamedParameterArgs({kind:"QueryParameters",namedParameters:t.queryParameters,values:r.queryParameters})),n.push(...this.getNamedParameterArgs({kind:"Headers",namedParameters:t.headers,values:r.headers})),t.body!=null&&r.requestBody!=null)switch(t.body.type){case"properties":n.push(...this.getMethodArgsForPropertiesRequest({request:t.body,snippet:r}));break;case"referenced":{let i=t.body.bodyType;if(i.type==="typeReference"){let o=i.value;if(o.type==="named"){let s=this.context.resolveNamedType({typeId:o.value});if(s!=null&&s.type==="object"){let a=this.context.getRecord(r.requestBody);if(a!=null){let u=this.getBodyFieldsAsKeywordArgs({namedType:s,bodyRecord:a});n.push(...u)}}else if(s!=null){let a=this.getBodyArgsForNonObjectType({namedType:s,typeRef:o,bodyValue:r.requestBody});n.push(...a)}}else{let s=this.context.dynamicTypeLiteralMapper.convert({typeReference:o,value:r.requestBody});Zn.TypeLiteral.isNop(s)||n.push(Zn.keywordArgument({name:t.body.bodyKey.snakeCase.safeName,value:s}))}}break}case"fileUpload":break;default:Be(t.body)}return n}getNamedParameterArgs({kind:t,namedParameters:r,values:n}){let i=[];if(this.context.errors.scope(t),r!=null){let o=this.context.associateByWireValue({parameters:r,values:n??{},ignoreMissingParameters:!0});for(let s of o){let a=this.context.dynamicTypeLiteralMapper.convert(s);Zn.TypeLiteral.isNop(a)||i.push(Zn.keywordArgument({name:this.context.getPropertyName(s.name.name),value:a}))}}return this.context.errors.unscope(),i}getMethodArgsForPropertiesRequest({request:t,snippet:r}){let n=[],i=this.context.associateByWireValue({parameters:t.value,values:this.context.getRecord(r.requestBody)??{}});for(let o of i){let s=this.context.dynamicTypeLiteralMapper.convert(o);Zn.TypeLiteral.isNop(s)||n.push(Zn.keywordArgument({name:this.context.getPropertyName(o.name.name),value:s}))}return n}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];if(n.push(...this.getNamedParameterArgs({kind:"PathParameters",namedParameters:t.pathParameters,values:r.pathParameters})),t.body!=null&&r.requestBody!=null)switch(t.body.type){case"bytes":this.context.errors.add({severity:"CRITICAL",message:"Bytes request body is not supported in Ruby snippets yet"});break;case"typeReference":{let i=t.body.value;if(i.type==="named"){let o=this.context.resolveNamedType({typeId:i.value});if(o!=null&&o.type==="object"){let s=this.context.getRecord(r.requestBody);if(s!=null){let a=this.getBodyFieldsAsKeywordArgs({namedType:o,bodyRecord:s});n.push(...a)}}else if(o!=null){let s=this.getBodyArgsForNonObjectType({namedType:o,typeRef:i,bodyValue:r.requestBody});n.push(...s)}}else{let o=this.context.dynamicTypeLiteralMapper.convert({typeReference:i,value:r.requestBody});Zn.TypeLiteral.isNop(o)||n.push(Zn.keywordArgument({name:"request",value:o}))}break}default:Be(t.body)}return n}getBodyArgsForNonObjectType({namedType:t,typeRef:r,bodyValue:n}){let i=[];switch(t.type){case"undiscriminatedUnion":{let o=this.context.getRecord(n);if(o!=null){for(let a of t.types)if(a.type==="named"){let u=this.context.resolveNamedType({typeId:a.value});if(u!=null&&u.type==="object"){let c=new Set(u.properties.map(d=>d.name.wireValue)),l=Object.keys(o);if(l.every(d=>c.has(d))&&l.length>0){let d=this.getBodyFieldsAsKeywordArgs({namedType:u,bodyRecord:o});return i.push(...d),i}}}}let s=this.context.dynamicTypeLiteralMapper.convert({typeReference:r,value:n});Zn.TypeLiteral.isNop(s)||i.push(Zn.keywordArgument({name:"request",value:s}));break}case"alias":{let o=t.typeReference;if(o.type==="named"){let a=this.context.resolveNamedType({typeId:o.value});if(a!=null&&a.type==="object"){let u=this.context.getRecord(n);if(u!=null){let c=this.getBodyFieldsAsKeywordArgs({namedType:a,bodyRecord:u});return i.push(...c),i}}}let s=this.context.dynamicTypeLiteralMapper.convert({typeReference:r,value:n});Zn.TypeLiteral.isNop(s)||i.push(Zn.keywordArgument({name:"request",value:s}));break}case"discriminatedUnion":case"enum":{let o=this.context.dynamicTypeLiteralMapper.convert({typeReference:r,value:n});Zn.TypeLiteral.isNop(o)||i.push(Zn.keywordArgument({name:"request",value:o}));break}case"object":break;default:Be(t)}return i}getBodyFieldsAsKeywordArgs({namedType:t,bodyRecord:r}){let n=[];switch(t.type){case"object":{for(let i of t.properties){let o=i.name.wireValue,s=r[o];if(s!==void 0){this.context.errors.scope(o);let a=this.context.dynamicTypeLiteralMapper.convert({typeReference:i.typeReference,value:s});this.context.errors.unscope(),Zn.TypeLiteral.isNop(a)||n.push(Zn.keywordArgument({name:this.context.getPropertyName(i.name.name),value:a}))}}break}case"alias":case"discriminatedUnion":case"undiscriminatedUnion":case"enum":break;default:Be(t)}return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>`${this.context.getMethodName(r)}`).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}};var LLt=class extends Wv{formatter;constructor({ir:t,config:r,formatter:n}){super(new VMn({ir:t,config:r})),this.formatter=n}async generate(t){return super.generate(t)}generateSync(t){return super.generateSync(t)}async generateSnippetAst(t,r){return super.generateSnippetAst(t,r)}createSnippetGenerator(t){return new qMn({context:t,formatter:this.formatter})}};var WMn=require("fs/promises"),jYu=Ae(require("path"),1);var GMn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new LLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");for(let[n,i]of r.entries())try{let o=pS(i);if(o==null)continue;let s=await this.dynamicSnippetsGenerator.generate(o),a=this.getTestFilePath({outputDir:t,idx:n});await(0,WMn.mkdir)(jYu.default.dirname(a),{recursive:!0}),await(0,WMn.writeFile)(a,s.snippet)}catch(o){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(i.endpoint)}: ${o}`),o instanceof Error&&o.stack&&this.context.logger.error(o.stack)}this.context.logger.debug("Done generating dynamic snippet tests")}getTestFilePath({outputDir:t,idx:r}){return Ge(t,Se.of(`dynamic-snippets/example${r}/snippet.rb`))}};var $Lt=require("fs/promises"),oXu=Ae(require("path"),1);qt();var bmo=new Set(["as","break","const","continue","crate","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","unsafe","use","where","while","abstract","async","await","become","box","do","dyn","final","macro","override","priv","try","typeof","unsized","virtual","yield"]);var MYu=new Set(["Box","Option","Result","Vec","HashMap","HashSet","String","str","i8","i16","i32","i64","i128","u8","u16","u32","u64","u128","f32","f64","bool","char","usize","isize"]);St();var ULt="filename_id:",zLt="typename_id:",BRm="clientname_id:",VLt=class e{static reservedFilenames=["lib","mod","main","test","prelude","error","environment","client","config","core"];static create(){return new e(e.reservedFilenames)}filenameRegistry;typenameRegistry;clientNameRegistry;constructor(t){this.filenameRegistry=new GC({reservedSymbolNames:t,conflictResolutionStrategy:"underscore-suffix"}),this.typenameRegistry=new GC({reservedSymbolNames:[],conflictResolutionStrategy:"numbered-suffix"}),this.clientNameRegistry=new GC({reservedSymbolNames:[],conflictResolutionStrategy:"numbered-suffix"})}registerSchemaTypeFilename(t,r){return this.filenameRegistry.registerSymbol(this.getSchemaTypeFilenameId(t),[r,`${r}_type`,`${r}_model`])}registerSchemaTypeTypeName(t,r){return this.typenameRegistry.registerSymbol(this.getSchemaTypeTypeNameId(t),[r])}registerInlineRequestFilename(t,r){return this.filenameRegistry.registerSymbol(this.getInlineRequestFilenameId(t),[r,`${r}_request`,`${r}_body`])}registerQueryRequestFilename(t,r){return this.filenameRegistry.registerSymbol(this.getQueryRequestFilenameId(t),[r,`${r}_query`,`${r}_params`])}registerInlineRequestTypeName(t,r){return this.typenameRegistry.registerSymbol(this.getInlineRequestTypeNameId(t),[r])}registerQueryRequestTypeName(t,r){return this.typenameRegistry.registerSymbol(this.getQueryRequestTypeNameId(t),[r])}registerFileUploadRequestFilename(t,r){return this.filenameRegistry.registerSymbol(this.getFileUploadRequestFilenameId(t),[r,`${r}_upload`,`${r}_file_request`])}registerFileUploadRequestTypeName(t,r){return this.typenameRegistry.registerSymbol(this.getFileUploadRequestTypeNameId(t),[r])}registerReferencedRequestWithQueryFilename(t,r){return this.filenameRegistry.registerSymbol(this.getReferencedRequestWithQueryFilenameId(t),[r,`${r}_request`,`${r}_with_query`])}registerReferencedRequestWithQueryTypeName(t,r){return this.typenameRegistry.registerSymbol(this.getReferencedRequestWithQueryTypeNameId(t),[r])}registerClientName(t,r){return this.clientNameRegistry.registerSymbol(this.getClientNameId(t),[r])}getSchemaTypeFilenameOrThrow(t){let r=this.filenameRegistry.getSymbolNameById(this.getSchemaTypeFilenameId(t));return Yy(r,`Filename not found for type ${t}`),`${r}.rs`}getInlineRequestFilenameOrThrow(t){let r=this.filenameRegistry.getSymbolNameById(this.getInlineRequestFilenameId(t));return Yy(r,`Filename not found for inline request ${t}`),`${r}.rs`}getQueryRequestFilenameOrThrow(t){let r=this.filenameRegistry.getSymbolNameById(this.getQueryRequestFilenameId(t));return Yy(r,`Filename not found for query request ${t}`),`${r}.rs`}getInlineRequestTypeNameOrThrow(t){let r=this.typenameRegistry.getSymbolNameById(this.getInlineRequestTypeNameId(t));return Yy(r,`Type name not found for inline request ${t}`),r}getQueryRequestTypeNameOrThrow(t){let r=this.typenameRegistry.getSymbolNameById(this.getQueryRequestTypeNameId(t));return Yy(r,`Type name not found for query request ${t}`),r}getFileUploadRequestFilenameOrThrow(t){let r=this.filenameRegistry.getSymbolNameById(this.getFileUploadRequestFilenameId(t));return Yy(r,`Filename not found for file upload request ${t}`),`${r}.rs`}getFileUploadRequestTypeNameOrThrow(t){let r=this.typenameRegistry.getSymbolNameById(this.getFileUploadRequestTypeNameId(t));return Yy(r,`Type name not found for file upload request ${t}`),r}getSchemaTypeTypeNameOrThrow(t){let r=this.typenameRegistry.getSymbolNameById(this.getSchemaTypeTypeNameId(t));return Yy(r,`Type name not found for schema type ${t}`),r}getClientNameOrThrow(t){let r=this.clientNameRegistry.getSymbolNameById(this.getClientNameId(t));return Yy(r,`Client name not found for client ${t}`),r}getClientNameOrUndefined(t){return this.clientNameRegistry.getSymbolNameById(this.getClientNameId(t))}getReferencedRequestWithQueryFilenameOrThrow(t){let r=this.filenameRegistry.getSymbolNameById(this.getReferencedRequestWithQueryFilenameId(t));return Yy(r,`Filename not found for referenced request with query ${t}`),`${r}.rs`}getReferencedRequestWithQueryTypeNameOrThrow(t){let r=this.typenameRegistry.getSymbolNameById(this.getReferencedRequestWithQueryTypeNameId(t));return Yy(r,`Type name not found for referenced request with query ${t}`),r}getSchemaTypeFilenameId(t){return`${ULt}schema_type_${t}`}getInlineRequestFilenameId(t){return`${ULt}inline_request_${t}`}getQueryRequestFilenameId(t){return`${ULt}query_request_${t}`}getInlineRequestTypeNameId(t){return`${zLt}inline_request_${t}`}getQueryRequestTypeNameId(t){return`${zLt}query_request_${t}`}getFileUploadRequestFilenameId(t){return`${ULt}file_upload_request_${t}`}getFileUploadRequestTypeNameId(t){return`${zLt}file_upload_request_${t}`}getSchemaTypeTypeNameId(t){return`${zLt}schema_type_${t}`}getClientNameId(t){return`${BRm}${t}`}getReferencedRequestWithQueryFilenameId(t){return`${ULt}referenced_request_with_query_${t}`}getReferencedRequestWithQueryTypeNameId(t){return`${zLt}referenced_request_with_query_${t}`}};Bi();function LYu(e){return e.charAt(0).toUpperCase()+qn(e).slice(1)}function Emo(e){return/^[0-9]/.test(e)?`_${e}`:bmo.has(e)?`r#${e}`:e}function UYu(e){return MYu.has(e)?`r#${e}`:e}function $Mn(e){return bmo.has(e)?`${e}_`:e}function zYu(e){let t=e.toLowerCase().replace(/[^a-z0-9_-]/g,"_").replace(/^[0-9]/,"_$&");return t=t.replace(/[_-]+/g,"_"),t=t.replace(/^_+|_+$/g,""),t||(t="rust_sdk"),t}function VYu(e,t){return`${e}_${t}`.toLowerCase()}var HMn=require("child_process");function vmo(e,t){try{let r=(0,HMn.spawnSync)("rustfmt",["--edition=2021"],{input:e,encoding:"utf8",timeout:5e3});if(r.status===0&&r.stdout)return t?.debug("rustfmt snippet formatting successful"),r.stdout;t?.debug(`rustfmt snippet formatting failed with status ${r.status}`)}catch(r){t?.debug(`rustfmt snippet formatting error: ${r}`)}return e}async function Imo(e,t){return new Promise(r=>{let n=(0,HMn.spawn)("rustfmt",["--edition=2021"],{stdio:"pipe"});n.stdin.write(e),n.stdin.end();let i="";n.stdout.on("data",o=>{i+=o.toString()}),n.on("close",o=>{o===0&&i?(t?.debug("rustfmt async snippet formatting successful"),r(i)):(t?.debug(`rustfmt async snippet formatting failed with exit code ${o}`),r(e))}),n.on("error",o=>{t?.debug(`rustfmt async snippet formatting error: ${o.message}`),r(e)})})}var OV=class{content=[];indentLevel=0;needsIndent=!0;write(t){this.needsIndent&&t.length>0&&(this.content.push(" ".repeat(this.indentLevel)),this.needsIndent=!1),this.content.push(t)}writeLine(t=""){this.write(t),this.newLine()}newLine(){this.content.push(`
2560
+ }`);break}case"set":{let r=this.internalType.values.filter(n=>!e.isNop(n));if(r.length===0){t.write("Set.new([])");break}t.write("Set.new(["),r.forEach((n,i)=>{i>0&&t.write(", "),n.write(t)}),t.write("])");break}case"list":{let r=this.internalType.values.filter(n=>!e.isNop(n));if(r.length===0){t.write("[]");break}if(r.length>=2&&r.every(n=>n instanceof e&&n.internalType.type==="str"&&!/[\s\\[\]]/.test(n.internalType.value))){let n=r.map(i=>i.internalType.value);t.write(`%w[${n.join(" ")}]`);break}t.write("["),r.forEach((n,i)=>{i>0&&t.write(", "),n.write(t)}),t.write("]");break}case"nop":break;case"nil":t.write("nil");break;default:Be(this.internalType)}}};var MMn;(function(e){e[e.Invariant=0]="Invariant",e.Covariant="out",e.Contravariant="in"})(MMn||(MMn={}));var VMe=class extends df{name;unchecked;bound;variance;defaultType;constructor({name:t,unchecked:r,bound:n,variance:i,defaultType:o}){super(),this.name=t,this.unchecked=r??!1,this.bound=n,this.variance=i??MMn.Invariant,this.defaultType=o}write(t){}writeTypeDefinition(t){this.unchecked&&t.write("unchecked "),this.variance!=MMn.Invariant&&t.write(`${this.variance} `),t.write(this.name),this.bound&&(t.write(" < "),this.bound.writeTypeDefinition(t)),this.defaultType&&(t.write(" = "),this.defaultType.writeTypeDefinition(t))}};var MLt=class extends rF{initializer;write(t){t.write(`&${this.name}`)}};var LMn=class extends df{errorClass;message;constructor({errorClass:t,message:r}){super(),this.errorClass=t,this.message=r}write(t){t.write("raise"),this.errorClass&&(t.write(" "),this.errorClass.write(t)),this.message&&(this.errorClass&&t.write(", "),this.message.write(t))}};function UMn(e){return new MMe(e)}function cRm(){return UMn("true")}function lRm(){return UMn("false")}function pRm(){return UMn("nil")}var fRm={positional(e){return new kLt(e)},keyword(e){return new UMe(e)},positionalSplat(e){return new QLt(e)},keywordSplat(e){return new FLt(e)},yield(e){return new MLt(e)}};function dRm(e){return new vfe(e)}function mRm(e){return new Efe(e)}function hRm(e){return new bfe(e)}function gRm(e){return new Q7(e)}function ARm(e){return new VMe(e)}function yRm(e){return new gfe(e)}function bRm(e){return new jMe(e)}function ERm(e){return new LMe(e)}function vRm(e){return new zMe(e)}function IRm(e){return new NLt(e)}function wRm(e){return new jMn(e)}function CRm(e){return new QMn(e)}function xRm(e){return new LMn(e)}function _Rm(e,t){let r=e;for(let n of t.toReversed())n.addStatement(r),r=n;return r}Bi();St();var zMn=class e{context;constructor({context:t}){this.context=t}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?Zn.TypeLiteral.nil():(this.context.errors.add({severity:Ir.Critical,message:"Expected non-null value, but got null"}),Zn.TypeLiteral.nop());if(t.value===void 0)return Zn.TypeLiteral.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value});case"literal":return this.convertLiteral({literalType:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value});case"named":{let r=this.context.resolveNamedType({typeId:t.typeReference.value});return r==null?Zn.TypeLiteral.nop():this.convertNamed({named:r,value:t.value,as:t.as})}case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as});case"set":return this.convertSet({set:t.typeReference.value,value:t.value});case"unknown":return Zn.TypeLiteral.nop();default:Be(t.typeReference)}}convertLiteral({literalType:t,value:r}){switch(t.type){case"boolean":{let n=this.context.getValueAsBoolean({value:r});return n==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.boolean(n)}case"string":{let n=this.context.getValueAsString({value:r});return n==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.string(n)}default:Be(t)}}convertList({list:t,value:r}){return Array.isArray(r)?Zn.TypeLiteral.list(r.map((n,i)=>{this.context.errors.scope({index:i});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}})):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),Zn.TypeLiteral.nop())}convertSet({set:t,value:r}){return Array.isArray(r)?Zn.TypeLiteral.set(r.map((n,i)=>{this.context.errors.scope({index:i});try{return this.convert({typeReference:t,value:n})}finally{this.context.errors.unscope()}})):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),Zn.TypeLiteral.nop())}convertMap({map:t,value:r}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),Zn.TypeLiteral.nop()):Zn.TypeLiteral.hash(Object.entries(r).map(([n,i])=>{this.context.errors.scope(n);try{return{key:this.convert({typeReference:t.key,value:n,as:"key"}),value:this.convert({typeReference:t.value,value:i})}}finally{this.context.errors.unscope()}}))}convertNamed({named:t,value:r,as:n}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference,value:r,as:n});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:r});case"object":return this.convertObject({object:t,value:r});case"enum":return this.convertEnum({enum_:t,value:r});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r});default:Be(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r}){let n=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(n==null)return Zn.TypeLiteral.nop();let i=n.singleDiscriminatedUnionType,o=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:n,unionVariant:i});return o==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.hash(o)}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:t,unionVariant:r}){switch(r.type){case"samePropertiesAsObject":{let n=this.context.resolveNamedType({typeId:r.typeId});if(n==null)return;let i=this.convertNamed({named:n,value:t.value});return this.extractHashEntries(i)}case"singleProperty":try{this.context.errors.scope(r.discriminantValue.wireValue);let n=this.context.getRecord(t.value);return n==null?[{key:Zn.TypeLiteral.string(this.context.getPropertyName(r.discriminantValue.name)),value:this.convert({typeReference:r.typeReference,value:t.value})}]:[{key:Zn.TypeLiteral.string(this.context.getPropertyName(r.discriminantValue.name)),value:this.convert({typeReference:r.typeReference,value:n[r.discriminantValue.wireValue]})}]}finally{this.context.errors.unscope()}case"noProperties":return[];default:Be(r)}}extractHashEntries(t){t instanceof Zn.TypeLiteral}convertEnum({enum_:t,value:r}){let n=this.getEnumValueName({enum_:t,value:r});return n==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.string(n)}getEnumValueName({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Ir.Critical,message:`Expected enum value string, got: ${typeof r}`});return}let n=t.values.find(i=>i.wireValue===r);if(n==null){this.context.errors.add({severity:Ir.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return n.wireValue}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r}){let n=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r});return n??Zn.TypeLiteral.nop()}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r}){for(let n of t.types){let i=this.context.clone(),s=new e({context:i}).convert({typeReference:n,value:r});if(i.errors.empty())return s}this.context.errors.add({severity:Ir.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}convertPrimitive({primitive:t,value:r,as:n}){switch(t){case"INTEGER":case"LONG":case"UINT":case"UINT_64":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.integer(i)}case"FLOAT":case"DOUBLE":{let i=this.getValueAsNumber({value:r});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.float(i)}case"BOOLEAN":{let i=this.getValueAsBoolean({value:r,as:n});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.boolean(i)}case"BASE_64":case"BIG_INTEGER":case"STRING":{let i=this.context.getValueAsString({value:r});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.string(i)}case"UUID":{let i=this.context.getValueAsString({value:r});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.string(i)}case"DATE":{let i=this.context.getValueAsString({value:r});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.string(i)}case"DATE_TIME":{let i=this.context.getValueAsString({value:r});return i==null?Zn.TypeLiteral.nop():Zn.TypeLiteral.string(i)}default:Be(t)}}convertObject({object:t,value:r}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),Zn.TypeLiteral.nop()):Zn.TypeLiteral.hash(Object.entries(r).map(([n,i])=>{this.context.errors.scope(n);let o=t.properties.find(c=>c.name.wireValue===n),s=o?.typeReference??{type:"unknown"},a=o?.name.name.snakeCase.safeName??n,u={key:Zn.TypeLiteral.string(a),value:this.convert({typeReference:s,value:i})};return this.context.errors.unscope(),u}))}getValueAsNumber({value:t,as:r}){let n=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="key"?typeof t=="string"?t==="true":!!t:t;return this.context.getValueAsBoolean({value:n})}};var VMn=class e extends $v{ir;customConfig;dynamicTypeLiteralMapper;constructor({ir:t,config:r}){super({ir:t,config:r}),this.ir=t,this.customConfig=r.customConfig!=null?r.customConfig:void 0,this.dynamicTypeLiteralMapper=new zMn({context:this})}clone(){return new e({ir:this.ir,config:this.config})}getRootClientClassReference(){return Zn.classReference({name:this.getRootClientClassName(),modules:[this.getRootModuleName()]})}getRootClientClassName(){return this.customConfig?.clientModuleName??"Client"}getRootModuleName(){return gc(this.customConfig?.moduleName??this.config.organization)}isSingleEnvironmentID(t){return typeof t=="string"}isMultiEnvironmentValues(t){return typeof t=="object"}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return Zn.codeblock(n=>{n.writeNode(this.getEnvironmentClassReference()),n.write("::"),n.write(this.getEnumName(r))})}getEnvironmentClassReference(){return Zn.classReference({name:"Environment",modules:[this.getRootModuleName()]})}getEnumName(t){return this.getName(t.screamingSnakeCase.safeName)}getMethodName(t){return this.getName(t.snakeCase.safeName)}getPropertyName(t){return this.getName(t.snakeCase.safeName)}getName(t){return t}};St();var QYu="client",SRm="@client",qMn=class{context;formatter;constructor({context:t,formatter:r}){this.context=t,this.formatter=r}async generateSnippet({endpoint:t,request:r}){return await this.buildCodeBlock({endpoint:t,snippet:r}).toStringAsync({customConfig:this.context.customConfig??{},formatter:this.formatter})}generateSnippetSync({endpoint:t,request:r}){return this.buildCodeBlock({endpoint:t,snippet:r}).toString({customConfig:this.context.customConfig??{},formatter:this.formatter})}async generateSnippetAst({endpoint:t,request:r,options:n}){return n?.skipClientInstantiation?this.buildCodeBlockWithoutClient({endpoint:t,snippet:r}):this.buildCodeBlock({endpoint:t,snippet:r})}buildCodeBlock({endpoint:t,snippet:r}){return Zn.codeblock(n=>{n.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),n.newLine(),n.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))})}buildCodeBlockWithoutClient({endpoint:t,snippet:r}){return Zn.codeblock(n=>{n.writeNodeStatement(this.callMethodOnExistingClient({endpoint:t,snippet:r}))})}constructClient({endpoint:t,snippet:r}){return Zn.codeblock(n=>{n.addRequire(this.context.getRootModuleName().toLowerCase());let i=this.context.getRootClientClassReference(),o=this.getRootClientBuilderArgs({endpoint:t,snippet:r});n.write(`${QYu} = `),n.writeNode(Zn.instantiateClass({classReference:i,arguments_:o}))})}getRootClientBaseUrlArg({baseUrl:t,environment:r}){if(t!=null&&r!=null)return this.context.errors.add({severity:"CRITICAL",message:"Cannot specify both baseUrl and environment options"}),[];if(t!=null)return[Zn.keywordArgument({name:"base_url",value:Zn.TypeLiteral.string(t)})];if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);return n==null?(this.context.errors.add({severity:"CRITICAL",message:`Environment ID ${r} not found`}),[]):[Zn.keywordArgument({name:"environment",value:n})]}if(this.context.isMultiEnvironmentValues(r))return this.context.errors.add({severity:"CRITICAL",message:"Multi-environment values are not supported in Ruby snippets yet"}),[]}return[]}getRootClientAuthArgs({auth:t,values:r}){if(r.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:r}).message),[];switch(t.type){case"basic":return r.type==="basic"?this.getRootClientBasicAuthArgs({auth:t,values:r}):[];case"bearer":return r.type==="bearer"?this.getRootClientBearerAuthArgs({auth:t,values:r}):[];case"header":return r.type==="header"?this.getRootClientHeaderAuthArgs({auth:t,values:r}):[];case"oauth":return r.type==="oauth"?this.getRootClientOAuthArgs({auth:t,values:r}):[];case"inferred":return[];default:Be(t)}}addError(t){this.context.errors.add({severity:Ir.Critical,message:t})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getRootClientBasicAuthArgs({auth:t,values:r}){return[Zn.keywordArgument({name:t.username.snakeCase.safeName,value:Zn.TypeLiteral.string(r.username)}),Zn.keywordArgument({name:t.password.snakeCase.safeName,value:Zn.TypeLiteral.string(r.password)})]}getRootClientBearerAuthArgs({auth:t,values:r}){return[Zn.keywordArgument({name:t.token.snakeCase.safeName,value:Zn.TypeLiteral.string(r.token)})]}getRootClientHeaderAuthArgs({auth:t,values:r}){return[Zn.keywordArgument({name:t.header.name.name.snakeCase.safeName,value:Zn.TypeLiteral.string(r.value)})]}getRootClientOAuthArgs({auth:t,values:r}){return[Zn.keywordArgument({name:t.clientId.snakeCase.safeName,value:Zn.TypeLiteral.string(r.clientId)}),Zn.keywordArgument({name:t.clientSecret.snakeCase.safeName,value:Zn.TypeLiteral.string(r.clientSecret)})]}getRootClientHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue];o!=null&&typeof o=="string"&&n.push(Zn.keywordArgument({name:i.name.name.snakeCase.safeName,value:Zn.TypeLiteral.string(o)}))}return n}getRootClientBuilderArgs({endpoint:t,snippet:r}){let n=[];t.auth!=null&&(r.auth!=null?n.push(...this.getRootClientAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:"WARNING",message:`Auth with ${t.auth.type} configuration is required for this endpoint`}));let i=this.getRootClientBaseUrlArg({baseUrl:r.baseURL,environment:r.environment});return i.length>0&&n.push(...i),this.context.errors.scope("Headers"),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),n}callMethod({endpoint:t,snippet:r}){let n={on:Zn.codeblock(QYu),method:this.getMethod({endpoint:t}),arguments_:[]};switch(t.request.type){case"inlined":n.keywordArguments=this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});break;case"body":n.keywordArguments=this.getMethodArgsForBodyRequest({request:t.request,snippet:r});break;default:Be(t.request)}let i=this.getRequestOptions({endpoint:t,snippet:r});return i!=null&&(n.keywordArguments=n.keywordArguments??[],n.keywordArguments.push(i)),Zn.invokeMethod(n)}callMethodOnExistingClient({endpoint:t,snippet:r}){let n={on:Zn.codeblock(SRm),method:this.getMethod({endpoint:t}),arguments_:[]};switch(t.request.type){case"inlined":n.keywordArguments=this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});break;case"body":n.keywordArguments=this.getMethodArgsForBodyRequest({request:t.request,snippet:r});break;default:Be(t.request)}let i=this.getRequestOptions({endpoint:t,snippet:r});return i!=null&&(n.keywordArguments=n.keywordArguments??[],n.keywordArguments.push(i)),Zn.invokeMethod(n)}getRequestOptions({endpoint:t,snippet:r}){let n=r.headers??{},i=Object.entries(n);if(i.length===0)return;let o=new Set;if(this.context.ir.headers!=null)for(let u of this.context.ir.headers)o.add(u.name.wireValue.toLowerCase());if(t.request.type==="inlined"&&t.request.headers!=null)for(let u of t.request.headers)o.add(u.name.wireValue.toLowerCase());let s=i.filter(([u])=>!o.has(u.toLowerCase()));if(s.length===0)return;let a=s.map(([u,c])=>({key:Zn.TypeLiteral.string(u),value:Zn.TypeLiteral.string(String(c))}));return Zn.keywordArgument({name:"request_options",value:Zn.TypeLiteral.hash([{key:Zn.TypeLiteral.string("additional_headers"),value:Zn.TypeLiteral.hash(a)}])})}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[];if(n.push(...this.getNamedParameterArgs({kind:"PathParameters",namedParameters:t.pathParameters,values:r.pathParameters})),n.push(...this.getNamedParameterArgs({kind:"QueryParameters",namedParameters:t.queryParameters,values:r.queryParameters})),n.push(...this.getNamedParameterArgs({kind:"Headers",namedParameters:t.headers,values:r.headers})),t.body!=null&&r.requestBody!=null)switch(t.body.type){case"properties":n.push(...this.getMethodArgsForPropertiesRequest({request:t.body,snippet:r}));break;case"referenced":{let i=t.body.bodyType;if(i.type==="typeReference"){let o=i.value;if(o.type==="named"){let s=this.context.resolveNamedType({typeId:o.value});if(s!=null&&s.type==="object"){let a=this.context.getRecord(r.requestBody);if(a!=null){let u=this.getBodyFieldsAsKeywordArgs({namedType:s,bodyRecord:a});n.push(...u)}}else if(s!=null){let a=this.getBodyArgsForNonObjectType({namedType:s,typeRef:o,bodyValue:r.requestBody});n.push(...a)}}else{let s=this.context.dynamicTypeLiteralMapper.convert({typeReference:o,value:r.requestBody});Zn.TypeLiteral.isNop(s)||n.push(Zn.keywordArgument({name:t.body.bodyKey.snakeCase.safeName,value:s}))}}break}case"fileUpload":break;default:Be(t.body)}return n}getNamedParameterArgs({kind:t,namedParameters:r,values:n}){let i=[];if(this.context.errors.scope(t),r!=null){let o=this.context.associateByWireValue({parameters:r,values:n??{},ignoreMissingParameters:!0});for(let s of o){let a=this.context.dynamicTypeLiteralMapper.convert(s);Zn.TypeLiteral.isNop(a)||i.push(Zn.keywordArgument({name:this.context.getPropertyName(s.name.name),value:a}))}}return this.context.errors.unscope(),i}getMethodArgsForPropertiesRequest({request:t,snippet:r}){let n=[],i=this.context.associateByWireValue({parameters:t.value,values:this.context.getRecord(r.requestBody)??{}});for(let o of i){let s=this.context.dynamicTypeLiteralMapper.convert(o);Zn.TypeLiteral.isNop(s)||n.push(Zn.keywordArgument({name:this.context.getPropertyName(o.name.name),value:s}))}return n}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];if(n.push(...this.getNamedParameterArgs({kind:"PathParameters",namedParameters:t.pathParameters,values:r.pathParameters})),t.body!=null&&r.requestBody!=null)switch(t.body.type){case"bytes":this.context.errors.add({severity:"CRITICAL",message:"Bytes request body is not supported in Ruby snippets yet"});break;case"typeReference":{let i=t.body.value;if(i.type==="named"){let o=this.context.resolveNamedType({typeId:i.value});if(o!=null&&o.type==="object"){let s=this.context.getRecord(r.requestBody);if(s!=null){let a=this.getBodyFieldsAsKeywordArgs({namedType:o,bodyRecord:s});n.push(...a)}}else if(o!=null){let s=this.getBodyArgsForNonObjectType({namedType:o,typeRef:i,bodyValue:r.requestBody});n.push(...s)}}else{let o=this.context.dynamicTypeLiteralMapper.convert({typeReference:i,value:r.requestBody});Zn.TypeLiteral.isNop(o)||n.push(Zn.keywordArgument({name:"request",value:o}))}break}default:Be(t.body)}return n}getBodyArgsForNonObjectType({namedType:t,typeRef:r,bodyValue:n}){let i=[];switch(t.type){case"undiscriminatedUnion":{let o=this.context.getRecord(n);if(o!=null){for(let a of t.types)if(a.type==="named"){let u=this.context.resolveNamedType({typeId:a.value});if(u!=null&&u.type==="object"){let c=new Set(u.properties.map(d=>d.name.wireValue)),l=Object.keys(o);if(l.every(d=>c.has(d))&&l.length>0){let d=this.getBodyFieldsAsKeywordArgs({namedType:u,bodyRecord:o});return i.push(...d),i}}}}let s=this.context.dynamicTypeLiteralMapper.convert({typeReference:r,value:n});Zn.TypeLiteral.isNop(s)||i.push(Zn.keywordArgument({name:"request",value:s}));break}case"alias":{let o=t.typeReference;if(o.type==="named"){let a=this.context.resolveNamedType({typeId:o.value});if(a!=null&&a.type==="object"){let u=this.context.getRecord(n);if(u!=null){let c=this.getBodyFieldsAsKeywordArgs({namedType:a,bodyRecord:u});return i.push(...c),i}}}let s=this.context.dynamicTypeLiteralMapper.convert({typeReference:r,value:n});Zn.TypeLiteral.isNop(s)||i.push(Zn.keywordArgument({name:"request",value:s}));break}case"discriminatedUnion":case"enum":{let o=this.context.dynamicTypeLiteralMapper.convert({typeReference:r,value:n});Zn.TypeLiteral.isNop(o)||i.push(Zn.keywordArgument({name:"request",value:o}));break}case"object":break;default:Be(t)}return i}getBodyFieldsAsKeywordArgs({namedType:t,bodyRecord:r}){let n=[];switch(t.type){case"object":{for(let i of t.properties){let o=i.name.wireValue,s=r[o];if(s!==void 0){this.context.errors.scope(o);let a=this.context.dynamicTypeLiteralMapper.convert({typeReference:i.typeReference,value:s});this.context.errors.unscope(),Zn.TypeLiteral.isNop(a)||n.push(Zn.keywordArgument({name:this.context.getPropertyName(i.name.name),value:a}))}}break}case"alias":case"discriminatedUnion":case"undiscriminatedUnion":case"enum":break;default:Be(t)}return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>`${this.context.getMethodName(r)}`).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}};var LLt=class extends Wv{formatter;constructor({ir:t,config:r,formatter:n}){super(new VMn({ir:t,config:r})),this.formatter=n}async generate(t,r={}){return super.generate(t,r)}generateSync(t){return super.generateSync(t)}async generateSnippetAst(t,r){return super.generateSnippetAst(t,r)}createSnippetGenerator(t){return new qMn({context:t,formatter:this.formatter})}};var WMn=require("fs/promises"),jYu=Ae(require("path"),1);var GMn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new LLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");for(let[n,{endpointId:i,request:o}]of r.entries())try{let s=pS(o);if(s==null)continue;let a=await this.dynamicSnippetsGenerator.generate(s,{endpointId:i}),u=this.getTestFilePath({outputDir:t,idx:n});await(0,WMn.mkdir)(jYu.default.dirname(u),{recursive:!0}),await(0,WMn.writeFile)(u,a.snippet)}catch(s){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(o.endpoint)}: ${s}`),s instanceof Error&&s.stack&&this.context.logger.error(s.stack)}this.context.logger.debug("Done generating dynamic snippet tests")}getTestFilePath({outputDir:t,idx:r}){return Ge(t,Se.of(`dynamic-snippets/example${r}/snippet.rb`))}};var $Lt=require("fs/promises"),oXu=Ae(require("path"),1);qt();var bmo=new Set(["as","break","const","continue","crate","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","unsafe","use","where","while","abstract","async","await","become","box","do","dyn","final","macro","override","priv","try","typeof","unsized","virtual","yield"]);var MYu=new Set(["Box","Option","Result","Vec","HashMap","HashSet","String","str","i8","i16","i32","i64","i128","u8","u16","u32","u64","u128","f32","f64","bool","char","usize","isize"]);St();var ULt="filename_id:",zLt="typename_id:",BRm="clientname_id:",VLt=class e{static reservedFilenames=["lib","mod","main","test","prelude","error","environment","client","config","core"];static create(){return new e(e.reservedFilenames)}filenameRegistry;typenameRegistry;clientNameRegistry;constructor(t){this.filenameRegistry=new GC({reservedSymbolNames:t,conflictResolutionStrategy:"underscore-suffix"}),this.typenameRegistry=new GC({reservedSymbolNames:[],conflictResolutionStrategy:"numbered-suffix"}),this.clientNameRegistry=new GC({reservedSymbolNames:[],conflictResolutionStrategy:"numbered-suffix"})}registerSchemaTypeFilename(t,r){return this.filenameRegistry.registerSymbol(this.getSchemaTypeFilenameId(t),[r,`${r}_type`,`${r}_model`])}registerSchemaTypeTypeName(t,r){return this.typenameRegistry.registerSymbol(this.getSchemaTypeTypeNameId(t),[r])}registerInlineRequestFilename(t,r){return this.filenameRegistry.registerSymbol(this.getInlineRequestFilenameId(t),[r,`${r}_request`,`${r}_body`])}registerQueryRequestFilename(t,r){return this.filenameRegistry.registerSymbol(this.getQueryRequestFilenameId(t),[r,`${r}_query`,`${r}_params`])}registerInlineRequestTypeName(t,r){return this.typenameRegistry.registerSymbol(this.getInlineRequestTypeNameId(t),[r])}registerQueryRequestTypeName(t,r){return this.typenameRegistry.registerSymbol(this.getQueryRequestTypeNameId(t),[r])}registerFileUploadRequestFilename(t,r){return this.filenameRegistry.registerSymbol(this.getFileUploadRequestFilenameId(t),[r,`${r}_upload`,`${r}_file_request`])}registerFileUploadRequestTypeName(t,r){return this.typenameRegistry.registerSymbol(this.getFileUploadRequestTypeNameId(t),[r])}registerReferencedRequestWithQueryFilename(t,r){return this.filenameRegistry.registerSymbol(this.getReferencedRequestWithQueryFilenameId(t),[r,`${r}_request`,`${r}_with_query`])}registerReferencedRequestWithQueryTypeName(t,r){return this.typenameRegistry.registerSymbol(this.getReferencedRequestWithQueryTypeNameId(t),[r])}registerClientName(t,r){return this.clientNameRegistry.registerSymbol(this.getClientNameId(t),[r])}getSchemaTypeFilenameOrThrow(t){let r=this.filenameRegistry.getSymbolNameById(this.getSchemaTypeFilenameId(t));return Yy(r,`Filename not found for type ${t}`),`${r}.rs`}getInlineRequestFilenameOrThrow(t){let r=this.filenameRegistry.getSymbolNameById(this.getInlineRequestFilenameId(t));return Yy(r,`Filename not found for inline request ${t}`),`${r}.rs`}getQueryRequestFilenameOrThrow(t){let r=this.filenameRegistry.getSymbolNameById(this.getQueryRequestFilenameId(t));return Yy(r,`Filename not found for query request ${t}`),`${r}.rs`}getInlineRequestTypeNameOrThrow(t){let r=this.typenameRegistry.getSymbolNameById(this.getInlineRequestTypeNameId(t));return Yy(r,`Type name not found for inline request ${t}`),r}getQueryRequestTypeNameOrThrow(t){let r=this.typenameRegistry.getSymbolNameById(this.getQueryRequestTypeNameId(t));return Yy(r,`Type name not found for query request ${t}`),r}getFileUploadRequestFilenameOrThrow(t){let r=this.filenameRegistry.getSymbolNameById(this.getFileUploadRequestFilenameId(t));return Yy(r,`Filename not found for file upload request ${t}`),`${r}.rs`}getFileUploadRequestTypeNameOrThrow(t){let r=this.typenameRegistry.getSymbolNameById(this.getFileUploadRequestTypeNameId(t));return Yy(r,`Type name not found for file upload request ${t}`),r}getSchemaTypeTypeNameOrThrow(t){let r=this.typenameRegistry.getSymbolNameById(this.getSchemaTypeTypeNameId(t));return Yy(r,`Type name not found for schema type ${t}`),r}getClientNameOrThrow(t){let r=this.clientNameRegistry.getSymbolNameById(this.getClientNameId(t));return Yy(r,`Client name not found for client ${t}`),r}getClientNameOrUndefined(t){return this.clientNameRegistry.getSymbolNameById(this.getClientNameId(t))}getReferencedRequestWithQueryFilenameOrThrow(t){let r=this.filenameRegistry.getSymbolNameById(this.getReferencedRequestWithQueryFilenameId(t));return Yy(r,`Filename not found for referenced request with query ${t}`),`${r}.rs`}getReferencedRequestWithQueryTypeNameOrThrow(t){let r=this.typenameRegistry.getSymbolNameById(this.getReferencedRequestWithQueryTypeNameId(t));return Yy(r,`Type name not found for referenced request with query ${t}`),r}getSchemaTypeFilenameId(t){return`${ULt}schema_type_${t}`}getInlineRequestFilenameId(t){return`${ULt}inline_request_${t}`}getQueryRequestFilenameId(t){return`${ULt}query_request_${t}`}getInlineRequestTypeNameId(t){return`${zLt}inline_request_${t}`}getQueryRequestTypeNameId(t){return`${zLt}query_request_${t}`}getFileUploadRequestFilenameId(t){return`${ULt}file_upload_request_${t}`}getFileUploadRequestTypeNameId(t){return`${zLt}file_upload_request_${t}`}getSchemaTypeTypeNameId(t){return`${zLt}schema_type_${t}`}getClientNameId(t){return`${BRm}${t}`}getReferencedRequestWithQueryFilenameId(t){return`${ULt}referenced_request_with_query_${t}`}getReferencedRequestWithQueryTypeNameId(t){return`${zLt}referenced_request_with_query_${t}`}};Bi();function LYu(e){return e.charAt(0).toUpperCase()+qn(e).slice(1)}function Emo(e){return/^[0-9]/.test(e)?`_${e}`:bmo.has(e)?`r#${e}`:e}function UYu(e){return MYu.has(e)?`r#${e}`:e}function $Mn(e){return bmo.has(e)?`${e}_`:e}function zYu(e){let t=e.toLowerCase().replace(/[^a-z0-9_-]/g,"_").replace(/^[0-9]/,"_$&");return t=t.replace(/[_-]+/g,"_"),t=t.replace(/^_+|_+$/g,""),t||(t="rust_sdk"),t}function VYu(e,t){return`${e}_${t}`.toLowerCase()}var HMn=require("child_process");function vmo(e,t){try{let r=(0,HMn.spawnSync)("rustfmt",["--edition=2021"],{input:e,encoding:"utf8",timeout:5e3});if(r.status===0&&r.stdout)return t?.debug("rustfmt snippet formatting successful"),r.stdout;t?.debug(`rustfmt snippet formatting failed with status ${r.status}`)}catch(r){t?.debug(`rustfmt snippet formatting error: ${r}`)}return e}async function Imo(e,t){return new Promise(r=>{let n=(0,HMn.spawn)("rustfmt",["--edition=2021"],{stdio:"pipe"});n.stdin.write(e),n.stdin.end();let i="";n.stdout.on("data",o=>{i+=o.toString()}),n.on("close",o=>{o===0&&i?(t?.debug("rustfmt async snippet formatting successful"),r(i)):(t?.debug(`rustfmt async snippet formatting failed with exit code ${o}`),r(e))}),n.on("error",o=>{t?.debug(`rustfmt async snippet formatting error: ${o.message}`),r(e)})})}var OV=class{content=[];indentLevel=0;needsIndent=!0;write(t){this.needsIndent&&t.length>0&&(this.content.push(" ".repeat(this.indentLevel)),this.needsIndent=!1),this.content.push(t)}writeLine(t=""){this.write(t),this.newLine()}newLine(){this.content.push(`
2561
2561
  `),this.needsIndent=!0}indent(){this.indentLevel++}dedent(){this.indentLevel>0&&this.indentLevel--}toString(){return this.content.join("")}writeBlock(t,r){this.writeLine(`${t} {`),this.indent(),r(),this.dedent(),this.writeLine("}")}};var cc=class{toString(){let t=new OV;return this.write(t),t.toString()}};var qMe=class e extends cc{name;args;nested;constructor({name:t,args:r,nested:n}){super(),this.name=t,this.args=r,this.nested=n}write(t){t.write(`#[${this.name}`),this.args&&this.args.length>0&&(t.write("("),this.args.forEach((r,n)=>{n>0&&t.write(", "),t.write(r)}),t.write(")")),this.nested&&this.nested.length>0&&(t.write("("),this.nested.forEach((r,n)=>{n>0&&t.write(", "),r.write(t)}),t.write(")")),t.write("]")}static derive(t){return new e({name:"derive",args:t})}static serde={rename:t=>new e({name:"serde",args:[`rename = ${JSON.stringify(t)}`]}),with:t=>new e({name:"serde",args:[`with = ${JSON.stringify(t)}`]}),deserializeWith:t=>new e({name:"serde",args:[`deserialize_with = ${JSON.stringify(t)}`]}),skip:()=>new e({name:"serde",args:["skip"]}),skipSerializingIf:t=>new e({name:"serde",args:[`skip_serializing_if = ${t}`]}),tag:t=>new e({name:"serde",args:[`tag = ${JSON.stringify(t)}`]}),untagged:()=>new e({name:"serde",args:["untagged"]}),flatten:()=>new e({name:"serde",args:["flatten"]}),default:()=>new e({name:"serde",args:["default"]}),content:t=>new e({name:"serde",args:[`content = ${JSON.stringify(t)}`]}),tagAndContent:(t,r)=>new e({name:"serde",args:[`tag = ${JSON.stringify(t)}`,`content = ${JSON.stringify(r)}`]}),transparent:()=>new e({name:"serde",args:["transparent"]})};static nonExhaustive(){return new e({name:"non_exhaustive"})}};var GMe=class extends cc{name;fields;constructors;methods;constructor({name:t,fields:r=[],constructors:n=[],methods:i=[]}){super(),this.name=t,this.fields=r,this.constructors=n,this.methods=i}write(t){this.writeStruct(t),t.newLine(),this.writeImpl(t)}writeStruct(t){t.write(`pub struct ${this.name} {`),t.newLine(),t.indent(),this.fields.forEach(r=>{t.write(`${r.visibility} ${r.name}: ${r.type},`),t.newLine()}),t.dedent(),t.write("}"),t.newLine()}writeImpl(t){t.write(`impl ${this.name} {`),t.newLine(),t.indent(),this.constructors.forEach(r=>{this.writeMethod(t,r),t.newLine()}),this.methods.forEach(r=>{this.writeMethod(t,r),t.newLine()}),t.dedent(),t.write("}"),t.newLine()}writeMethod(t,r){r.docs&&r.docs.write(t);let n=r.parameters?.join(", ")||"",i=r.returnType||"String",o=r.isAsync?"async ":"",s=r.name==="new"?"":"&self",a=s&&n?`${s}, ${n}`:s+n;t.write(`pub ${o}fn ${r.name}(${a}) -> ${i} {`),t.newLine(),t.indent(),r.body?t.write(r.body.toString()):t.write('todo!("Implement API call")'),t.newLine(),t.dedent(),t.write("}"),t.newLine()}};var $Se=class e extends cc{args;constructor(t){super(),this.args=t}write(t){switch(this.args.type){case"let":t.write("let "),this.args.mutable&&t.write("mut "),t.write(this.args.name),this.args.type_&&(t.write(": "),this.args.type_.write(t)),t.write(" = "),this.args.value.write(t),t.write(";");break;case"return":t.write("return"),this.args.value&&(t.write(" "),this.args.value.write(t)),t.write(";");break;case"expression":this.args.expression.write(t),t.write(";");break;case"assignment":this.args.target.write(t),t.write(" = "),this.args.value.write(t),t.write(";");break;case"if":{let r=this.args;t.write("if "),r.condition.write(t),t.write(" {"),t.newLine(),t.indent(),r.then.forEach(n=>{n.write(t),t.newLine()}),t.dedent(),t.write("}"),r.else_&&(t.write(" else {"),t.newLine(),t.indent(),r.else_.forEach(n=>{n.write(t),t.newLine()}),t.dedent(),t.write("}"));break}case"if-let":{let r=this.args;t.write("if let "),t.write(r.pattern),t.write(" = "),r.value.write(t),t.write(" {"),t.newLine(),t.indent(),r.then.forEach(n=>{n.write(t),t.newLine()}),t.dedent(),t.write("}"),r.else_&&(t.write(" else {"),t.newLine(),t.indent(),r.else_.forEach(n=>{n.write(t),t.newLine()}),t.dedent(),t.write("}"));break}case"match":{let r=this.args;t.write("match "),r.expression.write(t),t.write(" {"),t.newLine(),t.indent(),r.arms.forEach((n,i)=>{t.write(n.pattern),n.guard&&(t.write(" if "),n.guard.write(t)),t.write(" => {"),t.newLine(),t.indent(),n.body.forEach(o=>{o.write(t),t.newLine()}),t.dedent(),t.write("}"),i<r.arms.length-1&&t.write(","),t.newLine()}),t.dedent(),t.write("}");break}case"match-enhanced":{let r=this.args;t.write("match "),r.expression.write(t),t.write(" {"),t.newLine(),t.indent(),r.arms.forEach(n=>{n.write(t),t.newLine()}),t.dedent(),t.write("}");break}case"while":{let r=this.args;t.write("while "),r.condition.write(t),t.write(" {"),t.newLine(),t.indent(),r.body.forEach(n=>{n.write(t),t.newLine()}),t.dedent(),t.write("}");break}case"while-let":{let r=this.args;t.write("while let "),t.write(r.pattern),t.write(" = "),r.value.write(t),t.write(" {"),t.newLine(),t.indent(),r.body.forEach(n=>{n.write(t),t.newLine()}),t.dedent(),t.write("}");break}case"for":{let r=this.args;t.write("for "),t.write(r.pattern),t.write(" in "),r.iterable.write(t),t.write(" {"),t.newLine(),t.indent(),r.body.forEach(n=>{n.write(t),t.newLine()}),t.dedent(),t.write("}");break}case"loop":{let r=this.args;t.write("loop {"),t.newLine(),t.indent(),r.body.forEach(n=>{n.write(t),t.newLine()}),t.dedent(),t.write("}");break}case"break":{let r=this.args;t.write("break"),r.label&&(t.write(" '"),t.write(r.label)),r.value&&(t.write(" "),r.value.write(t)),t.write(";");break}case"continue":{let r=this.args;t.write("continue"),r.label&&(t.write(" '"),t.write(r.label)),t.write(";");break}case"unsafe":{let r=this.args;t.write("unsafe {"),t.newLine(),t.indent(),r.body.forEach(n=>{n.write(t),t.newLine()}),t.dedent(),t.write("}");break}case"raw":t.write(this.args.value);break}}static let(t){return new e({type:"let",...t})}static return(t){return new e({type:"return",value:t})}static expression(t){return new e({type:"expression",expression:t})}static assignment(t,r){return new e({type:"assignment",target:t,value:r})}static if(t,r,n){return new e({type:"if",condition:t,then:r,else_:n})}static match(t,r){return new e({type:"match",expression:t,arms:r})}static matchEnhanced(t,r){return new e({type:"match-enhanced",expression:t,arms:r})}static while(t,r){return new e({type:"while",condition:t,body:r})}static for(t,r,n){return new e({type:"for",pattern:t,iterable:r,body:n})}static ifLet(t,r,n,i){return new e({type:"if-let",pattern:t,value:r,then:n,else_:i})}static whileLet(t,r,n){return new e({type:"while-let",pattern:t,value:r,body:n})}static loop(t){return new e({type:"loop",body:t})}static break(t,r){return new e({type:"break",label:t,value:r})}static continue(t){return new e({type:"continue",label:t})}static unsafe(t){return new e({type:"unsafe",body:t})}static raw(t){return new e({type:"raw",value:t})}};var ddt=class e extends cc{args;constructor(t){super(),this.args=t}write(t){switch(t.write("{"),t.newLine(),t.indent(),this.args.type){case"statements":{let r=this.args;r.statements.forEach((n,i)=>{n.write(t),i<r.statements.length-1&&t.newLine()});break}case"expression":this.args.expression.write(t);break;case"empty":break}t.dedent(),t.newLine(),t.write("}")}static empty(){return new e({type:"empty"})}static fromStatements(t){return new e({type:"statements",statements:t})}static fromExpression(t){return new e({type:"expression",expression:t})}static fromStatementsAndExpression(t,r){return new e({type:"statements",statements:[...t,$Se.raw(r.toString())]})}};var WMe=class extends cc{summary;description;parameters;returns;examples;constructor({summary:t,description:r,parameters:n,returns:i,errors:o,examples:s}){super(),this.summary=this.sanitizeText(t),this.description=r?this.sanitizeText(r):void 0,this.parameters=(n??[]).map(a=>({name:a.name,description:this.sanitizeText(a.description)})),this.returns=i?this.sanitizeText(i):void 0,this.examples=(s??[]).map(a=>this.sanitizeText(a))}write(t){this.writeMultilineText(t,this.summary),this.description&&(t.write("///"),t.newLine(),this.writeMultilineText(t,this.description)),this.parameters.length>0&&(t.write("///"),t.newLine(),t.write("/// # Arguments"),t.newLine(),t.write("///"),t.newLine(),this.parameters.forEach(r=>{r.description.split(`
2562
2562
  `).forEach((i,o)=>{o===0?t.write(`/// * \`${r.name}\` - ${i.trim()}`):t.write(`/// ${i.trim()}`),t.newLine()})})),this.returns&&(t.write("///"),t.newLine(),t.write("/// # Returns"),t.newLine(),t.write("///"),t.newLine(),this.returns.split(`
2563
2563
  `).forEach(n=>{t.write(`/// ${n.trim()}`),t.newLine()})),this.examples.length>0&&(t.write("///"),t.newLine(),t.write("/// # Examples"),t.newLine(),t.write("///"),t.newLine(),this.examples.forEach(r=>{t.write("/// ```rust"),t.newLine(),this.writeMultilineText(t,r),t.write("/// ```"),t.newLine()}))}writeMultilineText(t,r){let n=r.split(`
@@ -2569,14 +2569,14 @@ ${this.buffer}`:this.buffer}stringifyRequires(){return Array.from(this.requires)
2569
2569
  `)+`
2570
2570
  `;return await Imo(i)}generateSnippetSync({endpoint:t,request:r}){let i=this.buildCodeComponents({endpoint:t,snippet:r}).join(`
2571
2571
  `)+`
2572
- `;return vmo(i)}async generateSnippetAst({endpoint:t,request:r,options:n}){throw new Error("Unsupported")}buildCodeComponents({endpoint:t,snippet:r}){let n=this.getUseStatements({endpoint:t}),i=sr.CodeBlock.fromStatements([sr.Statement.let({name:"config",value:this.getClientConfigStruct({endpoint:t,snippet:r})}),sr.Statement.let({name:iXu,value:sr.Expression.methodCall({target:sr.Expression.raw(`${this.getClientName()}::new(config)`),method:"expect",args:[sr.Expression.stringLiteral("Failed to build client")]})}),this.callMethod({endpoint:t,snippet:r})]),o=sr.standaloneFunction({name:"main",attributes:[sr.attribute({name:"tokio::main"})],parameters:[],isAsync:!0,body:i}),s=[];return n.forEach(a=>{s.push(a.toString())}),s.push(""),s.push(o.toString()),s}getUseStatements({endpoint:t}){let r=[];return r.push(new sr.UseStatement({path:`${this.context.getCrateName()}::prelude`,items:["*"]})),r}collectEndpointTypeImports(t,r){let n=t.request;if(n.pathParameters)for(let i of n.pathParameters)this.collectTypeReferenceImports(i.typeReference,r);if(n.type==="inlined"){if(n.queryParameters)for(let i of n.queryParameters)this.collectTypeReferenceImports(i.typeReference,r);if(n.headers)for(let i of n.headers)this.collectTypeReferenceImports(i.typeReference,r);n.body&&this.collectRequestBodyTypeImports(n.body,r)}else n.type==="body"&&n.body?.type==="typeReference"&&this.collectTypeReferenceImports(n.body.value,r)}collectRequestBodyTypeImports(t,r){switch(t.type){case"properties":for(let n of t.value)this.collectTypeReferenceImports(n.typeReference,r);break;case"referenced":t.bodyType.type==="typeReference"&&this.collectTypeReferenceImports(t.bodyType.value,r);break;case"fileUpload":for(let n of t.properties)n.type==="bodyProperty"&&this.collectTypeReferenceImports(n.typeReference,r);break}}collectTypesFromValue(t,r,n,i,o){if(typeof t=="object"&&t!=null&&!Array.isArray(t)){let s=t;Object.keys(s).length>0&&n.add("HashMap"),Object.keys(s).forEach(a=>{if(a==="type"||a==="_type"||a.endsWith("_type")){let u=s[a];typeof u=="string"&&this.findAndAddUnionTypes(u,r)}}),Object.values(s).forEach(a=>{this.collectTypesFromValue(a,r,n,i,o)})}else Array.isArray(t)?(t.length>0&&n.add("HashSet"),t.forEach(s=>this.collectTypesFromValue(s,r,n,i,o))):typeof t=="string"&&(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&o.add("Uuid"),/^\d{4}-\d{2}-\d{2}$/.test(t)&&i.add("NaiveDate"),/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(t)&&(i.add("DateTime"),i.add("Utc")))}findAndAddUnionTypes(t,r){Object.values(this.context.ir.types).forEach(n=>{if(n.type==="discriminatedUnion"){let i=n;if(Object.keys(i.types).includes(t)){r.add(this.context.getStructName(n.declaration.name));let o=i.types[t];if(o&&o.type==="samePropertiesAsObject"){let s=this.context.ir.types[o.typeId];s&&(r.add(this.context.getStructName(s.declaration.name)),this.collectNestedTypeImports(s,r))}}}})}collectNestedTypeImports(t,r,n=new Set){let i=t.declaration.name.pascalCase.safeName;if(!n.has(i))switch(n.add(i),t.type){case"object":r.add(this.context.getStructName(t.declaration.name));for(let o of t.properties)this.collectTypeReferenceImports(o.typeReference,r,n);break;case"alias":r.add(this.context.getStructName(t.declaration.name)),this.collectTypeReferenceImports(t.typeReference,r,n);break;case"enum":r.add(this.context.getEnumName(t.declaration.name));break;case"discriminatedUnion":case"undiscriminatedUnion":r.add(this.context.getStructName(t.declaration.name)),t.type==="discriminatedUnion"?Object.values(t.types).forEach(o=>{if(o.type==="singleProperty")this.collectTypeReferenceImports(o.typeReference,r,n);else if(o.type==="samePropertiesAsObject"){let s=this.context.ir.types[o.typeId];s&&this.collectNestedTypeImports(s,r,n)}}):t.type==="undiscriminatedUnion"&&t.types.forEach(o=>{this.collectTypeReferenceImports(o,r,n)});break}}collectTypeReferenceImports(t,r,n=new Set){switch(t.type){case"named":{let i=t.value,o=this.context.ir.types[i];o&&this.collectNestedTypeImports(o,r,n);break}case"optional":case"nullable":{let i=t.value;i&&this.collectTypeReferenceImports(i,r,n);break}case"list":{let i=t.value;i&&this.collectTypeReferenceImports(i,r,n);break}case"set":{let i=t.value;i&&this.collectTypeReferenceImports(i,r,n);break}case"map":{let i=t;i.key&&this.collectTypeReferenceImports(i.key,r,n),i.value&&this.collectTypeReferenceImports(i.value,r,n);break}case"primitive":case"literal":case"unknown":break}}getClientConfigStruct({endpoint:t,snippet:r}){let n=[],i=this.getBaseUrlValue({baseUrl:r.baseURL,environment:r.environment});if(i!=null&&n.push({name:"base_url",value:sr.Expression.methodCall({target:sr.Expression.stringLiteral(i),method:"to_string",args:[]})}),t.auth!=null&&r.auth!=null)switch(t.auth.type){case"bearer":r.auth.type==="bearer"&&n.push({name:"token",value:sr.Expression.functionCall("Some",[sr.Expression.methodCall({target:sr.Expression.stringLiteral(r.auth.token),method:"to_string",args:[]})])});break;case"basic":r.auth.type==="basic"&&(n.push({name:"username",value:sr.Expression.functionCall("Some",[sr.Expression.methodCall({target:sr.Expression.stringLiteral(r.auth.username),method:"to_string",args:[]})])}),n.push({name:"password",value:sr.Expression.functionCall("Some",[sr.Expression.methodCall({target:sr.Expression.stringLiteral(r.auth.password),method:"to_string",args:[]})])}));break;case"header":r.auth.type==="header"&&n.push({name:"api_key",value:sr.Expression.functionCall("Some",[sr.Expression.methodCall({target:sr.Expression.stringLiteral(String(r.auth.value)),method:"to_string",args:[]})])});break}return sr.Expression.structConstruction("ClientConfig",n.map(o=>({name:o.name,value:o.value})),!0)}getClientName(){return this.context.getClientStructName()}callMethod({endpoint:t,snippet:r}){return sr.Statement.expression(sr.Expression.methodCall({target:sr.Expression.reference(iXu),method:this.getMethodName({endpoint:t}),args:this.getMethodArgs({endpoint:t,snippet:r}),isAsync:!0}))}getBaseUrlValue({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null)return t;if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.resolveEnvironmentName("default");if(n==null){this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return n.snakeCase.safeName}this.context.isMultiEnvironmentValues(r)&&this.context.errors.add({severity:Ir.Warning,message:"Multi-environment values are not supported yet; use the baseUrl option instead"})}}getMethodArgs({endpoint:t,snippet:r}){let n=[];switch(t.request.type){case"inlined":n=this.getMethodArgsForInlinedRequest({endpoint:t,request:t.request,snippet:r});break;case"body":n=this.getMethodArgsForBodyRequest({request:t.request,snippet:r});break;default:Be(t.request)}return n}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[],i=this.buildRequestComponents({pathParameters:[...this.context.ir.pathParameters??[],...t.pathParameters??[]],snippet:r,body:t.body});return n.push(...i.pathArgs),i.bodyArg!=null&&n.push(sr.Expression.referenceOf(i.bodyArg)),n.push(sr.Expression.raw("None")),n}getMethodArgsForInlinedRequest({endpoint:t,request:r,snippet:n}){let i=[];this.context.errors.scope(Lo.PathParameters),this.context.scopeError("pathParameters");try{let p=[...this.context.ir.pathParameters??[],...r.pathParameters??[]];p.length>0&&i.push(...this.getPathParameterArgs({namedParameters:p,snippet:n}))}finally{this.context.unscopeError(),this.context.errors.unscope()}let o=(r.queryParameters??[]).length>0,s=r.body!=null,a=r.body,u=a!=null&&!o&&a.type==="referenced";if(o&&a!=null&&a.type==="referenced"&&a.bodyType.type==="bytes")i.push(...this.getBytesEndpointArgs({request:r,snippet:n}));else if(u&&a.type==="referenced"){let p=this.getReferencedRequestBodyPropertyExpression({body:a.bodyType,value:n.requestBody});i.push(sr.Expression.referenceOf(p))}else(o||s)&&i.push(sr.Expression.referenceOf(this.getInlinedRequestArg({endpoint:t,request:r,snippet:n})));return(r.headers??[]).length>0&&Object.keys(n.headers??{}).length>0?i.push(sr.Expression.functionCall("Some",[this.getRequestOptionsWithHeaders({request:r,snippet:n})])):i.push(sr.Expression.raw("None")),i}getBytesEndpointArgs({request:t,snippet:r}){let n=[],i=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}),o=new Map;for(let a of i){let u=this.context.getPropertyName(a.name.name);o.set(u,this.context.dynamicTypeLiteralMapper.convert(a))}let s=t.queryParameters??[];for(let a of s){let u=this.context.getPropertyName(a.name.name),c=o.get(u);c!=null?n.push(sr.Expression.referenceOf(c)):n.push(sr.Expression.referenceOf(sr.Expression.raw("None")))}return r.requestBody!=null&&typeof r.requestBody=="string"&&r.requestBody!==""?n.push(sr.Expression.referenceOf(sr.Expression.raw(`"${r.requestBody}".as_bytes().to_vec()`))):n.push(sr.Expression.referenceOf(sr.Expression.raw("vec![]"))),n}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r});default:Be(t)}}getBytesBodyRequestArg({value:t}){return typeof t!="string"?(this.context.errors.add({severity:Ir.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),sr.Expression.raw('todo!("Invalid bytes value")')):sr.Expression.stringLiteral(t)}getInlinedRequestArg({endpoint:t,request:r,snippet:n}){let i=[],o=new Set;this.context.errors.scope(Lo.QueryParameters),this.context.scopeError("queryParameters");try{let u=this.context.associateQueryParametersByWireValue({parameters:r.queryParameters??[],values:n.queryParameters??{}});for(let c of u){this.context.scopeError(c.name.wireValue);try{let l=this.context.getPropertyName(c.name.name);i.push({name:l,value:this.context.dynamicTypeLiteralMapper.convert(c)}),o.add(l)}finally{this.context.unscopeError()}}}finally{this.context.unscopeError(),this.context.errors.unscope()}if(this.context.errors.scope(Lo.RequestBody),r.body!=null){let u=this.getInlinedRequestBodyStructFields({body:r.body,value:n.requestBody});for(let c of u)i.push(c),o.add(c.name)}this.context.errors.unscope();let s=this.getCorrectRequestStructName(t,r),a=!1;return this.addMissingFields({request:r,structFields:i,providedFieldNames:o}),this.createStructExpression(s,i,a)}addMissingFields({request:t,structFields:r,providedFieldNames:n}){let i=t.queryParameters??[];for(let o of i){let s=this.context.getPropertyName(o.name.name);n.has(s)||(this.context.isOptionalType(o.typeReference)?r.push({name:s,value:sr.Expression.raw("None")}):r.push({name:s,value:this.generateDefaultValueForType(o.typeReference)}))}if(t.body!=null&&t.body.type==="properties")for(let o of t.body.value){let s=this.context.getPropertyName(o.name.name);n.has(s)||(this.context.isOptionalType(o.typeReference)?r.push({name:s,value:sr.Expression.raw("None")}):r.push({name:s,value:this.generateDefaultValueForType(o.typeReference)}))}}generateDefaultValueForType(t){switch(t.type){case"primitive":switch(t.value){case"STRING":return sr.Expression.stringLiteral("string");case"INTEGER":case"LONG":case"UINT":case"UINT_64":return sr.Expression.raw("0");case"FLOAT":case"DOUBLE":return sr.Expression.raw("0.0");case"BOOLEAN":return sr.Expression.raw("false");default:return sr.Expression.stringLiteral("default")}case"list":return sr.Expression.raw("vec![]");case"map":return sr.Expression.raw("std::collections::HashMap::new()");case"set":return sr.Expression.raw("std::collections::HashSet::new()");case"named":{let r=t.value,n=this.context.ir.types[r],i=this.context.getTypeNameById(r);if(!n)return sr.Expression.raw(`${i}("value".to_string())`);switch(n.type){case"alias":let o=this.generateDefaultValueForType(n.typeReference);return sr.Expression.raw(`${i}(${o.toString()})`);case"enum":if(n.values.length>0){let s=n.values[0];if(s){let a=s.name.pascalCase.unsafeName,u=this.context.escapeRustReservedType(a);return sr.Expression.raw(`${i}::${u}`)}}return sr.Expression.raw(`${i}::default()`);case"object":case"discriminatedUnion":case"undiscriminatedUnion":return sr.Expression.raw(`${i}::default()`);default:return sr.Expression.raw(`${i}("value".to_string())`)}}default:return sr.Expression.raw("Default::default()")}}getInlinedRequestBodyStructFields({body:t,value:r}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyStructFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyStructField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyStructFields({body:t,value:r});default:Be(t)}}getInlinedRequestBodyPropertyStructFields({parameters:t,value:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert(o)});return n}getReferencedRequestBodyPropertyStructField({body:t,value:r}){return{name:this.context.getPropertyName(t.bodyKey),value:this.getReferencedRequestBodyPropertyExpression({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyExpression({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r});default:Be(t)}}getFileUploadRequestBodyStructFields({body:t,value:r}){let n=[],i=this.context.filePropertyMapper.getFilePropertyInfo({body:t,value:r});return n.push(...i.fileFields.map(o=>({name:o.name,value:o.value}))),n.push(...i.bodyPropertyFields.map(o=>({name:o.name,value:o.value}))),n}getPathParameterArgs({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:r.pathParameters??{}});for(let o of i){let s=this.context.dynamicTypeLiteralMapper.convert(o);this.isCopyPrimitive(o.typeReference)?n.push(s):n.push(sr.Expression.referenceOf(s))}return n}isCopyPrimitive(t){if(t.type!=="primitive")return!1;switch(t.value){case"INTEGER":case"LONG":case"UINT":case"UINT_64":case"FLOAT":case"DOUBLE":case"BOOLEAN":return!0;default:return!1}}getRequestOptionsWithHeaders({request:t,snippet:r}){let n=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}),i=sr.Expression.functionCall("RequestOptions::new",[]);for(let o of n){this.context.scopeError(o.name.wireValue);try{let s=this.getHeaderValueAsString(o.value);i=sr.Expression.methodCall({target:i,method:"additional_header",args:[sr.Expression.stringLiteral(o.name.wireValue),s]})}finally{this.context.unscopeError()}}return i}getHeaderValueAsString(t){if(t==null)return sr.Expression.stringLiteral("");let r=String(t);return sr.Expression.stringLiteral(r)}buildRequestComponents({pathParameters:t,snippet:r,body:n}){let i=[],o=null;return this.context.errors.scope(Lo.PathParameters),t.length>0&&i.push(...this.getPathParameterArgs({namedParameters:t,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),n!=null&&(o=this.getBodyRequestArg({body:n,value:r.requestBody})),this.context.errors.unscope(),{pathArgs:i,bodyArg:o}}getMethodName({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getMethodName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}createStructExpression(t,r,n=!1){return this.shouldUseStructConstruction(r)?sr.Expression.structConstruction(t,r.map(i=>({name:i.name,value:i.value})),n):sr.Expression.structLiteral(t,r)}shouldUseStructConstruction(t){return!0}getCorrectRequestStructName(t,r){let n=(r.queryParameters??[]).length>0,i=r.body!=null,o=t.declaration.name.pascalCase.safeName;if(n&&!i){let s=this.context.getQueryRequestNameByEndpoint(t.declaration);return s||`${o}QueryRequest`}if(i&&r.body!=null){if(r.body.type==="referenced"&&r.body.bodyType.type==="typeReference"){let s=r.body.bodyType.value;if(s.type==="named"){let a=s.value;if(this.context.getTypeNameById(a)&&n)return`${o}Request`}}return r.body.type==="properties"?this.context.getStructNameByDeclaration(r.declaration):`${o}Request`}return this.context.getStructNameByDeclaration(r.declaration)}};var WLt=class extends Wv{constructor({ir:t,config:r,options:n={}}){super(new qLt({ir:t,config:r,options:n}))}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new GLt({context:t})}};var nLn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new WLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");let n=await this.initializeProject(t);for(let[i,o]of r.entries())try{let s=pS(o);if(s==null)continue;let a=await this.dynamicSnippetsGenerator.generate(s,{config:{},style:CC.Full}),u=this.getTestFilePath({absolutePathToOutputDir:n,idx:i});await(0,$Lt.mkdir)(oXu.default.dirname(u),{recursive:!0}),await(0,$Lt.writeFile)(u,a.snippet)}catch(s){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(o.endpoint)}: ${s}`)}this.context.logger.debug("Done generating dynamic snippet tests")}async initializeProject(t){let r=Ge(t,Se.of("dynamic-snippets"));return await(0,$Lt.mkdir)(r,{recursive:!0}),r}getTestFilePath({absolutePathToOutputDir:t,idx:r}){return Ge(t,Se.of(`example${r}.rs`))}};var XLt=require("fs/promises"),TXu=Ae(require("path"),1);qt();St();var oLn={};Z(oLn,{sanitizeForIdentifier:()=>Kmo,sanitizeToCamelCase:()=>oFm,sanitizeToPascalCase:()=>iFm});Bi();var IXu=Ae(vXu(),1);Bi();function iLn(e){return gc(qn(e))}function iFm(e){let t=Kmo(e);return iLn(t)}function oFm(e){let t=Kmo(e);return qn(t)}function Kmo(e){if(e==="")return"empty";let t=e;if(/^\d/.test(t)){let n=sFm(t);t=n.numberAsWords+gc(n.rest)}return/^[a-zA-Z][a-zA-Z0-9]*$/.test(t)||(t=t.replace(/^[^a-zA-Z0-9]+/,""),t=qn(t)),/^\d/.test(t)&&(t="value"+t),t===""?"value":t}function sFm(e){let t=e.match(/^(\d+)/);if(!t||!t[1])return{numberAsWords:"",rest:e};let r=t[1],n=e.slice(r.length);try{return{numberAsWords:(0,IXu.toWords)(parseInt(r,10)),rest:n}}catch{let i={0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"};return{numberAsWords:r.split("").map(s=>i[s]||s).join(""),rest:n}}}var nLe={};Z(nLe,{generateEnumCaseLabel:()=>uFm,generateName:()=>aFm,sanitizeLiteralValue:()=>Jmo});Bi();function aFm(e){let t=Jmo(e);return iLn(t)}function uFm(e){let t=Jmo(e);return qn(t)}function Jmo(e){if(e==="")return"empty";let t=e;return/^[a-zA-Z][a-zA-Z0-9]*$/.test(e)||(t=t.replace(/^[^a-zA-Z0-9]+/,""),t=qn(t)),/^\d/.test(t)||t===""?"value":t}var sLn=class{nameRegistry;fromSymbol;constructor(t,r){this.nameRegistry=t,this.fromSymbol=r}referenceSwiftType(t){let r=this.nameRegistry.reference({fromSymbol:this.fromSymbol,toSymbol:Br.Symbol.swiftType(t)});return Br.TypeReference.symbol(r)}referenceFoundationType(t){let r=this.nameRegistry.reference({fromSymbol:this.fromSymbol,toSymbol:Br.Symbol.foundationType(t)});return Br.TypeReference.symbol(r)}referenceAsIsType(t){let r=this.nameRegistry.getAsIsSymbolOrThrow(t),n=this.nameRegistry.reference({fromSymbol:this.fromSymbol,toSymbol:r});return Br.TypeReference.symbol(n)}referenceSourceTemplateType(t){let r=this.nameRegistry.getSourceTemplateSymbolOrThrow(t),n=this.nameRegistry.reference({fromSymbol:this.fromSymbol,toSymbol:r});return Br.TypeReference.symbol(n)}referenceType(t){let r=this.nameRegistry.reference({fromSymbol:this.fromSymbol,toSymbol:t});return Br.TypeReference.symbol(r)}resolveToSymbolIfSymbolType(t){let r=t.getReferenceIfSymbolType();return r===null?null:this.nameRegistry.resolveReference({fromSymbol:this.fromSymbol,reference:r})}resolvesToTheAsIsType(t,r){let n=this.resolveToSymbolIfSymbolType(t),i=this.nameRegistry.getAsIsSymbolOrThrow(r);return n?.id===i.id}resolvesToASwiftType(t){return this.resolveToSymbolIfSymbolType(t)?.isSwiftSymbol??!1}resolvesToTheSwiftType(t,r){return this.resolveToSymbolIfSymbolType(t)?.id===Br.Symbol.swiftType(r).id}resolvesToAFoundationType(t){return this.resolveToSymbolIfSymbolType(t)?.isFoundationSymbol??!1}resolvesToTheFoundationType(t,r){return this.resolveToSymbolIfSymbolType(t)?.id===Br.Symbol.foundationType(r).id}resolvesToACustomType(t){return this.resolveToSymbolIfSymbolType(t)?.isCustomSymbol??!1}resolvesToAnEnumWithRawValues(t){return this.resolveToSymbolIfSymbolType(t)?.shape.type==="enum-with-raw-values"}};var aLn={};Z(aLn,{inferCaseNameForTypeReference:()=>Nne});St();Bi();var cFm={String:"string",Bool:"bool",Int:"int",Int64:"int64",UInt:"uint",UInt64:"uint64",Float:"float",Double:"double",Void:"void",Encoder:"encoder",Decoder:"decoder",Any:"any"},lFm={Data:"data",Date:"date",UUID:"uuid"};function Nne(e,t,r){if(t.variant.type==="symbol"){let n=t.variant.symbol,i=r.resolveReference({fromSymbol:e,reference:n});DP(i,`Cannot find symbol ${n} for type reference ${t.variant.type}`);let o=i.name;return Br.Symbol.isSwiftSymbol(i.id)&&Br.Symbol.isSwiftSymbolName(o)?cFm[o]:Br.Symbol.isFoundationSymbol(i.id)&&Br.Symbol.isFoundationSymbolName(o)?lFm[o]:qn(o)}else if(t.variant.type==="generic"){let n=t.variant.arguments.map(i=>Nne(e,i,r));return`${Nne(e,t.variant.reference,r)}Of${gc(n.join("And"))}`}else{if(t.variant.type==="array")return`${Nne(e,t.variant.elementType,r)}Array`;if(t.variant.type==="dictionary"){let n=Nne(e,t.variant.keyType,r),i=Nne(e,t.variant.valueType,r);return`${n}To${gc(i)}Dictionary`}else if(t.variant.type==="optional"){let n=Nne(e,t.variant.valueType,r);return`optional${gc(n)}`}else if(t.variant.type==="nullable"){let n=Nne(e,t.variant.valueType,r);return`nullable${gc(n)}`}else if(t.variant.type==="tuple"){let n=t.variant.elements.map(i=>Nne(e,i,r));return`tuple${gc(n.join("And"))}`}else{if(t.variant.type==="member-access")return`${Nne(e,t.variant.target,r)}${gc(t.variant.memberName)}`;Be(t.variant)}}}St();Bi();St();var uLn=class{namespace;constructor(){this.namespace=new GC}getRequestTypeNameOrThrow(t,r){let n=this.requestTypeNameId(t,r);return this.namespace.getSymbolNameByIdOrThrow(n)}addRequestTypeSymbol(t,r,n){let i=this.requestTypeNameId(t,r);return this.namespace.registerSymbol(i,n)}requestTypeNameId(t,r){return`${t}_${r}`}};St();var cLn=class{namespace;constructor(){this.namespace=new GC}addStaticSymbolName(t){let r=this.staticSymbolNameId(t);return this.namespace.registerSymbol(r,[t])}staticSymbolNameId(t){return`Static:${t}`}addRootClientSymbolName(t){let r=this.rootClientSymbolNameId();return this.namespace.registerSymbol(r,t)}getRootClientSymbolNameOrThrow(){return this.namespace.getSymbolNameByIdOrThrow(this.rootClientSymbolNameId())}rootClientSymbolNameId(){return"RootClientClass"}addEnvironmentSymbolName(t){let r=this.environmentSymbolNameId();return this.namespace.registerSymbol(r,t)}getEnvironmentSymbolNameOrThrow(){return this.namespace.getSymbolNameByIdOrThrow(this.environmentSymbolNameId())}environmentSymbolNameId(){return"EnvironmentEnum"}addErrorEnumSymbolName(t){let r=this.errorEnumSymbolNameId();return this.namespace.registerSymbol(r,t)}getErrorEnumSymbolNameOrThrow(){return this.namespace.getSymbolNameByIdOrThrow(this.errorEnumSymbolNameId())}errorEnumSymbolNameId(){return"ErrorEnum"}addRequestsContainerSymbolName(t){let r=this.requestsContainerSymbolNameId();return this.namespace.registerSymbol(r,t)}getRequestsContainerSymbolNameOrThrow(){return this.namespace.getSymbolNameByIdOrThrow(this.requestsContainerSymbolNameId())}requestsContainerSymbolNameId(){return"RequestsContainer"}addSubClientSymbolName(t,r){let n=this.subClientSymbolNameId(t);return this.namespace.registerSymbol(n,r)}getSubClientSymbolNameOrThrow(t){return this.namespace.getSymbolNameByIdOrThrow(this.subClientSymbolNameId(t))}subClientSymbolNameId(t){return`SubClient:${t}`}addSchemaTypeSymbolName(t,r){let n=this.schemaTypeSymbolNameId(t);return this.namespace.registerSymbol(n,r)}getSchemaTypeSymbolNameOrThrow(t){let r=this.schemaTypeSymbolNameId(t);return this.namespace.getSymbolNameByIdOrThrow(r)}schemaTypeSymbolNameId(t){return`SchemaType:${t}`}};St();var lLn=class{namespace;constructor(){this.namespace=new GC}asIsNameId(t){return`AsIs:${t}`}wireTestSuiteNameId(t){return`WireTestSuite:${t}`}addAsIsSymbol(t){let r=this.asIsNameId(t);this.namespace.registerSymbol(r,[t])}registerWireTestSuiteSymbol(t){return this.namespace.registerSymbol(this.wireTestSuiteNameId(t),[`${t}WireTests`,`${t}WireTestSuite`])}getWireTestSuiteNameOrThrow(t){return this.namespace.getSymbolNameByIdOrThrow(this.wireTestSuiteNameId(t))}};var pLn=class e{static create(){return new e}symbolRegistry;sourceModuleNamespace;testModuleNamespace;requestsNamespace;sourceStaticSymbolsByName;testStaticSymbolsByName;requestTypeSymbols;subClientSymbols;nestedLiteralEnumSymbolsByParentSymbolId;undiscriminatedUnionVariantsByParentSymbolId;constructor(){this.symbolRegistry=Br.SymbolRegistry.create(),this.sourceModuleNamespace=new cLn,this.testModuleNamespace=new lLn,this.requestsNamespace=new uLn,this.sourceStaticSymbolsByName=new Map,this.testStaticSymbolsByName=new Map,this.requestTypeSymbols=[],this.subClientSymbols=[],this.nestedLiteralEnumSymbolsByParentSymbolId=new Map,this.undiscriminatedUnionVariantsByParentSymbolId=new Map}getAsIsSymbolOrThrow(t){let r=this.sourceStaticSymbolsByName.get(t);return Yy(r,`As is symbol not found for name "${t}"`),r}getSourceTemplateSymbolOrThrow(t){switch(t){case"ClientError":return this.getErrorEnumSymbolOrThrow();case"HTTPClient":{let r=this.symbolRegistry.inferSymbolIdForSourceModuleType(t);return Br.Symbol.create(r,t,{type:"class"})}default:Be(t)}}registerSourceModuleSymbol({configModuleName:t,apiNamePascalCase:r,asIsSymbols:n}){let i=[`${r}`,`${r}Api`,`${r}Module`];typeof t=="string"&&i.unshift(t);let s=new GC({reservedSymbolNames:["Swift","Foundation"]}).registerSymbol("Module",i),a=this.symbolRegistry.registerSourceModule(s);return n.forEach(u=>{let c=u.name;this.registerSourceStaticSymbol(c,u.shape)}),a}getRegisteredSourceModuleSymbolOrThrow(){return this.symbolRegistry.getRegisteredSourceModuleSymbolOrThrow()}registerSourceStaticSymbol(t,r){this.symbolRegistry.registerSourceModuleType(t,r),this.sourceModuleNamespace.addStaticSymbolName(t);let n=this.symbolRegistry.inferSymbolIdForSourceModuleType(t),i=Br.Symbol.create(n,t,r);this.sourceStaticSymbolsByName.set(t,i)}registerTestModuleSymbol({sourceModuleName:t,asIsSymbols:r}){let n=[`${t}Tests`,`${t}Test`,`${t}TestsModule`],i=(()=>{let s=new GC;return s.registerSymbol("Swift",["Swift"]),s.registerSymbol("Foundation",["Foundation"]),s.registerSymbol(t,[t]),s.registerSymbol(`${t}Tests`,n)})(),o=this.symbolRegistry.registerTestModule(i);return r.forEach(s=>{let a=s.name;this.symbolRegistry.registerTestModuleType(a,s.shape),this.testModuleNamespace.addAsIsSymbol(a);let u=this.symbolRegistry.inferSymbolIdForTestModuleType(a),c=Br.Symbol.create(u,a,s.shape);this.testStaticSymbolsByName.set(a,c)}),o}getRegisteredTestModuleSymbolOrThrow(){return this.symbolRegistry.getRegisteredTestModuleSymbolOrThrow()}registerRootClientSymbol({configClientClassName:t,registeredSourceModuleName:r}){let n=[`${r}Client`,`${r}ApiClient`,`${r}Service`];typeof t=="string"&&n.unshift(t);let i=this.sourceModuleNamespace.addRootClientSymbolName(n);return this.symbolRegistry.registerSourceModuleType(i,{type:"class"})}getRootClientSymbolOrThrow(){let t=this.sourceModuleNamespace.getRootClientSymbolNameOrThrow(),r=this.symbolRegistry.inferSymbolIdForSourceModuleType(t);return this.symbolRegistry.getSymbolByIdOrThrow(r)}registerEnvironmentSymbol({configEnvironmentEnumName:t,registeredSourceModuleName:r}){let n=[`${r}Environment`,`${r}Environ`,`${r}Env`];typeof t=="string"&&n.unshift(t);let i=this.sourceModuleNamespace.addEnvironmentSymbolName(n);return this.symbolRegistry.registerSourceModuleType(i,{type:"enum-with-raw-values"})}getEnvironmentSymbolOrThrow(){let t=this.sourceModuleNamespace.getEnvironmentSymbolNameOrThrow(),r=this.symbolRegistry.inferSymbolIdForSourceModuleType(t);return this.symbolRegistry.getSymbolByIdOrThrow(r)}registerErrorEnumSymbol(t){let r=[`${t}Error`,`${t}ClientError`],n=this.sourceModuleNamespace.addErrorEnumSymbolName(r);return this.symbolRegistry.registerSourceModuleType(n,{type:"enum-with-associated-values"})}getErrorEnumSymbolOrThrow(){let t=this.sourceModuleNamespace.getErrorEnumSymbolNameOrThrow(),r=this.symbolRegistry.inferSymbolIdForSourceModuleType(t);return this.symbolRegistry.getSymbolByIdOrThrow(r)}registerRequestsContainerSymbol(){let t=this.sourceModuleNamespace.addRequestsContainerSymbolName(["Requests","RequestTypes","InlineRequests"]);return this.symbolRegistry.registerSourceModuleType(t,{type:"enum-container"})}getRequestsContainerSymbolOrThrow(){let t=this.sourceModuleNamespace.getRequestsContainerSymbolNameOrThrow(),r=this.symbolRegistry.inferSymbolIdForSourceModuleType(t);return this.symbolRegistry.getSymbolByIdOrThrow(r)}registerRequestTypeSymbol({endpointId:t,requestNamePascalCase:r}){let n=[`${r}Type`];r.endsWith("Request")?n.push(`${r}Body`,`${r}BodyType`):n.push(`${r}Request`,`${r}RequestBody`,`${r}RequestBodyType`);let i=this.getRequestsContainerSymbolOrThrow(),o=this.requestsNamespace.addRequestTypeSymbol(t,r,[r,...n]),s=this.symbolRegistry.registerNestedType({parentSymbol:i,symbolName:o,shape:{type:"struct"}});return this.requestTypeSymbols.push(s),s}getRequestTypeSymbolOrThrow(t,r){let n=this.requestsNamespace.getRequestTypeNameOrThrow(t,r),i=this.getRequestsContainerSymbolOrThrow(),o=this.symbolRegistry.inferSymbolIdForNestedType(i.id,n);return this.symbolRegistry.getSymbolByIdOrThrow(o)}getAllRequestTypeSymbols(){return[...this.requestTypeSymbols]}registerSubClientSymbol({subpackageId:t,fernFilepathPartNamesPascalCase:r,subpackageNamePascalCase:n}){let i=r.toReversed();i.shift();let o=i.map((u,c)=>i.slice(0,c+1).reverse().join("")+n+"Client"),s=this.sourceModuleNamespace.addSubClientSymbolName(t,[`${n}Client`,...o]),a=this.symbolRegistry.registerSourceModuleType(s,{type:"class"});return this.subClientSymbols.push(a),a}getSubClientSymbolOrThrow(t){let r=this.sourceModuleNamespace.getSubClientSymbolNameOrThrow(t),n=this.symbolRegistry.inferSymbolIdForSourceModuleType(r);return this.symbolRegistry.getSymbolByIdOrThrow(n)}getAllSubClientSymbols(){return[...this.subClientSymbols]}registerSchemaTypeSymbol(t,r,n){let i=this.sourceModuleNamespace.addSchemaTypeSymbolName(t,[r,`${r}Type`,`${r}Model`,`${r}Schema`]);return this.symbolRegistry.registerSourceModuleType(i,n)}getSchemaTypeSymbolOrThrow(t){let r=this.sourceModuleNamespace.getSchemaTypeSymbolNameOrThrow(t),n=this.symbolRegistry.inferSymbolIdForSourceModuleType(r);return this.symbolRegistry.getSymbolByIdOrThrow(n)}registerNestedLiteralEnumSymbol({parentSymbol:t,literalValue:r}){let n=typeof t=="string"?t:t.id,i=this.nestedLiteralEnumSymbolsByParentSymbolId.get(n)??new Map,o=i.get(r);if(o)return o;let s=Array.from(i.values()),a=(()=>{let c=new GC({reservedSymbolNames:["CodingKeys"]});s.forEach(p=>{c.registerSymbol(p.id,[p.name])});let l=nLe.generateName(r);return c.registerSymbol(r,[l,`${l}Literal`,`${l}Enum`,`${l}StringEnum`])})(),u=this.symbolRegistry.registerNestedType({parentSymbol:t,symbolName:a,shape:{type:"enum-with-raw-values"}});return i.set(r,u),this.nestedLiteralEnumSymbolsByParentSymbolId.set(n,i),u}getNestedLiteralEnumSymbolOrThrow(t,r){let n=typeof t=="string"?t:t.id,o=(this.nestedLiteralEnumSymbolsByParentSymbolId.get(n)??new Map).get(r);return Yy(o,`Nested literal enum symbol not found for literal value "${r}" in parent symbol "${n}"`),o}getAllNestedLiteralEnumSymbolsOrThrow(t){let r=typeof t=="string"?t:t.id,n=this.nestedLiteralEnumSymbolsByParentSymbolId.get(r)??new Map;return Array.from(n.entries()).sort(([,i],[,o])=>i.name.localeCompare(o.name)).map(([i,o])=>({symbol:o,literalValue:i,caseLabel:nLe.generateEnumCaseLabel(i)}))}registerUndiscriminatedUnionVariants({parentSymbol:t,variants:r}){let n=typeof t=="string"?t:t.id,i=uze(r,(o,s)=>o.caseName===s.caseName);return i.sort((o,s)=>o.caseName.localeCompare(s.caseName)),this.undiscriminatedUnionVariantsByParentSymbolId.set(n,i),i}getAllUndiscriminatedUnionVariantsOrThrow(t){let r=typeof t=="string"?t:t.id;return this.undiscriminatedUnionVariantsByParentSymbolId.get(r)??[]}registerWireTestSuiteSymbol(t){let r=this.testModuleNamespace.registerWireTestSuiteSymbol(t);return this.symbolRegistry.registerTestModuleType(r,{type:"struct"})}getWireTestSuiteSymbolOrThrow(t){let r=this.testModuleNamespace.getWireTestSuiteNameOrThrow(t),n=this.symbolRegistry.inferSymbolIdForTestModuleType(r);return this.symbolRegistry.getSymbolByIdOrThrow(n)}referenceFromSourceModuleScope(t){let r=this.getRegisteredSourceModuleSymbolOrThrow();return this.symbolRegistry.reference({fromSymbol:r,toSymbol:t})}reference({fromSymbol:t,toSymbol:r}){return this.symbolRegistry.reference({fromSymbol:t,toSymbol:r})}resolveReference({fromSymbol:t,reference:r}){return this.symbolRegistry.resolveReference({fromSymbol:t,reference:r})}};var Br={};Z(Br,{AccessLevel:()=>wXu,Class:()=>ydt,CodeBlock:()=>dS,Comment:()=>bdt,ComputedProperty:()=>Idt,DeclarationType:()=>KLt,DocComment:()=>wdt,EnumWithAssociatedValues:()=>Cdt,EnumWithRawValues:()=>xdt,Expression:()=>kne,Extension:()=>_dt,FunctionArgument:()=>Sdt,FunctionParameter:()=>Bdt,Initializer:()=>Odt,LineBreak:()=>fLn,Method:()=>Tdt,Pattern:()=>dLn,Property:()=>Pdt,Protocol:()=>xXu,SourceAsIsFileSpecs:()=>dFm,SourceTemplateFileSpecs:()=>mFm,Statement:()=>vdt,Struct:()=>Ddt,Symbol:()=>_C,SymbolRegistry:()=>Ymo,TypeReference:()=>mLn,class_:()=>hFm,codeBlock:()=>gFm,comment:()=>AFm,computedProperty:()=>yFm,docComment:()=>bFm,enumWithAssociatedValues:()=>EFm,enumWithRawValues:()=>vFm,extension:()=>IFm,functionArgument:()=>wFm,functionParameter:()=>CFm,initializer:()=>xFm,method:()=>_Fm,property:()=>SFm,struct:()=>BFm});var wXu={Open:"open",Public:"public",Package:"package",Internal:"internal",Fileprivate:"fileprivate",Private:"private"};var HLt=class extends wC{toString(){return this.buffer}};var ep=class extends O0{toString(){let t=new HLt;return this.write(t),t.toString()}toStringWithIndentation(t){let r=new HLt;for(let n=1;n<t;n++)r.indent();this.write(r);for(let n=1;n<t;n++)r.dedent();return r.toString()}};var ydt=class extends ep{name;final;accessLevel;conformances;properties;initializers;methods;docs;constructor({accessLevel:t,name:r,final:n,conformances:i,properties:o,initializers:s,methods:a,docs:u}){super(),this.name=r,this.final=n,this.accessLevel=t,this.conformances=i??[],this.properties=o,this.initializers=s??[],this.methods=a??[],this.docs=u}write(t){this.docs!=null&&this.docs.write(t),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),this.final&&t.write("final "),t.write(`class ${this.name}`),this.conformances.forEach((r,n)=>{n===0?t.write(": "):n>0&&t.write(", "),t.write(r)}),t.write(" {"),t.newLine(),t.indent(),this.properties.forEach(r=>{r.write(t),t.newLine()}),this.initializers.length>0&&(t.newLine(),this.initializers.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()})),this.methods.length>0&&(t.newLine(),this.methods.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()})),t.dedent(),t.write("}")}};St();var dS=class e extends ep{args;constructor(t){super(),this.args=t}write(t){let r=new Ly(this.args);t.write("{"),t.newLine(),t.indent(),r.write(t),t.dedent(),t.write("}")}static empty(){return new e(ft)}static withStatements(t){return new e(r=>{t.forEach(n=>{n.write(r)})})}};var bdt=class extends ep{content;constructor({content:t}){super(),this.content=t}write(t){this.content.split(`
2572
+ `;return vmo(i)}async generateSnippetAst({endpoint:t,request:r,options:n}){throw new Error("Unsupported")}buildCodeComponents({endpoint:t,snippet:r}){let n=this.getUseStatements({endpoint:t}),i=sr.CodeBlock.fromStatements([sr.Statement.let({name:"config",value:this.getClientConfigStruct({endpoint:t,snippet:r})}),sr.Statement.let({name:iXu,value:sr.Expression.methodCall({target:sr.Expression.raw(`${this.getClientName()}::new(config)`),method:"expect",args:[sr.Expression.stringLiteral("Failed to build client")]})}),this.callMethod({endpoint:t,snippet:r})]),o=sr.standaloneFunction({name:"main",attributes:[sr.attribute({name:"tokio::main"})],parameters:[],isAsync:!0,body:i}),s=[];return n.forEach(a=>{s.push(a.toString())}),s.push(""),s.push(o.toString()),s}getUseStatements({endpoint:t}){let r=[];return r.push(new sr.UseStatement({path:`${this.context.getCrateName()}::prelude`,items:["*"]})),r}collectEndpointTypeImports(t,r){let n=t.request;if(n.pathParameters)for(let i of n.pathParameters)this.collectTypeReferenceImports(i.typeReference,r);if(n.type==="inlined"){if(n.queryParameters)for(let i of n.queryParameters)this.collectTypeReferenceImports(i.typeReference,r);if(n.headers)for(let i of n.headers)this.collectTypeReferenceImports(i.typeReference,r);n.body&&this.collectRequestBodyTypeImports(n.body,r)}else n.type==="body"&&n.body?.type==="typeReference"&&this.collectTypeReferenceImports(n.body.value,r)}collectRequestBodyTypeImports(t,r){switch(t.type){case"properties":for(let n of t.value)this.collectTypeReferenceImports(n.typeReference,r);break;case"referenced":t.bodyType.type==="typeReference"&&this.collectTypeReferenceImports(t.bodyType.value,r);break;case"fileUpload":for(let n of t.properties)n.type==="bodyProperty"&&this.collectTypeReferenceImports(n.typeReference,r);break}}collectTypesFromValue(t,r,n,i,o){if(typeof t=="object"&&t!=null&&!Array.isArray(t)){let s=t;Object.keys(s).length>0&&n.add("HashMap"),Object.keys(s).forEach(a=>{if(a==="type"||a==="_type"||a.endsWith("_type")){let u=s[a];typeof u=="string"&&this.findAndAddUnionTypes(u,r)}}),Object.values(s).forEach(a=>{this.collectTypesFromValue(a,r,n,i,o)})}else Array.isArray(t)?(t.length>0&&n.add("HashSet"),t.forEach(s=>this.collectTypesFromValue(s,r,n,i,o))):typeof t=="string"&&(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&o.add("Uuid"),/^\d{4}-\d{2}-\d{2}$/.test(t)&&i.add("NaiveDate"),/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(t)&&(i.add("DateTime"),i.add("Utc")))}findAndAddUnionTypes(t,r){Object.values(this.context.ir.types).forEach(n=>{if(n.type==="discriminatedUnion"){let i=n;if(Object.keys(i.types).includes(t)){r.add(this.context.getStructName(n.declaration.name));let o=i.types[t];if(o&&o.type==="samePropertiesAsObject"){let s=this.context.ir.types[o.typeId];s&&(r.add(this.context.getStructName(s.declaration.name)),this.collectNestedTypeImports(s,r))}}}})}collectNestedTypeImports(t,r,n=new Set){let i=t.declaration.name.pascalCase.safeName;if(!n.has(i))switch(n.add(i),t.type){case"object":r.add(this.context.getStructName(t.declaration.name));for(let o of t.properties)this.collectTypeReferenceImports(o.typeReference,r,n);break;case"alias":r.add(this.context.getStructName(t.declaration.name)),this.collectTypeReferenceImports(t.typeReference,r,n);break;case"enum":r.add(this.context.getEnumName(t.declaration.name));break;case"discriminatedUnion":case"undiscriminatedUnion":r.add(this.context.getStructName(t.declaration.name)),t.type==="discriminatedUnion"?Object.values(t.types).forEach(o=>{if(o.type==="singleProperty")this.collectTypeReferenceImports(o.typeReference,r,n);else if(o.type==="samePropertiesAsObject"){let s=this.context.ir.types[o.typeId];s&&this.collectNestedTypeImports(s,r,n)}}):t.type==="undiscriminatedUnion"&&t.types.forEach(o=>{this.collectTypeReferenceImports(o,r,n)});break}}collectTypeReferenceImports(t,r,n=new Set){switch(t.type){case"named":{let i=t.value,o=this.context.ir.types[i];o&&this.collectNestedTypeImports(o,r,n);break}case"optional":case"nullable":{let i=t.value;i&&this.collectTypeReferenceImports(i,r,n);break}case"list":{let i=t.value;i&&this.collectTypeReferenceImports(i,r,n);break}case"set":{let i=t.value;i&&this.collectTypeReferenceImports(i,r,n);break}case"map":{let i=t;i.key&&this.collectTypeReferenceImports(i.key,r,n),i.value&&this.collectTypeReferenceImports(i.value,r,n);break}case"primitive":case"literal":case"unknown":break}}getClientConfigStruct({endpoint:t,snippet:r}){let n=[],i=this.getBaseUrlValue({baseUrl:r.baseURL,environment:r.environment});if(i!=null&&n.push({name:"base_url",value:sr.Expression.methodCall({target:sr.Expression.stringLiteral(i),method:"to_string",args:[]})}),t.auth!=null&&r.auth!=null)switch(t.auth.type){case"bearer":r.auth.type==="bearer"&&n.push({name:"token",value:sr.Expression.functionCall("Some",[sr.Expression.methodCall({target:sr.Expression.stringLiteral(r.auth.token),method:"to_string",args:[]})])});break;case"basic":r.auth.type==="basic"&&(n.push({name:"username",value:sr.Expression.functionCall("Some",[sr.Expression.methodCall({target:sr.Expression.stringLiteral(r.auth.username),method:"to_string",args:[]})])}),n.push({name:"password",value:sr.Expression.functionCall("Some",[sr.Expression.methodCall({target:sr.Expression.stringLiteral(r.auth.password),method:"to_string",args:[]})])}));break;case"header":r.auth.type==="header"&&n.push({name:"api_key",value:sr.Expression.functionCall("Some",[sr.Expression.methodCall({target:sr.Expression.stringLiteral(String(r.auth.value)),method:"to_string",args:[]})])});break}return sr.Expression.structConstruction("ClientConfig",n.map(o=>({name:o.name,value:o.value})),!0)}getClientName(){return this.context.getClientStructName()}callMethod({endpoint:t,snippet:r}){return sr.Statement.expression(sr.Expression.methodCall({target:sr.Expression.reference(iXu),method:this.getMethodName({endpoint:t}),args:this.getMethodArgs({endpoint:t,snippet:r}),isAsync:!0}))}getBaseUrlValue({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null)return t;if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.resolveEnvironmentName("default");if(n==null){this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return n.snakeCase.safeName}this.context.isMultiEnvironmentValues(r)&&this.context.errors.add({severity:Ir.Warning,message:"Multi-environment values are not supported yet; use the baseUrl option instead"})}}getMethodArgs({endpoint:t,snippet:r}){let n=[];switch(t.request.type){case"inlined":n=this.getMethodArgsForInlinedRequest({endpoint:t,request:t.request,snippet:r});break;case"body":n=this.getMethodArgsForBodyRequest({request:t.request,snippet:r});break;default:Be(t.request)}return n}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[],i=this.buildRequestComponents({pathParameters:[...this.context.ir.pathParameters??[],...t.pathParameters??[]],snippet:r,body:t.body});return n.push(...i.pathArgs),i.bodyArg!=null&&n.push(sr.Expression.referenceOf(i.bodyArg)),n.push(sr.Expression.raw("None")),n}getMethodArgsForInlinedRequest({endpoint:t,request:r,snippet:n}){let i=[];this.context.errors.scope(Lo.PathParameters),this.context.scopeError("pathParameters");try{let p=[...this.context.ir.pathParameters??[],...r.pathParameters??[]];p.length>0&&i.push(...this.getPathParameterArgs({namedParameters:p,snippet:n}))}finally{this.context.unscopeError(),this.context.errors.unscope()}let o=(r.queryParameters??[]).length>0,s=r.body!=null,a=r.body,u=a!=null&&!o&&a.type==="referenced";if(o&&a!=null&&a.type==="referenced"&&a.bodyType.type==="bytes")i.push(...this.getBytesEndpointArgs({request:r,snippet:n}));else if(u&&a.type==="referenced"){let p=this.getReferencedRequestBodyPropertyExpression({body:a.bodyType,value:n.requestBody});i.push(sr.Expression.referenceOf(p))}else(o||s)&&i.push(sr.Expression.referenceOf(this.getInlinedRequestArg({endpoint:t,request:r,snippet:n})));return(r.headers??[]).length>0&&Object.keys(n.headers??{}).length>0?i.push(sr.Expression.functionCall("Some",[this.getRequestOptionsWithHeaders({request:r,snippet:n})])):i.push(sr.Expression.raw("None")),i}getBytesEndpointArgs({request:t,snippet:r}){let n=[],i=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}),o=new Map;for(let a of i){let u=this.context.getPropertyName(a.name.name);o.set(u,this.context.dynamicTypeLiteralMapper.convert(a))}let s=t.queryParameters??[];for(let a of s){let u=this.context.getPropertyName(a.name.name),c=o.get(u);c!=null?n.push(sr.Expression.referenceOf(c)):n.push(sr.Expression.referenceOf(sr.Expression.raw("None")))}return r.requestBody!=null&&typeof r.requestBody=="string"&&r.requestBody!==""?n.push(sr.Expression.referenceOf(sr.Expression.raw(`"${r.requestBody}".as_bytes().to_vec()`))):n.push(sr.Expression.referenceOf(sr.Expression.raw("vec![]"))),n}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r});default:Be(t)}}getBytesBodyRequestArg({value:t}){return typeof t!="string"?(this.context.errors.add({severity:Ir.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),sr.Expression.raw('todo!("Invalid bytes value")')):sr.Expression.stringLiteral(t)}getInlinedRequestArg({endpoint:t,request:r,snippet:n}){let i=[],o=new Set;this.context.errors.scope(Lo.QueryParameters),this.context.scopeError("queryParameters");try{let u=this.context.associateQueryParametersByWireValue({parameters:r.queryParameters??[],values:n.queryParameters??{}});for(let c of u){this.context.scopeError(c.name.wireValue);try{let l=this.context.getPropertyName(c.name.name);i.push({name:l,value:this.context.dynamicTypeLiteralMapper.convert(c)}),o.add(l)}finally{this.context.unscopeError()}}}finally{this.context.unscopeError(),this.context.errors.unscope()}if(this.context.errors.scope(Lo.RequestBody),r.body!=null){let u=this.getInlinedRequestBodyStructFields({body:r.body,value:n.requestBody});for(let c of u)i.push(c),o.add(c.name)}this.context.errors.unscope();let s=this.getCorrectRequestStructName(t,r),a=!1;return this.addMissingFields({request:r,structFields:i,providedFieldNames:o}),this.createStructExpression(s,i,a)}addMissingFields({request:t,structFields:r,providedFieldNames:n}){let i=t.queryParameters??[];for(let o of i){let s=this.context.getPropertyName(o.name.name);n.has(s)||(this.context.isOptionalType(o.typeReference)?r.push({name:s,value:sr.Expression.raw("None")}):r.push({name:s,value:this.generateDefaultValueForType(o.typeReference)}))}if(t.body!=null&&t.body.type==="properties")for(let o of t.body.value){let s=this.context.getPropertyName(o.name.name);n.has(s)||(this.context.isOptionalType(o.typeReference)?r.push({name:s,value:sr.Expression.raw("None")}):r.push({name:s,value:this.generateDefaultValueForType(o.typeReference)}))}}generateDefaultValueForType(t){switch(t.type){case"primitive":switch(t.value){case"STRING":return sr.Expression.stringLiteral("string");case"INTEGER":case"LONG":case"UINT":case"UINT_64":return sr.Expression.raw("0");case"FLOAT":case"DOUBLE":return sr.Expression.raw("0.0");case"BOOLEAN":return sr.Expression.raw("false");default:return sr.Expression.stringLiteral("default")}case"list":return sr.Expression.raw("vec![]");case"map":return sr.Expression.raw("std::collections::HashMap::new()");case"set":return sr.Expression.raw("std::collections::HashSet::new()");case"named":{let r=t.value,n=this.context.ir.types[r],i=this.context.getTypeNameById(r);if(!n)return sr.Expression.raw(`${i}("value".to_string())`);switch(n.type){case"alias":let o=this.generateDefaultValueForType(n.typeReference);return sr.Expression.raw(`${i}(${o.toString()})`);case"enum":if(n.values.length>0){let s=n.values[0];if(s){let a=s.name.pascalCase.unsafeName,u=this.context.escapeRustReservedType(a);return sr.Expression.raw(`${i}::${u}`)}}return sr.Expression.raw(`${i}::default()`);case"object":case"discriminatedUnion":case"undiscriminatedUnion":return sr.Expression.raw(`${i}::default()`);default:return sr.Expression.raw(`${i}("value".to_string())`)}}default:return sr.Expression.raw("Default::default()")}}getInlinedRequestBodyStructFields({body:t,value:r}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyStructFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyStructField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyStructFields({body:t,value:r});default:Be(t)}}getInlinedRequestBodyPropertyStructFields({parameters:t,value:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert(o)});return n}getReferencedRequestBodyPropertyStructField({body:t,value:r}){return{name:this.context.getPropertyName(t.bodyKey),value:this.getReferencedRequestBodyPropertyExpression({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyExpression({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r});default:Be(t)}}getFileUploadRequestBodyStructFields({body:t,value:r}){let n=[],i=this.context.filePropertyMapper.getFilePropertyInfo({body:t,value:r});return n.push(...i.fileFields.map(o=>({name:o.name,value:o.value}))),n.push(...i.bodyPropertyFields.map(o=>({name:o.name,value:o.value}))),n}getPathParameterArgs({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:r.pathParameters??{}});for(let o of i){let s=this.context.dynamicTypeLiteralMapper.convert(o);this.isCopyPrimitive(o.typeReference)?n.push(s):n.push(sr.Expression.referenceOf(s))}return n}isCopyPrimitive(t){if(t.type!=="primitive")return!1;switch(t.value){case"INTEGER":case"LONG":case"UINT":case"UINT_64":case"FLOAT":case"DOUBLE":case"BOOLEAN":return!0;default:return!1}}getRequestOptionsWithHeaders({request:t,snippet:r}){let n=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}),i=sr.Expression.functionCall("RequestOptions::new",[]);for(let o of n){this.context.scopeError(o.name.wireValue);try{let s=this.getHeaderValueAsString(o.value);i=sr.Expression.methodCall({target:i,method:"additional_header",args:[sr.Expression.stringLiteral(o.name.wireValue),s]})}finally{this.context.unscopeError()}}return i}getHeaderValueAsString(t){if(t==null)return sr.Expression.stringLiteral("");let r=String(t);return sr.Expression.stringLiteral(r)}buildRequestComponents({pathParameters:t,snippet:r,body:n}){let i=[],o=null;return this.context.errors.scope(Lo.PathParameters),t.length>0&&i.push(...this.getPathParameterArgs({namedParameters:t,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),n!=null&&(o=this.getBodyRequestArg({body:n,value:r.requestBody})),this.context.errors.unscope(),{pathArgs:i,bodyArg:o}}getMethodName({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getMethodName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}createStructExpression(t,r,n=!1){return this.shouldUseStructConstruction(r)?sr.Expression.structConstruction(t,r.map(i=>({name:i.name,value:i.value})),n):sr.Expression.structLiteral(t,r)}shouldUseStructConstruction(t){return!0}getCorrectRequestStructName(t,r){let n=(r.queryParameters??[]).length>0,i=r.body!=null,o=t.declaration.name.pascalCase.safeName;if(n&&!i){let s=this.context.getQueryRequestNameByEndpoint(t.declaration);return s||`${o}QueryRequest`}if(i&&r.body!=null){if(r.body.type==="referenced"&&r.body.bodyType.type==="typeReference"){let s=r.body.bodyType.value;if(s.type==="named"){let a=s.value;if(this.context.getTypeNameById(a)&&n)return`${o}Request`}}return r.body.type==="properties"?this.context.getStructNameByDeclaration(r.declaration):`${o}Request`}return this.context.getStructNameByDeclaration(r.declaration)}};var WLt=class extends Wv{constructor({ir:t,config:r,options:n={}}){super(new qLt({ir:t,config:r,options:n}))}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new GLt({context:t})}};var nLn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new WLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");let n=await this.initializeProject(t);for(let[i,{endpointId:o,request:s}]of r.entries())try{let a=pS(s);if(a==null)continue;let u=await this.dynamicSnippetsGenerator.generate(a,{config:{},style:CC.Full,endpointId:o}),c=this.getTestFilePath({absolutePathToOutputDir:n,idx:i});await(0,$Lt.mkdir)(oXu.default.dirname(c),{recursive:!0}),await(0,$Lt.writeFile)(c,u.snippet)}catch(a){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(s.endpoint)}: ${a}`)}this.context.logger.debug("Done generating dynamic snippet tests")}async initializeProject(t){let r=Ge(t,Se.of("dynamic-snippets"));return await(0,$Lt.mkdir)(r,{recursive:!0}),r}getTestFilePath({absolutePathToOutputDir:t,idx:r}){return Ge(t,Se.of(`example${r}.rs`))}};var XLt=require("fs/promises"),TXu=Ae(require("path"),1);qt();St();var oLn={};Z(oLn,{sanitizeForIdentifier:()=>Kmo,sanitizeToCamelCase:()=>oFm,sanitizeToPascalCase:()=>iFm});Bi();var IXu=Ae(vXu(),1);Bi();function iLn(e){return gc(qn(e))}function iFm(e){let t=Kmo(e);return iLn(t)}function oFm(e){let t=Kmo(e);return qn(t)}function Kmo(e){if(e==="")return"empty";let t=e;if(/^\d/.test(t)){let n=sFm(t);t=n.numberAsWords+gc(n.rest)}return/^[a-zA-Z][a-zA-Z0-9]*$/.test(t)||(t=t.replace(/^[^a-zA-Z0-9]+/,""),t=qn(t)),/^\d/.test(t)&&(t="value"+t),t===""?"value":t}function sFm(e){let t=e.match(/^(\d+)/);if(!t||!t[1])return{numberAsWords:"",rest:e};let r=t[1],n=e.slice(r.length);try{return{numberAsWords:(0,IXu.toWords)(parseInt(r,10)),rest:n}}catch{let i={0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"};return{numberAsWords:r.split("").map(s=>i[s]||s).join(""),rest:n}}}var nLe={};Z(nLe,{generateEnumCaseLabel:()=>uFm,generateName:()=>aFm,sanitizeLiteralValue:()=>Jmo});Bi();function aFm(e){let t=Jmo(e);return iLn(t)}function uFm(e){let t=Jmo(e);return qn(t)}function Jmo(e){if(e==="")return"empty";let t=e;return/^[a-zA-Z][a-zA-Z0-9]*$/.test(e)||(t=t.replace(/^[^a-zA-Z0-9]+/,""),t=qn(t)),/^\d/.test(t)||t===""?"value":t}var sLn=class{nameRegistry;fromSymbol;constructor(t,r){this.nameRegistry=t,this.fromSymbol=r}referenceSwiftType(t){let r=this.nameRegistry.reference({fromSymbol:this.fromSymbol,toSymbol:Br.Symbol.swiftType(t)});return Br.TypeReference.symbol(r)}referenceFoundationType(t){let r=this.nameRegistry.reference({fromSymbol:this.fromSymbol,toSymbol:Br.Symbol.foundationType(t)});return Br.TypeReference.symbol(r)}referenceAsIsType(t){let r=this.nameRegistry.getAsIsSymbolOrThrow(t),n=this.nameRegistry.reference({fromSymbol:this.fromSymbol,toSymbol:r});return Br.TypeReference.symbol(n)}referenceSourceTemplateType(t){let r=this.nameRegistry.getSourceTemplateSymbolOrThrow(t),n=this.nameRegistry.reference({fromSymbol:this.fromSymbol,toSymbol:r});return Br.TypeReference.symbol(n)}referenceType(t){let r=this.nameRegistry.reference({fromSymbol:this.fromSymbol,toSymbol:t});return Br.TypeReference.symbol(r)}resolveToSymbolIfSymbolType(t){let r=t.getReferenceIfSymbolType();return r===null?null:this.nameRegistry.resolveReference({fromSymbol:this.fromSymbol,reference:r})}resolvesToTheAsIsType(t,r){let n=this.resolveToSymbolIfSymbolType(t),i=this.nameRegistry.getAsIsSymbolOrThrow(r);return n?.id===i.id}resolvesToASwiftType(t){return this.resolveToSymbolIfSymbolType(t)?.isSwiftSymbol??!1}resolvesToTheSwiftType(t,r){return this.resolveToSymbolIfSymbolType(t)?.id===Br.Symbol.swiftType(r).id}resolvesToAFoundationType(t){return this.resolveToSymbolIfSymbolType(t)?.isFoundationSymbol??!1}resolvesToTheFoundationType(t,r){return this.resolveToSymbolIfSymbolType(t)?.id===Br.Symbol.foundationType(r).id}resolvesToACustomType(t){return this.resolveToSymbolIfSymbolType(t)?.isCustomSymbol??!1}resolvesToAnEnumWithRawValues(t){return this.resolveToSymbolIfSymbolType(t)?.shape.type==="enum-with-raw-values"}};var aLn={};Z(aLn,{inferCaseNameForTypeReference:()=>Nne});St();Bi();var cFm={String:"string",Bool:"bool",Int:"int",Int64:"int64",UInt:"uint",UInt64:"uint64",Float:"float",Double:"double",Void:"void",Encoder:"encoder",Decoder:"decoder",Any:"any"},lFm={Data:"data",Date:"date",UUID:"uuid"};function Nne(e,t,r){if(t.variant.type==="symbol"){let n=t.variant.symbol,i=r.resolveReference({fromSymbol:e,reference:n});DP(i,`Cannot find symbol ${n} for type reference ${t.variant.type}`);let o=i.name;return Br.Symbol.isSwiftSymbol(i.id)&&Br.Symbol.isSwiftSymbolName(o)?cFm[o]:Br.Symbol.isFoundationSymbol(i.id)&&Br.Symbol.isFoundationSymbolName(o)?lFm[o]:qn(o)}else if(t.variant.type==="generic"){let n=t.variant.arguments.map(i=>Nne(e,i,r));return`${Nne(e,t.variant.reference,r)}Of${gc(n.join("And"))}`}else{if(t.variant.type==="array")return`${Nne(e,t.variant.elementType,r)}Array`;if(t.variant.type==="dictionary"){let n=Nne(e,t.variant.keyType,r),i=Nne(e,t.variant.valueType,r);return`${n}To${gc(i)}Dictionary`}else if(t.variant.type==="optional"){let n=Nne(e,t.variant.valueType,r);return`optional${gc(n)}`}else if(t.variant.type==="nullable"){let n=Nne(e,t.variant.valueType,r);return`nullable${gc(n)}`}else if(t.variant.type==="tuple"){let n=t.variant.elements.map(i=>Nne(e,i,r));return`tuple${gc(n.join("And"))}`}else{if(t.variant.type==="member-access")return`${Nne(e,t.variant.target,r)}${gc(t.variant.memberName)}`;Be(t.variant)}}}St();Bi();St();var uLn=class{namespace;constructor(){this.namespace=new GC}getRequestTypeNameOrThrow(t,r){let n=this.requestTypeNameId(t,r);return this.namespace.getSymbolNameByIdOrThrow(n)}addRequestTypeSymbol(t,r,n){let i=this.requestTypeNameId(t,r);return this.namespace.registerSymbol(i,n)}requestTypeNameId(t,r){return`${t}_${r}`}};St();var cLn=class{namespace;constructor(){this.namespace=new GC}addStaticSymbolName(t){let r=this.staticSymbolNameId(t);return this.namespace.registerSymbol(r,[t])}staticSymbolNameId(t){return`Static:${t}`}addRootClientSymbolName(t){let r=this.rootClientSymbolNameId();return this.namespace.registerSymbol(r,t)}getRootClientSymbolNameOrThrow(){return this.namespace.getSymbolNameByIdOrThrow(this.rootClientSymbolNameId())}rootClientSymbolNameId(){return"RootClientClass"}addEnvironmentSymbolName(t){let r=this.environmentSymbolNameId();return this.namespace.registerSymbol(r,t)}getEnvironmentSymbolNameOrThrow(){return this.namespace.getSymbolNameByIdOrThrow(this.environmentSymbolNameId())}environmentSymbolNameId(){return"EnvironmentEnum"}addErrorEnumSymbolName(t){let r=this.errorEnumSymbolNameId();return this.namespace.registerSymbol(r,t)}getErrorEnumSymbolNameOrThrow(){return this.namespace.getSymbolNameByIdOrThrow(this.errorEnumSymbolNameId())}errorEnumSymbolNameId(){return"ErrorEnum"}addRequestsContainerSymbolName(t){let r=this.requestsContainerSymbolNameId();return this.namespace.registerSymbol(r,t)}getRequestsContainerSymbolNameOrThrow(){return this.namespace.getSymbolNameByIdOrThrow(this.requestsContainerSymbolNameId())}requestsContainerSymbolNameId(){return"RequestsContainer"}addSubClientSymbolName(t,r){let n=this.subClientSymbolNameId(t);return this.namespace.registerSymbol(n,r)}getSubClientSymbolNameOrThrow(t){return this.namespace.getSymbolNameByIdOrThrow(this.subClientSymbolNameId(t))}subClientSymbolNameId(t){return`SubClient:${t}`}addSchemaTypeSymbolName(t,r){let n=this.schemaTypeSymbolNameId(t);return this.namespace.registerSymbol(n,r)}getSchemaTypeSymbolNameOrThrow(t){let r=this.schemaTypeSymbolNameId(t);return this.namespace.getSymbolNameByIdOrThrow(r)}schemaTypeSymbolNameId(t){return`SchemaType:${t}`}};St();var lLn=class{namespace;constructor(){this.namespace=new GC}asIsNameId(t){return`AsIs:${t}`}wireTestSuiteNameId(t){return`WireTestSuite:${t}`}addAsIsSymbol(t){let r=this.asIsNameId(t);this.namespace.registerSymbol(r,[t])}registerWireTestSuiteSymbol(t){return this.namespace.registerSymbol(this.wireTestSuiteNameId(t),[`${t}WireTests`,`${t}WireTestSuite`])}getWireTestSuiteNameOrThrow(t){return this.namespace.getSymbolNameByIdOrThrow(this.wireTestSuiteNameId(t))}};var pLn=class e{static create(){return new e}symbolRegistry;sourceModuleNamespace;testModuleNamespace;requestsNamespace;sourceStaticSymbolsByName;testStaticSymbolsByName;requestTypeSymbols;subClientSymbols;nestedLiteralEnumSymbolsByParentSymbolId;undiscriminatedUnionVariantsByParentSymbolId;constructor(){this.symbolRegistry=Br.SymbolRegistry.create(),this.sourceModuleNamespace=new cLn,this.testModuleNamespace=new lLn,this.requestsNamespace=new uLn,this.sourceStaticSymbolsByName=new Map,this.testStaticSymbolsByName=new Map,this.requestTypeSymbols=[],this.subClientSymbols=[],this.nestedLiteralEnumSymbolsByParentSymbolId=new Map,this.undiscriminatedUnionVariantsByParentSymbolId=new Map}getAsIsSymbolOrThrow(t){let r=this.sourceStaticSymbolsByName.get(t);return Yy(r,`As is symbol not found for name "${t}"`),r}getSourceTemplateSymbolOrThrow(t){switch(t){case"ClientError":return this.getErrorEnumSymbolOrThrow();case"HTTPClient":{let r=this.symbolRegistry.inferSymbolIdForSourceModuleType(t);return Br.Symbol.create(r,t,{type:"class"})}default:Be(t)}}registerSourceModuleSymbol({configModuleName:t,apiNamePascalCase:r,asIsSymbols:n}){let i=[`${r}`,`${r}Api`,`${r}Module`];typeof t=="string"&&i.unshift(t);let s=new GC({reservedSymbolNames:["Swift","Foundation"]}).registerSymbol("Module",i),a=this.symbolRegistry.registerSourceModule(s);return n.forEach(u=>{let c=u.name;this.registerSourceStaticSymbol(c,u.shape)}),a}getRegisteredSourceModuleSymbolOrThrow(){return this.symbolRegistry.getRegisteredSourceModuleSymbolOrThrow()}registerSourceStaticSymbol(t,r){this.symbolRegistry.registerSourceModuleType(t,r),this.sourceModuleNamespace.addStaticSymbolName(t);let n=this.symbolRegistry.inferSymbolIdForSourceModuleType(t),i=Br.Symbol.create(n,t,r);this.sourceStaticSymbolsByName.set(t,i)}registerTestModuleSymbol({sourceModuleName:t,asIsSymbols:r}){let n=[`${t}Tests`,`${t}Test`,`${t}TestsModule`],i=(()=>{let s=new GC;return s.registerSymbol("Swift",["Swift"]),s.registerSymbol("Foundation",["Foundation"]),s.registerSymbol(t,[t]),s.registerSymbol(`${t}Tests`,n)})(),o=this.symbolRegistry.registerTestModule(i);return r.forEach(s=>{let a=s.name;this.symbolRegistry.registerTestModuleType(a,s.shape),this.testModuleNamespace.addAsIsSymbol(a);let u=this.symbolRegistry.inferSymbolIdForTestModuleType(a),c=Br.Symbol.create(u,a,s.shape);this.testStaticSymbolsByName.set(a,c)}),o}getRegisteredTestModuleSymbolOrThrow(){return this.symbolRegistry.getRegisteredTestModuleSymbolOrThrow()}registerRootClientSymbol({configClientClassName:t,registeredSourceModuleName:r}){let n=[`${r}Client`,`${r}ApiClient`,`${r}Service`];typeof t=="string"&&n.unshift(t);let i=this.sourceModuleNamespace.addRootClientSymbolName(n);return this.symbolRegistry.registerSourceModuleType(i,{type:"class"})}getRootClientSymbolOrThrow(){let t=this.sourceModuleNamespace.getRootClientSymbolNameOrThrow(),r=this.symbolRegistry.inferSymbolIdForSourceModuleType(t);return this.symbolRegistry.getSymbolByIdOrThrow(r)}registerEnvironmentSymbol({configEnvironmentEnumName:t,registeredSourceModuleName:r}){let n=[`${r}Environment`,`${r}Environ`,`${r}Env`];typeof t=="string"&&n.unshift(t);let i=this.sourceModuleNamespace.addEnvironmentSymbolName(n);return this.symbolRegistry.registerSourceModuleType(i,{type:"enum-with-raw-values"})}getEnvironmentSymbolOrThrow(){let t=this.sourceModuleNamespace.getEnvironmentSymbolNameOrThrow(),r=this.symbolRegistry.inferSymbolIdForSourceModuleType(t);return this.symbolRegistry.getSymbolByIdOrThrow(r)}registerErrorEnumSymbol(t){let r=[`${t}Error`,`${t}ClientError`],n=this.sourceModuleNamespace.addErrorEnumSymbolName(r);return this.symbolRegistry.registerSourceModuleType(n,{type:"enum-with-associated-values"})}getErrorEnumSymbolOrThrow(){let t=this.sourceModuleNamespace.getErrorEnumSymbolNameOrThrow(),r=this.symbolRegistry.inferSymbolIdForSourceModuleType(t);return this.symbolRegistry.getSymbolByIdOrThrow(r)}registerRequestsContainerSymbol(){let t=this.sourceModuleNamespace.addRequestsContainerSymbolName(["Requests","RequestTypes","InlineRequests"]);return this.symbolRegistry.registerSourceModuleType(t,{type:"enum-container"})}getRequestsContainerSymbolOrThrow(){let t=this.sourceModuleNamespace.getRequestsContainerSymbolNameOrThrow(),r=this.symbolRegistry.inferSymbolIdForSourceModuleType(t);return this.symbolRegistry.getSymbolByIdOrThrow(r)}registerRequestTypeSymbol({endpointId:t,requestNamePascalCase:r}){let n=[`${r}Type`];r.endsWith("Request")?n.push(`${r}Body`,`${r}BodyType`):n.push(`${r}Request`,`${r}RequestBody`,`${r}RequestBodyType`);let i=this.getRequestsContainerSymbolOrThrow(),o=this.requestsNamespace.addRequestTypeSymbol(t,r,[r,...n]),s=this.symbolRegistry.registerNestedType({parentSymbol:i,symbolName:o,shape:{type:"struct"}});return this.requestTypeSymbols.push(s),s}getRequestTypeSymbolOrThrow(t,r){let n=this.requestsNamespace.getRequestTypeNameOrThrow(t,r),i=this.getRequestsContainerSymbolOrThrow(),o=this.symbolRegistry.inferSymbolIdForNestedType(i.id,n);return this.symbolRegistry.getSymbolByIdOrThrow(o)}getAllRequestTypeSymbols(){return[...this.requestTypeSymbols]}registerSubClientSymbol({subpackageId:t,fernFilepathPartNamesPascalCase:r,subpackageNamePascalCase:n}){let i=r.toReversed();i.shift();let o=i.map((u,c)=>i.slice(0,c+1).reverse().join("")+n+"Client"),s=this.sourceModuleNamespace.addSubClientSymbolName(t,[`${n}Client`,...o]),a=this.symbolRegistry.registerSourceModuleType(s,{type:"class"});return this.subClientSymbols.push(a),a}getSubClientSymbolOrThrow(t){let r=this.sourceModuleNamespace.getSubClientSymbolNameOrThrow(t),n=this.symbolRegistry.inferSymbolIdForSourceModuleType(r);return this.symbolRegistry.getSymbolByIdOrThrow(n)}getAllSubClientSymbols(){return[...this.subClientSymbols]}registerSchemaTypeSymbol(t,r,n){let i=this.sourceModuleNamespace.addSchemaTypeSymbolName(t,[r,`${r}Type`,`${r}Model`,`${r}Schema`]);return this.symbolRegistry.registerSourceModuleType(i,n)}getSchemaTypeSymbolOrThrow(t){let r=this.sourceModuleNamespace.getSchemaTypeSymbolNameOrThrow(t),n=this.symbolRegistry.inferSymbolIdForSourceModuleType(r);return this.symbolRegistry.getSymbolByIdOrThrow(n)}registerNestedLiteralEnumSymbol({parentSymbol:t,literalValue:r}){let n=typeof t=="string"?t:t.id,i=this.nestedLiteralEnumSymbolsByParentSymbolId.get(n)??new Map,o=i.get(r);if(o)return o;let s=Array.from(i.values()),a=(()=>{let c=new GC({reservedSymbolNames:["CodingKeys"]});s.forEach(p=>{c.registerSymbol(p.id,[p.name])});let l=nLe.generateName(r);return c.registerSymbol(r,[l,`${l}Literal`,`${l}Enum`,`${l}StringEnum`])})(),u=this.symbolRegistry.registerNestedType({parentSymbol:t,symbolName:a,shape:{type:"enum-with-raw-values"}});return i.set(r,u),this.nestedLiteralEnumSymbolsByParentSymbolId.set(n,i),u}getNestedLiteralEnumSymbolOrThrow(t,r){let n=typeof t=="string"?t:t.id,o=(this.nestedLiteralEnumSymbolsByParentSymbolId.get(n)??new Map).get(r);return Yy(o,`Nested literal enum symbol not found for literal value "${r}" in parent symbol "${n}"`),o}getAllNestedLiteralEnumSymbolsOrThrow(t){let r=typeof t=="string"?t:t.id,n=this.nestedLiteralEnumSymbolsByParentSymbolId.get(r)??new Map;return Array.from(n.entries()).sort(([,i],[,o])=>i.name.localeCompare(o.name)).map(([i,o])=>({symbol:o,literalValue:i,caseLabel:nLe.generateEnumCaseLabel(i)}))}registerUndiscriminatedUnionVariants({parentSymbol:t,variants:r}){let n=typeof t=="string"?t:t.id,i=uze(r,(o,s)=>o.caseName===s.caseName);return i.sort((o,s)=>o.caseName.localeCompare(s.caseName)),this.undiscriminatedUnionVariantsByParentSymbolId.set(n,i),i}getAllUndiscriminatedUnionVariantsOrThrow(t){let r=typeof t=="string"?t:t.id;return this.undiscriminatedUnionVariantsByParentSymbolId.get(r)??[]}registerWireTestSuiteSymbol(t){let r=this.testModuleNamespace.registerWireTestSuiteSymbol(t);return this.symbolRegistry.registerTestModuleType(r,{type:"struct"})}getWireTestSuiteSymbolOrThrow(t){let r=this.testModuleNamespace.getWireTestSuiteNameOrThrow(t),n=this.symbolRegistry.inferSymbolIdForTestModuleType(r);return this.symbolRegistry.getSymbolByIdOrThrow(n)}referenceFromSourceModuleScope(t){let r=this.getRegisteredSourceModuleSymbolOrThrow();return this.symbolRegistry.reference({fromSymbol:r,toSymbol:t})}reference({fromSymbol:t,toSymbol:r}){return this.symbolRegistry.reference({fromSymbol:t,toSymbol:r})}resolveReference({fromSymbol:t,reference:r}){return this.symbolRegistry.resolveReference({fromSymbol:t,reference:r})}};var Br={};Z(Br,{AccessLevel:()=>wXu,Class:()=>ydt,CodeBlock:()=>dS,Comment:()=>bdt,ComputedProperty:()=>Idt,DeclarationType:()=>KLt,DocComment:()=>wdt,EnumWithAssociatedValues:()=>Cdt,EnumWithRawValues:()=>xdt,Expression:()=>kne,Extension:()=>_dt,FunctionArgument:()=>Sdt,FunctionParameter:()=>Bdt,Initializer:()=>Odt,LineBreak:()=>fLn,Method:()=>Tdt,Pattern:()=>dLn,Property:()=>Pdt,Protocol:()=>xXu,SourceAsIsFileSpecs:()=>dFm,SourceTemplateFileSpecs:()=>mFm,Statement:()=>vdt,Struct:()=>Ddt,Symbol:()=>_C,SymbolRegistry:()=>Ymo,TypeReference:()=>mLn,class_:()=>hFm,codeBlock:()=>gFm,comment:()=>AFm,computedProperty:()=>yFm,docComment:()=>bFm,enumWithAssociatedValues:()=>EFm,enumWithRawValues:()=>vFm,extension:()=>IFm,functionArgument:()=>wFm,functionParameter:()=>CFm,initializer:()=>xFm,method:()=>_Fm,property:()=>SFm,struct:()=>BFm});var wXu={Open:"open",Public:"public",Package:"package",Internal:"internal",Fileprivate:"fileprivate",Private:"private"};var HLt=class extends wC{toString(){return this.buffer}};var ep=class extends O0{toString(){let t=new HLt;return this.write(t),t.toString()}toStringWithIndentation(t){let r=new HLt;for(let n=1;n<t;n++)r.indent();this.write(r);for(let n=1;n<t;n++)r.dedent();return r.toString()}};var ydt=class extends ep{name;final;accessLevel;conformances;properties;initializers;methods;docs;constructor({accessLevel:t,name:r,final:n,conformances:i,properties:o,initializers:s,methods:a,docs:u}){super(),this.name=r,this.final=n,this.accessLevel=t,this.conformances=i??[],this.properties=o,this.initializers=s??[],this.methods=a??[],this.docs=u}write(t){this.docs!=null&&this.docs.write(t),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),this.final&&t.write("final "),t.write(`class ${this.name}`),this.conformances.forEach((r,n)=>{n===0?t.write(": "):n>0&&t.write(", "),t.write(r)}),t.write(" {"),t.newLine(),t.indent(),this.properties.forEach(r=>{r.write(t),t.newLine()}),this.initializers.length>0&&(t.newLine(),this.initializers.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()})),this.methods.length>0&&(t.newLine(),this.methods.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()})),t.dedent(),t.write("}")}};St();var dS=class e extends ep{args;constructor(t){super(),this.args=t}write(t){let r=new Ly(this.args);t.write("{"),t.newLine(),t.indent(),r.write(t),t.dedent(),t.write("}")}static empty(){return new e(ft)}static withStatements(t){return new e(r=>{t.forEach(n=>{n.write(r)})})}};var bdt=class extends ep{content;constructor({content:t}){super(),this.content=t}write(t){this.content.split(`
2573
2573
  `).forEach(n=>{t.write(`// ${n}`),t.newLine()})}};St();function CXu(e){return e.replace(/\\u([0-9a-fA-F]{4})/g,"\\u{$1}").replace(/(?<!\\)\\f/g,"\\u{000C}").replace(/(?<!\\)\\v/g,"\\u{000B}").replace(/(?<!\\)\\0/g,"\\u{0000}").replace(/(?<!\\)"/g,'\\"')}var pFm=["Any","as","associatedtype","break","case","catch","class","continue","default","defer","deinit","do","else","fallthrough","false","for","guard","enum","extension","fileprivate","func","if","import","in","init","inout","internal","is","let","nil","operator","private","precedencegroup","Protocol","protocol","public","repeat","rethrows","return","Self","self","static","struct","subscript","super","switch","throw","throws","true","try","Type","typealias","var","where","while"],fFm=new Set(pFm);function iLe(e){return fFm.has(e)}function vQ(e){return iLe(e)?`\`${e}\``:e}function Edt(e){return e==="self"?"self_":e}St();var kne=class extends ep{internalExpression;constructor(t){super(),this.internalExpression=t}isNop(){return this.internalExpression.type==="nop"}isStructInitialization(){return this.internalExpression.type==="struct-initialization"}asStructInitializationOrThrow(){if(this.internalExpression.type!=="struct-initialization")throw new Error("Internal error; swift.Expression is not a struct initialization");return this.internalExpression}write(t){switch(this.internalExpression.type){case"reference":t.write(vQ(this.internalExpression.unsafeName));break;case"member-access":this.internalExpression.target.write(t),this.internalExpression.optionalChain&&t.write("?"),t.write("."),t.write(this.internalExpression.memberName);break;case"equals":this.internalExpression.left.write(t),t.write(" == "),this.internalExpression.right.write(t);break;case"enum-case-shorthand":t.write("."),t.write(this.internalExpression.caseName);break;case"function-call":this.writeCallableExpression({writer:t,target:vQ(this.internalExpression.unsafeName),arguments_:this.internalExpression.arguments_,multiline:!!this.internalExpression.multiline});break;case"struct-initialization":this.writeCallableExpression({writer:t,target:vQ(this.internalExpression.unsafeName),arguments_:this.internalExpression.arguments_,multiline:!!this.internalExpression.multiline});break;case"class-initialization":this.writeCallableExpression({writer:t,target:vQ(this.internalExpression.unsafeName),arguments_:this.internalExpression.arguments_,multiline:!!this.internalExpression.multiline});break;case"method-call":this.internalExpression.target.write(t),t.write("."),this.writeCallableExpression({writer:t,target:this.internalExpression.methodName,arguments_:this.internalExpression.arguments_,multiline:!!this.internalExpression.multiline});break;case"method-call-with-trailing-closure":this.internalExpression.target.write(t),t.write("."),t.write(this.internalExpression.methodName),t.write(" {"),this.internalExpression.multiline?(t.newLine(),t.indent()):t.write(" "),this.internalExpression.closureBody.write(t),this.internalExpression.multiline?(t.newLine(),t.dedent()):t.write(" "),t.write("}");break;case"contextual-method-call":t.write("."),this.writeCallableExpression({writer:t,target:this.internalExpression.methodName,arguments_:this.internalExpression.arguments_,multiline:!!this.internalExpression.multiline});break;case"try":t.write("try "),this.internalExpression.expression.write(t);break;case"optional-try":t.write("try? "),this.internalExpression.expression.write(t);break;case"force-try":t.write("try! "),this.internalExpression.expression.write(t);break;case"await":t.write("await "),this.internalExpression.expression.write(t);break;case"string-literal":t.write(`"${this.internalExpression.value}"`);break;case"number-literal":t.write(this.internalExpression.value.toString());break;case"bool-literal":t.write(this.internalExpression.value?"true":"false");break;case"date-literal":t.write(`try! Date("${this.internalExpression.isoString}", strategy: .iso8601)`);break;case"calendar-date-literal":t.write(`CalendarDate("${this.internalExpression.isoString}")!`);break;case"uuid-literal":t.write(`UUID(uuidString: "${this.internalExpression.value}")!`);break;case"dictionary-literal":this.writeDictionaryLiteral(t,this.internalExpression);break;case"array-literal":this.writeArrayLiteral(t,this.internalExpression);break;case"data-literal":t.write(`Data("${this.internalExpression.value}".utf8)`);break;case"raw-value":t.write(this.internalExpression.value);break;case"nop":break;default:Be(this.internalExpression)}}writeCallableExpression({writer:t,target:r,arguments_:n,multiline:i}){t.write(r),t.write("("),i&&(t.newLine(),t.indent()),n?.forEach((o,s)=>{s>0&&(t.write(","),i?t.newLine():t.write(" ")),o.write(t)}),i&&(t.newLine(),t.dedent()),t.write(")")}writeDictionaryLiteral(t,r){if(!r.entries||r.entries.length===0){t.write("[:]");return}t.write("[");let n=!!r.multiline;n&&(t.newLine(),t.indent()),r.entries?.forEach(([i,o],s)=>{s>0&&(t.write(", "),n&&t.newLine()),i.write(t),t.write(": "),o.write(t)}),n&&(t.newLine(),t.dedent()),t.write("]")}writeArrayLiteral(t,r){if(!r.elements||r.elements.length===0){t.write("[]");return}t.write("[");let n=!!r.multiline;n&&(t.newLine(),t.indent()),r.elements?.forEach((i,o)=>{o>0&&(t.write(","),n?t.newLine():t.write(" ")),i.write(t)}),n&&(t.newLine(),t.dedent()),t.write("]")}static reference(t){return new this({type:"reference",unsafeName:t})}static memberAccess(t){return new this({type:"member-access",...t})}static equals(t,r){return new this({type:"equals",left:t,right:r})}static enumCaseShorthand(t){return new this({type:"enum-case-shorthand",caseName:t})}static functionCall(t){return new this({type:"function-call",...t})}static structInitialization(t){return new this({type:"struct-initialization",...t})}static classInitialization(t){return new this({type:"class-initialization",...t})}static stringLiteral(t){return new this({type:"string-literal",value:t})}static numberLiteral(t){return new this({type:"number-literal",value:t})}static boolLiteral(t){return new this({type:"bool-literal",value:t})}static dateLiteral(t){return new this({type:"date-literal",isoString:t})}static calendarDateLiteral(t){return new this({type:"calendar-date-literal",isoString:t})}static uuidLiteral(t){return new this({type:"uuid-literal",value:t})}static dictionaryLiteral(t){return new this({type:"dictionary-literal",...t})}static arrayLiteral(t){return new this({type:"array-literal",...t})}static dataLiteral(t){return new this({type:"data-literal",value:t})}static methodCall(t){return new this({type:"method-call",...t})}static methodCallWithTrailingClosure(t){return new this({type:"method-call-with-trailing-closure",...t})}static contextualMethodCall(t){return new this({type:"contextual-method-call",...t})}static try(t){return new this({type:"try",expression:t})}static optionalTry(t){return new this({type:"optional-try",expression:t})}static forceTry(t){return new this({type:"force-try",expression:t})}static await(t){return new this({type:"await",expression:t})}static rawValue(t){return new this({type:"raw-value",value:t})}static nop(){return new this({type:"nop"})}static nil(){return new this({type:"raw-value",value:"nil"})}static self(){return new this({type:"raw-value",value:"self"})}};St();var KLt={Var:"var",Let:"let"};var vdt=class extends ep{internalStatement;constructor(t){super(),this.internalStatement=t}write(t){switch(this.internalStatement.type){case"typealias-declaration":this.internalStatement.docs!=null&&this.internalStatement.docs.write(t),this.internalStatement.accessLevel&&(t.write(this.internalStatement.accessLevel),t.write(" ")),t.write("typealias "),t.write(this.internalStatement.unsafeName),t.write(" = "),this.internalStatement.aliasedType.write(t),t.newLine();break;case"constant-declaration":t.write(KLt.Let),t.write(" "),t.write(vQ(this.internalStatement.unsafeName)),t.write(" = "),this.internalStatement.value.write(t),this.internalStatement.noTrailingNewline||t.newLine();break;case"variable-declaration":t.write(KLt.Var),t.write(" "),t.write(vQ(this.internalStatement.unsafeName)),t.write(" = "),this.internalStatement.value.write(t),this.internalStatement.noTrailingNewline||t.newLine();break;case"function-declaration":this.internalStatement.docs!=null&&this.internalStatement.docs.write(t),this.internalStatement.accessLevel!=null&&(t.write(this.internalStatement.accessLevel),t.write(" ")),t.write("func "),t.write(vQ(this.internalStatement.unsafeName)),t.write("("),this.internalStatement.parameters?.forEach((r,n)=>{n>0&&t.write(", "),r.write(t)}),t.write(")"),this.internalStatement.async&&t.write(" async"),this.internalStatement.throws&&t.write(" throws"),this.internalStatement.returnType&&(t.write(" -> "),this.internalStatement.returnType.write(t)),t.write(" "),(this.internalStatement.body??dS.empty()).write(t),t.newLine();break;case"variable-assignment":t.write(vQ(this.internalStatement.unsafeName)),t.write(" = "),this.internalStatement.value.write(t),t.newLine();break;case"self-assignment":t.write("self = "),t.write(this.internalStatement.value.toString()),t.newLine();break;case"property-assignment":t.write("self."),t.write(this.internalStatement.unsafeName),t.write(" = "),this.internalStatement.value.write(t),t.newLine();break;case"discard-assignment":t.write("_ = "),this.internalStatement.value.write(t),t.newLine();break;case"return":t.write("return "),this.internalStatement.expression.write(t),t.newLine();break;case"throw":t.write("throw "),this.internalStatement.expression.write(t),t.newLine();break;case"expression-statement":this.internalStatement.expression.write(t),t.newLine();break;case"import":t.write("import "),t.write(this.internalStatement.moduleName),t.newLine();break;case"switch":t.write("switch "),this.internalStatement.target.write(t),t.write(" {"),t.newLine();for(let r of this.internalStatement.cases)if(t.write("case "),r.pattern.write(t),t.write(":"),t.newLine(),r.body.length>0){t.indent();for(let n of r.body)n.write(t);t.dedent()}if(this.internalStatement.defaultCase&&(t.write("default:"),t.newLine(),this.internalStatement.defaultCase.length>0)){t.indent();for(let r of this.internalStatement.defaultCase)r.write(t);t.dedent()}t.write("}"),t.newLine();break;case"if":{t.write("if "),this.internalStatement.condition.write(t),t.write(" "),dS.withStatements(this.internalStatement.body).write(t);for(let r of this.internalStatement.elseIfs??[])t.write(" else if "),r.condition.write(t),t.write(" "),dS.withStatements(r.body).write(t);this.internalStatement.else&&(t.write(" else "),dS.withStatements(this.internalStatement.else).write(t)),t.newLine();break}case"raw":t.write(this.internalStatement.content),t.newLine();break;default:Be(this.internalStatement)}}static typealiasDeclaration(t){return new this({type:"typealias-declaration",...t})}static constantDeclaration(t){return new this({type:"constant-declaration",...t})}static variableDeclaration(t){return new this({type:"variable-declaration",...t})}static functionDeclaration(t){return new this({type:"function-declaration",...t})}static variableAssignment(t,r){return new this({type:"variable-assignment",unsafeName:t,value:r})}static selfAssignment(t){return new this({type:"self-assignment",value:t})}static propertyAssignment(t,r){return new this({type:"property-assignment",unsafeName:t,value:r})}static discardAssignment(t){return new this({type:"discard-assignment",value:t})}static return(t){return new this({type:"return",expression:t})}static throw(t){return new this({type:"throw",expression:t})}static expressionStatement(t){return new this({type:"expression-statement",expression:t})}static import(t){return new this({type:"import",moduleName:t})}static switch(t){return new this({type:"switch",...t})}static if(t){return new this({type:"if",...t})}static raw(t){return new this({type:"raw",content:t})}};var Idt=class extends ep{unsafeName;accessLevel;type;body;docs;constructor({unsafeName:t,accessLevel:r,type:n,body:i,docs:o}){super(),this.unsafeName=t,this.accessLevel=r,this.type=n,this.body=i,this.docs=o}write(t){this.docs!=null&&this.docs.write(t),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),t.write("var "),t.write(vQ(this.unsafeName)),t.write(": "),this.type.write(t),t.write(" "),this.body instanceof dS?this.body.write(t):this.body instanceof kne?dS.withStatements([vdt.expressionStatement(this.body)]).write(t):Be(this.body)}};var wdt=class e extends ep{summary;description;parameters;returns;throws;constructor({summary:t,description:r,parameters:n,returns:i,throws:o}){super(),this.summary=e.sanitizeText(t),this.description=r!=null?e.sanitizeText(r):void 0,this.parameters=(n??[]).map(s=>({name:s.name,description:e.sanitizeText(s.description)})),this.returns=i!=null?e.sanitizeText(i):void 0,this.throws=(o??[]).map(s=>e.sanitizeText(s))}write(t){if(this.writeMultilineText(t,this.summary),this.description!=null&&(t.write("///"),t.newLine(),this.writeMultilineText(t,this.description)),this.parameters.length>0){t.write("///"),t.newLine();for(let r of this.parameters)r.description.split(`
2574
2574
  `).forEach((i,o)=>{o===0?(t.write("/// - Parameter "),t.write(r.name),t.write(": "),t.write(i)):(t.write("/// "),t.write(i)),t.newLine()})}if(this.returns!=null&&this.returns.split(`
2575
2575
  `).forEach((n,i)=>{i===0?(t.write("/// - Returns: "),t.write(n)):(t.write("/// "),t.write(n)),t.newLine()}),this.throws.length>0)for(let r of this.throws)r.split(`
2576
2576
  `).forEach((i,o)=>{o===0?(t.write("/// - Throws: "),t.write(i)):(t.write("/// "),t.write(i)),t.newLine()})}writeMultilineText(t,r){let n=r.split(`
2577
2577
  `);for(let i of n)t.write("/// "),t.write(i),t.newLine()}static sanitizeText(t){return t=t.replace(/\r\n/g,`
2578
2578
  `).replace(/\r/g,`
2579
- `),t=t.replace(/\x00/g,""),t}};var Cdt=class extends ep{name;accessLevel;indirect;conformances;cases;initializers;methods;nestedTypes;docs;constructor({accessLevel:t,indirect:r,name:n,conformances:i,cases:o,initializers:s,methods:a,nestedTypes:u,docs:c}){super(),this.name=n,this.indirect=r??!1,this.accessLevel=t,this.conformances=i??[],this.cases=o,this.initializers=s??[],this.methods=a??[],this.nestedTypes=u??[],this.docs=c}write(t){this.docs!=null&&this.docs.write(t),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),this.indirect&&t.write("indirect "),t.write(`enum ${this.name}`),this.conformances.forEach((r,n)=>{n===0?t.write(": "):n>0&&t.write(", "),t.write(r)}),t.write(" {"),t.newLine(),t.indent(),this.cases.forEach(r=>{r.docs!=null&&r.docs.write(t),t.write("case "),iLe(r.unsafeName)?t.write(`\`${r.unsafeName}\``):t.write(r.unsafeName),r.associatedValue!=null&&(t.write("("),r.associatedValue.forEach((n,i)=>{i>0&&t.write(", "),n.write(t)}),t.write(")")),t.newLine()}),this.initializers.length>0&&(t.newLine(),this.initializers.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()})),this.methods.length>0&&(t.newLine(),this.methods.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()})),this.nestedTypes.length>0&&(t.newLine(),this.nestedTypes.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()})),t.dedent(),t.write("}")}};var xdt=class extends ep{name;accessLevel;conformances;cases;docs;constructor({accessLevel:t,name:r,conformances:n,cases:i,docs:o}){super(),this.name=r,this.accessLevel=t,this.conformances=n??[],this.cases=i,this.docs=o}write(t){if(this.docs!=null&&this.docs.write(t),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),t.write(`enum ${this.name}`),this.conformances.forEach((r,n)=>{n===0?t.write(": "):n>0&&t.write(", "),t.write(r)}),this.cases.length===0){t.write(" {}");return}t.write(" {"),t.newLine(),t.indent(),this.cases.forEach(r=>{r.docs!=null&&r.docs.write(t),t.write("case "),iLe(r.unsafeName)?t.write(`\`${r.unsafeName}\``):t.write(r.unsafeName),r.rawValue!==r.unsafeName&&(t.write(" = "),t.write(`"${CXu(r.rawValue)}"`)),t.newLine()}),t.dedent(),t.write("}")}};var _dt=class extends ep{name;conformances;initializers;computedProperties;methods;nestedTypes;docs;constructor({name:t,conformances:r,initializers:n,computedProperties:i,methods:o,nestedTypes:s,docs:a}){super(),this.name=t,this.conformances=r??[],this.initializers=n??[],this.computedProperties=i??[],this.methods=o??[],this.nestedTypes=s??[],this.docs=a}write(t){this.docs!=null&&this.docs.write(t),t.write(`extension ${this.name}`),this.conformances.forEach((r,n)=>{n===0?t.write(": "):n>0&&t.write(", "),t.write(r)}),t.write(" {"),this.initializers.length>0&&(t.newLine(),t.indent(),this.initializers.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()}),t.dedent()),this.computedProperties.length>0&&(t.newLine(),t.indent(),this.computedProperties.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()}),t.dedent()),this.methods.length>0&&(t.newLine(),t.indent(),this.methods.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()}),t.dedent()),this.nestedTypes.length>0&&(t.newLine(),t.indent(),this.nestedTypes.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()}),t.dedent()),t.write("}")}};var Sdt=class extends ep{label;value;constructor({label:t,value:r}){super(),this.label=t,this.value=r}write(t){this.label!=null&&(t.write(this.label),t.write(": ")),this.value.write(t)}};var Bdt=class extends ep{argumentLabel;unsafeName;escaping;type;defaultValue;docsContent;constructor({argumentLabel:t,unsafeName:r,escaping:n,type:i,defaultValue:o,docsContent:s}){super(),this.argumentLabel=t,this.unsafeName=r,this.escaping=n,this.type=i,this.defaultValue=o,this.docsContent=s}write(t){this.argumentLabel==null?t.write("_ "):this.argumentLabel!==this.unsafeName&&(t.write(this.argumentLabel),t.write(" ")),t.write(this.unsafeName),t.write(": "),this.escaping&&t.write("@escaping "),this.type.write(t),this.defaultValue!=null&&(t.write(" = "),this.defaultValue.write(t))}};var Odt=class extends ep{accessLevel;convenience;failable;throws;parameters;body;multiline;docs;constructor({accessLevel:t,convenience:r,failable:n,throws:i,parameters:o,body:s,multiline:a,docs:u}){super(),this.accessLevel=t,this.convenience=r,this.failable=n,this.throws=i,this.parameters=o??[],this.body=s??dS.empty(),this.multiline=a,this.docs=u}write(t){this.docs!=null&&this.docs.write(t),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),this.convenience&&t.write("convenience "),t.write("init"),this.failable&&t.write("?"),t.write("("),this.multiline&&(t.newLine(),t.indent()),this.parameters.forEach((r,n)=>{n>0&&(t.write(","),this.multiline?t.newLine():t.write(" ")),r.write(t)}),this.multiline&&(t.newLine(),t.dedent()),t.write(") "),this.throws&&t.write("throws "),this.body.write(t)}};var fLn=class e extends ep{count;constructor({count:t=1}={}){super(),this.count=t}write(t){for(let r=0;r<this.count;r++)t.newLine()}static single(){return new e({count:1})}static double(){return new e({count:2})}static multiple(t){return new e({count:t})}};var Tdt=class extends ep{attributes;unsafeName;accessLevel;static_;parameters;async;throws;returnType;body;docs;constructor({attributes:t,unsafeName:r,accessLevel:n,static_:i,parameters:o,async:s,throws:a,returnType:u,body:c,docs:l}){super(),this.attributes=t??[],this.unsafeName=r,this.accessLevel=n,this.static_=i,this.parameters=o??[],this.async=s,this.throws=a,this.returnType=u,this.body=c??dS.empty(),this.docs=l}write(t){this.docs!=null&&this.docs.write(t),this.attributes.forEach(r=>{r.arguments?.length?kne.functionCall({unsafeName:`@${r.name}`,arguments_:r.arguments}).write(t):(t.write("@"),t.write(r.name)),t.write(" ")}),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),this.static_&&t.write("static "),t.write("func "),t.write(vQ(this.unsafeName)),t.write("("),this.parameters.forEach((r,n)=>{n>0&&t.write(", "),r.write(t)}),t.write(")"),this.async&&t.write(" async"),this.throws&&t.write(" throws"),t.write(" -> "),this.returnType.write(t),t.write(" "),this.body.write(t)}};St();var dLn=class extends ep{internalPattern;constructor(t){super(),this.internalPattern=t}write(t){this.internalPattern.type==="enum-case-value-binding"?(t.write("."),t.write(this.internalPattern.caseName),t.write("("),t.write(this.internalPattern.declarationType),t.write(" "),t.write(this.internalPattern.referenceName),t.write(")")):Be(this.internalPattern.type)}static enumCaseValueBinding(t){return new this({type:"enum-case-value-binding",...t})}};var Pdt=class extends ep{unsafeName;accessLevel;static_;declarationType;type;indirect;defaultValue;docs;constructor({unsafeName:t,accessLevel:r,static_:n,declarationType:i,type:o,indirect:s,defaultValue:a,docs:u}){super(),this.unsafeName=t,this.accessLevel=r,this.static_=n,this.declarationType=i,this.type=o,this.indirect=s,this.defaultValue=a,this.docs=u}write(t){this.docs!=null&&this.docs.write(t),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),this.static_&&t.write("static "),t.write(this.declarationType),t.write(" "),iLe(this.unsafeName)?t.write(`\`${this.unsafeName}\``):t.write(this.unsafeName),t.write(": "),this.type.write(t),this.defaultValue!=null&&(t.write(" = "),this.defaultValue.write(t))}};var xXu={CaseIterable:"CaseIterable",Codable:"Codable",CodingKey:"CodingKey",Decodable:"Decodable",Encodable:"Encodable",Equatable:"Equatable",Error:"Error",Hashable:"Hashable",Sendable:"Sendable",MultipartFormDataConvertible:"MultipartFormDataConvertible"};var Ddt=class extends ep{attributes;name;accessLevel;conformances;properties;initializers;methods;nestedTypes;docs;constructor({attributes:t,accessLevel:r,name:n,conformances:i,properties:o,initializers:s,methods:a,nestedTypes:u,docs:c}){super(),this.attributes=t??[],this.name=n,this.accessLevel=r,this.conformances=i??[],this.properties=o??[],this.initializers=s??[],this.methods=a??[],this.nestedTypes=u??[],this.docs=c}write(t){this.docs!=null&&this.docs.write(t),this.attributes.forEach(a=>{a.arguments?.length?kne.functionCall({unsafeName:`@${a.name}`,arguments_:a.arguments}).write(t):(t.write("@"),t.write(a.name)),t.write(" ")}),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),t.write(`struct ${this.name}`),this.conformances.forEach((a,u)=>{u===0?t.write(": "):u>0&&t.write(", "),t.write(a)}),t.write(" {"),t.newLine(),t.indent();let r=this.properties.length>0,n=this.initializers.length>0,i=this.methods.length>0,o=this.nestedTypes.length>0;this.properties.forEach(a=>{a.write(t),t.newLine()});let s=r;n&&(s&&t.newLine(),this.initializers.forEach((a,u)=>{u>0&&t.newLine(),a.write(t),t.newLine()}),s=!0),i&&(s&&t.newLine(),this.methods.forEach((a,u)=>{u>0&&t.newLine(),a.write(t),t.newLine()}),s=!0),o&&(s&&t.newLine(),this.nestedTypes.forEach((a,u)=>{u>0&&t.newLine(),a.write(t),t.newLine()})),t.dedent(),t.write("}")}};St();var mLn=class e extends ep{variant;constructor(t){super(),this.variant=t}nonOptional(){return e.nonOptional(this)}nonNullable(){return e.nonNullable(this)}getReferenceIfSymbolType(){return this.variant.type==="symbol"?this.variant.symbol:null}write(t){let{variant:r}=this;switch(r.type){case"symbol":t.write(r.symbol);break;case"generic":{r.reference.write(t),r.arguments.length>0&&(t.write("<"),r.arguments.forEach((n,i)=>{n.write(t),i<r.arguments.length-1&&t.write(", ")}),t.write(">"));break}case"tuple":t.write("("),r.elements.forEach((n,i)=>{i>0&&t.write(", "),n.write(t)}),t.write(")");break;case"array":t.write("["),r.elementType.write(t),t.write("]");break;case"dictionary":t.write("["),r.keyType.write(t),t.write(": "),r.valueType.write(t),t.write("]");break;case"optional":r.valueType.write(t),t.write("?");break;case"nullable":t.write("Nullable<"),r.valueType.write(t),t.write(">");break;case"member-access":r.target.write(t),t.write("."),t.write(r.memberName);break;default:Be(r)}}equals(t){switch(this.variant.type){case"symbol":return t.variant.type==="symbol"&&this.variant.symbol===t.variant.symbol;case"generic":return t.variant.type==="generic"&&this.variant.reference.equals(t.variant.reference)&&this.variant.arguments.every((r,n)=>t.variant.type==="generic"&&t.variant.arguments[n]&&r.equals(t.variant.arguments[n]));case"tuple":return t.variant.type==="tuple"&&this.variant.elements.every((r,n)=>t.variant.type==="tuple"&&t.variant.elements[n]&&r.equals(t.variant.elements[n]));case"array":return t.variant.type==="array"&&this.variant.elementType.equals(t.variant.elementType);case"dictionary":return t.variant.type==="dictionary"&&this.variant.keyType.equals(t.variant.keyType)&&this.variant.valueType.equals(t.variant.valueType);case"optional":return t.variant.type=="optional"&&this.variant.valueType.equals(t.variant.valueType);case"nullable":return t.variant.type==="nullable"&&this.variant.valueType.equals(t.variant.valueType);case"member-access":return t.variant.type==="member-access"&&this.variant.target.equals(t.variant.target)&&this.variant.memberName===t.variant.memberName;default:Be(this.variant)}}static symbol(t){return new this({type:"symbol",symbol:t})}static generic(t,r){return new this({type:"generic",reference:t,arguments:r})}static tuple(t){return new this({type:"tuple",elements:t})}static array(t){return new this({type:"array",elementType:t})}static dictionary(t,r){return new this({type:"dictionary",keyType:t,valueType:r})}static optional(t){return t.variant.type==="optional"?t:new this({type:"optional",valueType:t})}static nullable(t){return t.variant.type==="nullable"?t:new this({type:"nullable",valueType:t})}static memberAccess(t,r){return new this({type:"member-access",target:t,memberName:r})}static nonOptional(t){return t.variant.type==="optional"?e.nonOptional(t.variant.valueType):t}static nonNullable(t){return t.variant.type==="nullable"?e.nonNullable(t.variant.valueType):t}static unqualifiedToSwiftType(t){return e.symbol(t)}static unqualifiedToFoundationType(t){return e.symbol(t)}};var dFm={Http:{relativePathToDir:"Core/Networking",filenameWithoutExtension:"HTTP",symbols:[{name:"HTTP",shape:{type:"enum-container"}}]},MultipartFormData:{relativePathToDir:"Core/Networking",filenameWithoutExtension:"MultipartFormData",symbols:[{name:"MultipartFormData",shape:{type:"class"}}]},MultipartFormDataConvertible:{relativePathToDir:"Core/Networking",filenameWithoutExtension:"MultipartFormDataConvertible",symbols:[{name:"MultipartFormDataConvertible",shape:{type:"protocol"}}]},MultipartFormField:{relativePathToDir:"Core/Networking",filenameWithoutExtension:"MultipartFormField",symbols:[{name:"MultipartFormField",shape:{type:"enum-with-associated-values"}}]},QueryParameter:{relativePathToDir:"Core/Networking",filenameWithoutExtension:"QueryParameter",symbols:[{name:"QueryParameter",shape:{type:"enum-with-associated-values"}}]},DecoderPlusAdditionalProperties:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"Decoder+AdditionalProperties",symbols:[]},EncodableValue:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"EncodableValue",symbols:[{name:"EncodableValue",shape:{type:"struct"}}]},EncoderPlusAdditionalProperties:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"Encoder+AdditionalProperties",symbols:[]},JSONEncoderPlusEncodableValue:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"JSONEncoder+EncodableValue",symbols:[]},KeyedDecodingContainerPlusNullable:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"KeyedDecodingContainer+Nullable",symbols:[]},KeyedEncodingContainerPlusNullable:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"KeyedEncodingContainer+Nullable",symbols:[]},Serde:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"Serde",symbols:[{name:"Serde",shape:{type:"class"}}]},StringKey:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"StringKey",symbols:[{name:"StringKey",shape:{type:"struct"}}]},DataPlusString:{relativePathToDir:"Core",filenameWithoutExtension:"Data+String",symbols:[]},StringPlusUrlEncoding:{relativePathToDir:"Core",filenameWithoutExtension:"String+URLEncoding",symbols:[]},CalendarDate:{relativePathToDir:"Public",filenameWithoutExtension:"CalendarDate",symbols:[{name:"CalendarDate",shape:{type:"struct"}}]},ClientConfig:{relativePathToDir:"Public",filenameWithoutExtension:"ClientConfig",symbols:[{name:"ClientConfig",shape:{type:"class"}}]},FormFile:{relativePathToDir:"Public",filenameWithoutExtension:"FormFile",symbols:[{name:"FormFile",shape:{type:"struct"}}]},HTTPError:{relativePathToDir:"Public",filenameWithoutExtension:"HTTPError",symbols:[{name:"HTTPError",shape:{type:"struct"}}]},Indirect:{relativePathToDir:"Public",filenameWithoutExtension:"Indirect",symbols:[{name:"Indirect",shape:{type:"class"}}]},JsonValue:{relativePathToDir:"Public",filenameWithoutExtension:"JSONValue",symbols:[{name:"JSONValue",shape:{type:"enum-with-associated-values"}}]},Networking:{relativePathToDir:"Public",filenameWithoutExtension:"Networking",symbols:[{name:"Networking",shape:{type:"enum-container"}}]},Nullable:{relativePathToDir:"Public",filenameWithoutExtension:"Nullable",symbols:[{name:"Nullable",shape:{type:"enum-with-associated-values"}}]},RequestOptions:{relativePathToDir:"Public",filenameWithoutExtension:"RequestOptions",symbols:[{name:"RequestOptions",shape:{type:"struct"}}]}};var _C=class e{static SWIFT_SYMBOL_NAME="Swift";static SWIFT_SYMBOL_ID=e.SWIFT_SYMBOL_NAME;static swiftTypeSymbolsByName={String:e.swiftType("String"),Bool:e.swiftType("Bool"),Int:e.swiftType("Int"),Int64:e.swiftType("Int64"),UInt:e.swiftType("UInt"),UInt64:e.swiftType("UInt64"),Float:e.swiftType("Float"),Double:e.swiftType("Double"),Void:e.swiftType("Void"),Encoder:e.swiftType("Encoder"),Decoder:e.swiftType("Decoder"),Any:e.swiftType("Any")};static swiftTypeSymbols=Object.values(e.swiftTypeSymbolsByName);static FOUNDATION_SYMBOL_NAME="Foundation";static FOUNDATION_SYMBOL_ID=e.FOUNDATION_SYMBOL_NAME;static foundationTypeSymbolsByName={Data:e.foundationType("Data"),Date:e.foundationType("Date"),UUID:e.foundationType("UUID")};static foundationTypeSymbols=Object.values(e.foundationTypeSymbolsByName);static isSwiftSymbol(t){return e.SWIFT_SYMBOL_ID===t||t.startsWith(`${e.SWIFT_SYMBOL_ID}.`)}static isSwiftSymbolName(t){return t in e.swiftTypeSymbolsByName}static isFoundationSymbol(t){return e.FOUNDATION_SYMBOL_ID===t||t.startsWith(`${e.FOUNDATION_SYMBOL_ID}.`)}static isFoundationSymbolName(t){return t in e.foundationTypeSymbolsByName}static isCustomSymbol(t){return!e.isSwiftSymbol(t)&&!e.isFoundationSymbol(t)}static create(t,r,n){return new e(t,r,n)}static swiftType(t){return e.create(`${e.SWIFT_SYMBOL_ID}.${t}`,t,{type:"system"})}static foundationType(t){return e.create(`${e.FOUNDATION_SYMBOL_ID}.${t}`,t,{type:"system"})}id;name;shape;constructor(t,r,n){this.id=t,this.name=r,this.shape=n}get isSwiftSymbol(){return e.isSwiftSymbol(this.id)}get isFoundationSymbol(){return e.isFoundationSymbol(this.id)}get isCustomSymbol(){return e.isCustomSymbol(this.id)}};St();St();St();var hLn=class{id;name;childrenByName;constructor(t,r){this.id=t,this.name=r,this.childrenByName=new Map}get children(){return Array.from(this.childrenByName.values())}addChild(t){if(this.childrenByName.has(t.name))throw new Error(`A child with the name '${t.name}' already exists in module '${this.name}'.`);this.childrenByName.set(t.name,t)}getChildByName(t){return this.childrenByName.get(t)}},gLn=class extends hLn{kind="module";imports;parent=null;constructor(t,r){super(t,r),this.imports=[]}addImport(t){this.imports.push(t)}get qualifiedPath(){return[this.name]}get qualifiedName(){return this.name}},ALn=class extends hLn{kind="type";shape;parent;constructor(t,r,n){super(r,t),this.parent=null,this.shape=n}getNearestModuleAncestorOrThrow(){let t=this.parent;for(;t!==null&&t.kind!=="module";)t=t.parent;return DP(t,`No module ancestor found for type symbol '${this.id}'`),t}get qualifiedPath(){return[...this.parent?.qualifiedPath??[],this.name]}get qualifiedName(){return this.qualifiedPath.join(".")}};var JLt=class{symbolsById=new Map;createModuleSymbol({symbolId:t,symbolName:r}){this.validateSymbolNotExists(t);let n=new gLn(t,r);return this.symbolsById.set(t,n),n}createTypeSymbol({symbolId:t,symbolName:r,shape:n}){this.validateSymbolNotExists(t);let i=new ALn(r,t,n);return this.symbolsById.set(t,i),i}addImportRelation({clientSymbolId:t,importedSymbolId:r}){let n=this.getSymbolByIdOrThrow(t),i=this.getSymbolByIdOrThrow(r);if(n.kind!=="module"||i.kind!=="module")throw new Error(`Client module '${n.id}' and imported module '${i.id}' must both be module symbols.`);n.addImport(i)}nestSymbol({parentSymbolId:t,childSymbolId:r}){let n=this.getSymbolByIdOrThrow(t),i=this.getSymbolByIdOrThrow(r);n.addChild(i),i.parent=n}reference({fromSymbolId:t,targetSymbolId:r}){let n=this.getSymbolByIdOrThrow(t),i=this.getSymbolByIdOrThrow(r),o=i.qualifiedPath;for(let s=1;s<=o.length;s++){let a=o.slice(o.length-s);if(this.resolvePath(n,a)?.id===i.id)return a.join(".")}return i.qualifiedName}resolveReference({fromSymbolId:t,reference:r}){let n=this.getSymbolByIdOrThrow(t),i=r.split(".").filter(o=>o.length>0);return this.resolvePath(n,i)}resolvePath(t,r){let[n,...i]=r;if(n===void 0)return null;let o=this.resolveFirstSegment(t,n);if(o===null)return null;let s=o;for(let a=0;a<i.length;a++){let u=i[a];if(Yy(u),s=s.getChildByName(u)??null,s===null)return null}return s}resolveFirstSegment(t,r){let n=t;for(;n!==null;){let s=n.getChildByName(r);if(s)return s;n=n.parent}let i=t.kind==="module"?t:t.getNearestModuleAncestorOrThrow();if(i.name===r)return i;for(let s of i.imports)if(s.name===r)return s;let o=null;for(let s of i.imports){let a=s.getChildByName(r);if(a){if(o!=null&&o.id!==a.id)return null;o=a}}return o}getSymbolByIdOrThrow(t){let r=this.symbolsById.get(t);return Yy(r,`A symbol with the ID '${t}' was not found in the registry.`),r}getSymbolById(t){return this.symbolsById.get(t)??null}validateSymbolNotExists(t){if(this.symbolsById.has(t))throw new Error(`A symbol with the ID '${t}' already exists in the registry.`)}};var Ymo=class e{static create(){let{graph:t,swiftSymbol:r,foundationSymbol:n}=e.createGraph();return new e(t,r,n)}static createGraph(){let t=new JLt,r=()=>{let s=t.createModuleSymbol({symbolId:_C.SWIFT_SYMBOL_ID,symbolName:_C.SWIFT_SYMBOL_NAME});return _C.swiftTypeSymbols.forEach(a=>{let u=t.createTypeSymbol({symbolId:a.id,symbolName:a.name,shape:{type:"system"}});t.nestSymbol({parentSymbolId:s.id,childSymbolId:u.id})}),s},n=()=>{let s=t.createModuleSymbol({symbolId:_C.FOUNDATION_SYMBOL_ID,symbolName:_C.FOUNDATION_SYMBOL_NAME});return _C.foundationTypeSymbols.forEach(a=>{let u=t.createTypeSymbol({symbolId:a.id,symbolName:a.name,shape:{type:"system"}});t.nestSymbol({parentSymbolId:s.id,childSymbolId:u.id})}),s},i=r(),o=n();return{graph:t,swiftSymbol:i,foundationSymbol:o}}graph;swiftSymbol;foundationSymbol;registeredSourceModule;registeredTestModule;constructor(t,r,n){this.graph=t,this.swiftSymbol=r,this.foundationSymbol=n,this.registeredSourceModule=null,this.registeredTestModule=null}getRegisteredSourceModuleSymbolOrThrow(){return DP(this.registeredSourceModule,"Module symbol not found."),_C.create(this.registeredSourceModule.id,this.registeredSourceModule.name,{type:"other"})}getRegisteredTestModuleSymbolOrThrow(){return DP(this.registeredTestModule,"Module symbol not found."),_C.create(this.registeredTestModule.id,this.registeredTestModule.name,{type:"other"})}getSymbolByIdOrThrow(t){let r=this.graph.getSymbolById(t);return DP(r,`Symbol with ID '${t}' not found in registry.`),_C.create(r.id,r.name,r.kind==="type"?r.shape:{type:"other"})}registerSourceModule(t){let r=t,n=this.graph.createModuleSymbol({symbolId:r,symbolName:t});return n.addImport(this.swiftSymbol),n.addImport(this.foundationSymbol),this.registeredSourceModule=n,_C.create(n.id,n.name,{type:"other"})}registerTestModule(t){let r=t,n=this.graph.createModuleSymbol({symbolId:r,symbolName:t});return n.addImport(this.swiftSymbol),n.addImport(this.foundationSymbol),DP(this.registeredSourceModule,"Cannot register a test module before registering a source module."),n.addImport(this.registeredSourceModule),this.registeredTestModule=n,_C.create(n.id,n.name,{type:"other"})}registerSourceModuleType(t,r){DP(this.registeredSourceModule,"Cannot register a type before registering a module.");let n=this.inferSymbolIdForSourceModuleType(t),i=this.graph.createTypeSymbol({symbolId:n,symbolName:t,shape:r});return this.graph.nestSymbol({parentSymbolId:this.registeredSourceModule.id,childSymbolId:i.id}),_C.create(i.id,i.name,r)}registerTestModuleType(t,r){DP(this.registeredTestModule,"Cannot register a type before registering a module.");let n=this.inferSymbolIdForTestModuleType(t),i=this.graph.createTypeSymbol({symbolId:n,symbolName:t,shape:r});return this.graph.nestSymbol({parentSymbolId:this.registeredTestModule.id,childSymbolId:i.id}),_C.create(i.id,i.name,r)}registerNestedType({parentSymbol:t,symbolName:r,shape:n}){let i=typeof t=="string"?t:t.id,o=this.inferSymbolIdForNestedType(i,r),s=this.graph.createTypeSymbol({symbolId:o,symbolName:r,shape:n});return this.graph.nestSymbol({parentSymbolId:i,childSymbolId:s.id}),_C.create(s.id,s.name,n)}reference({fromSymbol:t,toSymbol:r}){let n=typeof t=="string"?t:t.id,i=typeof r=="string"?r:r.id;return this.graph.reference({fromSymbolId:n,targetSymbolId:i})}resolveReference({fromSymbol:t,reference:r}){let n=typeof t=="string"?t:t.id,i=this.graph.resolveReference({fromSymbolId:n,reference:r});return i?_C.create(i.id,i.name,i.kind==="type"?i.shape:{type:"other"}):null}inferSymbolIdForSourceModuleType(t){return DP(this.registeredSourceModule,"Cannot get symbol id for a type before registering a module."),`${this.registeredSourceModule.id}.${t}`}inferSymbolIdForTestModuleType(t){return DP(this.registeredTestModule,"Cannot get symbol id for a type before registering a module."),`${this.registeredTestModule.id}.${t}`}inferSymbolIdForNestedType(t,r){return`${t}.${r}`}};St();var mFm={ClientError:{relativePath:"",filenameWithoutExtension:e=>(y6t(e.errorEnumName),e.errorEnumName)},HTTPClient:{relativePath:"Core/Networking",filenameWithoutExtension:()=>"HTTPClient"}};function hFm(e){return new ydt(e)}function gFm(e){return new dS(e)}function AFm(e){return new bdt(e)}function yFm(e){return new Idt(e)}function bFm(e){return new wdt(e)}function EFm(e){return new Cdt(e)}function vFm(e){return new xdt(e)}function IFm(e){return new _dt(e)}function wFm(e){return new Sdt(e)}function CFm(e){return new Bdt(e)}function xFm(e){return new Odt(e)}function _Fm(e){return new Tdt(e)}function SFm(e){return new Pdt(e)}function BFm(e){return new Ddt(e)}Bi();function _Xu(e){return gc(qn(e))}St();var yLn=class{context;constructor({context:t}){this.context=t}convert(t){let{fromSymbol:r,typeReference:n,value:i,as:o}=t;switch(n.type){case"list":return this.convertList({fromSymbol:r,list:n.value,value:i});case"literal":{if(n.value.type==="string")return Br.Expression.enumCaseShorthand(nLe.generateEnumCaseLabel(n.value.value));if(n.value.type==="boolean")return Br.Expression.nop();Be(n.value);break}case"map":return this.convertMap({fromSymbol:r,map:n,value:i});case"named":{let s=this.context.resolveNamedType({typeId:n.value});return s==null?Br.Expression.nop():this.convertNamed({fromSymbol:r,typeId:n.value,named:s,value:i,as:o})}case"nullable":return this.context.customConfig?.nullableAsOptional?this.convert({fromSymbol:r,typeReference:n.value,value:i,as:o}):this.convertNullable({fromSymbol:r,nullable:n,value:i,as:o});case"optional":return this.convert({fromSymbol:r,typeReference:n.value,value:i,as:o});case"primitive":return this.convertPrimitive({primitive:n.value,value:i,as:o});case"set":return Br.Expression.nop();case"unknown":return this.convertUnknown(i);default:Be(n)}}convertList({fromSymbol:t,list:r,value:n}){return Array.isArray(n)?Br.Expression.arrayLiteral({elements:n.map((i,o)=>{this.context.errors.scope({index:o});try{return this.convert({fromSymbol:t,typeReference:r,value:i})}finally{this.context.errors.unscope()}}),multiline:!0}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof n}`}),Br.Expression.nop())}convertMap({fromSymbol:t,map:r,value:n}){return typeof n!="object"||n==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${n==null?"null":typeof n}`}),Br.Expression.nop()):Br.Expression.dictionaryLiteral({entries:Object.entries(n).map(([i,o])=>{this.context.errors.scope(i);try{return[this.convert({fromSymbol:t,typeReference:r.key,value:i,as:"mapKey"}),this.convert({fromSymbol:t,typeReference:r.value,value:o,as:"mapValue"})]}finally{this.context.errors.unscope()}}),multiline:!0})}convertNamed({fromSymbol:t,typeId:r,named:n,value:i,as:o}){switch(n.type){case"alias":return this.convert({fromSymbol:t,typeReference:n.typeReference,value:i,as:o});case"discriminatedUnion":{let s=this.context.nameRegistry.getSchemaTypeSymbolOrThrow(r);return this.convertDiscriminatedUnion({fromSymbol:t,unionSymbol:s,discriminatedUnion:n,value:i})}case"enum":return this.convertEnum({enum_:n,value:i});case"object":return this.convertObject({fromSymbol:t,typeId:r,object_:n,value:i});case"undiscriminatedUnion":{let s=this.context.nameRegistry.getSchemaTypeSymbolOrThrow(r);return this.convertUndiscriminatedUnion({fromSymbol:t,unionSymbol:s,undiscriminatedUnion:n,value:i})}default:Be(n)}}convertNullable({fromSymbol:t,nullable:r,value:n,as:i}){return n==null?Br.Expression.enumCaseShorthand("null"):Br.Expression.contextualMethodCall({methodName:"value",arguments_:[Br.functionArgument({value:this.convert({fromSymbol:t,typeReference:r.value,value:n,as:i})})]})}convertDiscriminatedUnion({fromSymbol:t,discriminatedUnion:r,unionSymbol:n,value:i}){let o=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:r,value:i});if(o==null)return Br.Expression.nop();let s=o.singleDiscriminatedUnionType,a=oLn.sanitizeToCamelCase(s.discriminantValue.name.camelCase.unsafeName);switch(s.type){case"samePropertiesAsObject":{let u=this.context.resolveNamedType({typeId:s.typeId});if(u==null)return Br.Expression.nop();let c=this.convertNamed({fromSymbol:t,typeId:s.typeId,named:u,value:o.value});return Br.Expression.methodCall({target:Br.Expression.reference(n.name),methodName:a,arguments_:[Br.functionArgument({value:c})],multiline:!0})}case"singleProperty":try{this.context.errors.scope(s.discriminantValue.wireValue);let u=this.context.getRecord(o.value);if(u==null)return Br.Expression.nop();let c=this.convert({fromSymbol:t,typeReference:s.typeReference,value:u[s.discriminantValue.wireValue]});return Br.Expression.methodCall({target:Br.Expression.reference(n.name),methodName:a,arguments_:[Br.functionArgument({value:c})],multiline:!0})}finally{this.context.errors.unscope()}case"noProperties":return Br.Expression.memberAccess({target:Br.Expression.reference(n.name),memberName:a});default:Be(s)}}convertEnum({enum_:t,value:r}){let n=this.getEnumValue({enum_:t,value:r});return n==null?Br.Expression.nop():Br.Expression.enumCaseShorthand(n.name.camelCase.unsafeName)}getEnumValue({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Ir.Critical,message:`Expected enum value string, got: ${typeof r}`});return}let n=t.values.find(i=>i.wireValue===r);if(n==null){this.context.errors.add({severity:Ir.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return n}convertObject({fromSymbol:t,typeId:r,object_:n,value:i}){let o=this.context.nameRegistry.getSchemaTypeSymbolOrThrow(r);return Br.Expression.structInitialization({unsafeName:o.name,arguments_:this.context.getExampleObjectProperties({parameters:n.properties,snippetObject:i}).map(s=>this.convert({fromSymbol:t,typeReference:s.typeReference,value:s.value}).isNop()?null:Br.functionArgument({label:Edt(s.name.name.camelCase.unsafeName),value:this.convert({fromSymbol:t,typeReference:s.typeReference,value:s.value})})).filter(s=>s!=null),multiline:!0})}convertUndiscriminatedUnion({fromSymbol:t,unionSymbol:r,undiscriminatedUnion:n,value:i}){let o=this.findMatchingUndiscriminatedUnionType({fromSymbol:t,unionSymbol:r,undiscriminatedUnion:n,value:i});return o??Br.Expression.nop()}findMatchingUndiscriminatedUnionType({fromSymbol:t,unionSymbol:r,undiscriminatedUnion:n,value:i}){let o=this.context.nameRegistry.getAllUndiscriminatedUnionVariantsOrThrow(r);for(let s of n.types){let a=this.context.errors.size();try{let u=this.convert({fromSymbol:t,typeReference:s,value:i}),c=this.context.getSwiftTypeReferenceFromScope(s,t),l=o.find(p=>p.swiftType.equals(c));if(l==null){this.context.errors.truncate(a);continue}return Br.Expression.methodCall({target:Br.Expression.reference(r.name),methodName:l.caseName,arguments_:[Br.functionArgument({value:u})],multiline:!0})}catch{this.context.errors.truncate(a);continue}}this.context.errors.add({severity:Ir.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof i}" value`})}convertUnknown(t){switch(typeof t){case"boolean":return Br.Expression.contextualMethodCall({methodName:"bool",arguments_:[Br.functionArgument({value:Br.Expression.boolLiteral(t)})]});case"string":return Br.Expression.contextualMethodCall({methodName:"string",arguments_:[Br.functionArgument({value:Br.Expression.stringLiteral(t)})]});case"number":return Br.Expression.contextualMethodCall({methodName:"number",arguments_:[Br.functionArgument({value:Br.Expression.numberLiteral(t)})]});case"object":return t===null?Br.Expression.enumCaseShorthand("null"):Array.isArray(t)?Br.Expression.contextualMethodCall({methodName:"array",arguments_:[Br.functionArgument({value:Br.Expression.arrayLiteral({elements:t.map(r=>this.convertUnknown(r)),multiline:!0})})]}):Br.Expression.contextualMethodCall({methodName:"object",arguments_:[Br.functionArgument({value:Br.Expression.dictionaryLiteral({entries:Object.entries(t).map(([r,n])=>[Br.Expression.stringLiteral(r),this.convertUnknown(n)]),multiline:!0})})]});default:throw new Error(`Internal error; unsupported unknown type: ${typeof t}`)}}convertPrimitive({primitive:t,value:r,as:n}){switch(t){case"INTEGER":case"UINT":case"LONG":case"UINT_64":case"FLOAT":case"DOUBLE":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Br.Expression.nop():Br.Expression.numberLiteral(i)}case"BOOLEAN":{let i=this.getValueAsBoolean({value:r,as:n});return i==null?Br.Expression.nop():Br.Expression.boolLiteral(i)}case"STRING":{let i=this.context.getValueAsString({value:r});return i==null?Br.Expression.nop():Br.Expression.stringLiteral(i)}case"DATE":{let i=this.context.getValueAsString({value:r});return i==null?Br.Expression.nop():Br.Expression.calendarDateLiteral(i)}case"DATE_TIME":{let i=this.context.getValueAsString({value:r});if(i==null)return Br.Expression.nop();let o=new Date(i).getTime(),s=Math.round(o/1e3),u=new Date(s*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return Br.Expression.dateLiteral(u)}case"UUID":{let i=this.context.getValueAsString({value:r});return i==null?Br.Expression.nop():Br.Expression.uuidLiteral(i)}case"BASE_64":{let i=this.context.getValueAsString({value:r});return i==null?Br.Expression.nop():Br.Expression.stringLiteral(i)}case"BIG_INTEGER":return this.context.getValueAsString({value:r})==null?Br.Expression.nop():Br.Expression.nop();default:Be(t)}}getValueAsNumber({value:t,as:r}){let n=r==="mapKey"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=(()=>{switch(r){case"mapKey":return t==="true"?!0:t==="false"?!1:t;case"mapValue":case void 0:return t;default:Be(r)}})();return this.context.getValueAsBoolean({value:n})}};St();var bLn=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({fromSymbol:t,body:r,value:n}){let i={fileFields:[],bodyPropertyFields:[]},o=this.context.getRecord(n)??{};for(let s of r.properties)switch(s.type){case"file":{let a=Br.functionArgument({label:Edt(s.name.camelCase.unsafeName),value:this.getSingleFileProperty({property:s,record:o})});i.fileFields.push(a);break}case"fileArray":{let a=Br.functionArgument({label:Edt(s.name.camelCase.unsafeName),value:this.getArrayFileProperty({property:s,record:o})});i.fileFields.push(a);break}case"bodyProperty":{let a=Br.functionArgument({label:Edt(s.name.name.camelCase.unsafeName),value:this.getBodyProperty({fromSymbol:t,property:s,record:o})});i.bodyPropertyFields.push(a);break}default:Be(s)}return i}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r});return Br.Expression.contextualMethodCall({methodName:"init",arguments_:[Br.functionArgument({label:"data",value:Br.Expression.dataLiteral(n??"")})]})}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});return Br.Expression.arrayLiteral({elements:(n??[]).map(i=>Br.Expression.contextualMethodCall({methodName:"init",arguments_:[Br.functionArgument({label:"data",value:Br.Expression.dataLiteral(i)})]})),multiline:!0})}getBodyProperty({fromSymbol:t,property:r,record:n}){let i=n[r.name.wireValue];return i==null?Br.Expression.nop():this.context.dynamicTypeLiteralMapper.convert({fromSymbol:t,typeReference:r.typeReference,value:i})}};St();function SXu({parentSymbol:e,registry:t,namedType:r,context:n}){zw(r,"type")._visit({object:i=>{Xmo({parentSymbol:e,registry:t,properties:i.properties})},discriminatedUnion:i=>{Object.values(i.types).forEach(o=>{zw(o,"type")._visit({noProperties:ft,samePropertiesAsObject:ft,singleProperty:s=>{Ife({parentSymbol:e,registry:t,typeReference:s.typeReference})},_other:ft})})},undiscriminatedUnion:i=>{i.types.forEach(o=>{Ife({parentSymbol:e,registry:t,typeReference:o})})},alias:ft,enum:ft,_other:ft})}function Xmo({parentSymbol:e,registry:t,properties:r}){r.forEach(n=>{Ife({parentSymbol:e,registry:t,typeReference:n.typeReference})})}function Ife({parentSymbol:e,registry:t,typeReference:r}){zw(r,"type")._visit({list:n=>{Ife({parentSymbol:e,registry:t,typeReference:n.value})},literal:n=>{zw(n.value,"type")._visit({string:i=>{t.registerNestedLiteralEnumSymbol({parentSymbol:e,literalValue:i.value})},boolean:ft,_other:ft})},map:n=>{Ife({parentSymbol:e,registry:t,typeReference:n.key}),Ife({parentSymbol:e,registry:t,typeReference:n.value})},named:ft,nullable:n=>{Ife({parentSymbol:e,registry:t,typeReference:n.value})},optional:n=>{Ife({parentSymbol:e,registry:t,typeReference:n.value})},primitive:ft,set:n=>{Ife({parentSymbol:e,registry:t,typeReference:n.value})},unknown:ft,_other:ft})}function BXu({parentSymbol:e,registry:t,namedType:r,context:n}){if(r.type==="undiscriminatedUnion"){let i=r.types.map(o=>{let s=n.getSwiftTypeReferenceFromScope(o,e);return{swiftType:s,caseName:aLn.inferCaseNameForTypeReference(e,s,t),docsContent:void 0}});t.registerUndiscriminatedUnionVariants({parentSymbol:e,variants:i})}}var ELn=class e extends $v{ir;customConfig;dynamicTypeLiteralMapper;filePropertyMapper;nameRegistry;constructor({ir:t,config:r,options:n}){super({ir:t,config:r,options:n}),this.ir=t,this.customConfig=r.customConfig!=null?r.customConfig:void 0,this.dynamicTypeLiteralMapper=new yLn({context:this}),this.filePropertyMapper=new bLn({context:this}),this.nameRegistry=pLn.create(),this.registerSourceSymbols(this.nameRegistry,t)}registerSourceSymbols(t,r){let n=_Xu(this.config.workspaceName),i=t.registerSourceModuleSymbol({configModuleName:this.customConfig?.moduleName,apiNamePascalCase:n,asIsSymbols:Object.values(Br.SourceAsIsFileSpecs).flatMap(s=>s.symbols)});return t.registerRootClientSymbol({configClientClassName:this.customConfig?.clientClassName,registeredSourceModuleName:i.name}),Xy(Br.SourceTemplateFileSpecs).forEach(([s])=>{switch(s){case"ClientError":t.registerErrorEnumSymbol(i.name);break;case"HTTPClient":t.registerSourceStaticSymbol(s,{type:"class"});break;default:Be(s)}}),t.registerEnvironmentSymbol({configEnvironmentEnumName:this.customConfig?.environmentEnumName,registeredSourceModuleName:i.name}),Object.entries(r.types).map(([s,a])=>{let u=zw(a,"type")._visit({alias:()=>({type:"struct"}),enum:()=>({type:"enum-with-raw-values"}),object:()=>({type:"struct"}),discriminatedUnion:()=>({type:"enum-with-associated-values"}),undiscriminatedUnion:()=>({type:"enum-with-associated-values"}),_other:()=>({type:"other"})}),c=t.registerSchemaTypeSymbol(s,a.declaration.name.pascalCase.unsafeName,u);return{namedType:a,registeredSymbol:c}}).forEach(({namedType:s,registeredSymbol:a})=>{SXu({parentSymbol:a,registry:t,namedType:s,context:this}),BXu({parentSymbol:a,registry:t,namedType:s,context:this})}),t.registerRequestsContainerSymbol(),Object.entries(r.endpoints).forEach(([s,a])=>{if(a.request.type==="inlined"){if(a.request.body?.type==="properties"){let u=t.registerRequestTypeSymbol({endpointId:s,requestNamePascalCase:a.request.declaration.name.pascalCase.unsafeName});Xmo({parentSymbol:u,registry:t,properties:a.request.body.value})}a.request.body?.type==="fileUpload"&&t.registerRequestTypeSymbol({endpointId:s,requestNamePascalCase:a.request.declaration.name.pascalCase.unsafeName})}}),t}getNamedTypeOrThrow(t){let r=this.ir.types[t];return Yy(r,`Type declaration with the id '${t}' not found`),r}getPropertiesOfDiscriminatedUnionVariant(t){let r=this.getNamedTypeOrThrow(t);return zw(r,"type")._visit({alias:()=>[],enum:()=>[],object:n=>n.properties,discriminatedUnion:()=>[],undiscriminatedUnion:()=>[],_other:()=>[]})}getSwiftTypeReferenceFromScope(t,r){let n=this.createReferencer(r);return zw(t,"type")._visit({list:i=>Br.TypeReference.array(this.getSwiftTypeReferenceFromScope(i.value,r)),literal:i=>zw(i.value,"type")._visit({boolean:()=>n.referenceAsIsType("JSONValue"),string:o=>{let s=this.nameRegistry.getNestedLiteralEnumSymbolOrThrow(r,o.value);return n.referenceType(s)},_other:()=>n.referenceAsIsType("JSONValue")}),map:i=>Br.TypeReference.dictionary(this.getSwiftTypeReferenceFromScope(i.key,r),this.getSwiftTypeReferenceFromScope(i.value,r)),named:i=>{let o=this.nameRegistry.getSchemaTypeSymbolOrThrow(i.value),s=this.nameRegistry.reference({fromSymbol:r,toSymbol:o});return Br.TypeReference.symbol(s)},nullable:i=>this.customConfig?.nullableAsOptional?Br.TypeReference.optional(this.getSwiftTypeReferenceFromScope(i.value,r)):Br.TypeReference.nullable(this.getSwiftTypeReferenceFromScope(i.value,r)),optional:i=>Br.TypeReference.optional(this.getSwiftTypeReferenceFromScope(i.value,r)),primitive:i=>zw(i,"value")._visit({STRING:()=>n.referenceSwiftType("String"),BOOLEAN:()=>n.referenceSwiftType("Bool"),INTEGER:()=>n.referenceSwiftType("Int"),UINT:()=>n.referenceSwiftType("UInt"),UINT_64:()=>n.referenceSwiftType("UInt64"),LONG:()=>n.referenceSwiftType("Int64"),FLOAT:()=>n.referenceSwiftType("Float"),DOUBLE:()=>n.referenceSwiftType("Double"),BIG_INTEGER:()=>n.referenceSwiftType("String"),DATE:()=>n.referenceAsIsType("CalendarDate"),DATE_TIME:()=>n.referenceFoundationType("Date"),BASE_64:()=>n.referenceSwiftType("String"),UUID:()=>n.referenceFoundationType("UUID"),_other:()=>n.referenceAsIsType("JSONValue")}),set:()=>n.referenceAsIsType("JSONValue"),unknown:()=>n.referenceAsIsType("JSONValue"),_other:()=>n.referenceAsIsType("JSONValue")})}createReferencer(t){return new sLn(this.nameRegistry,t)}clone(){return new e({ir:this.ir,config:this.config,options:this.options})}};St();var OXu="client",vLn=class{context;constructor({context:t}){this.context=t}async generateSnippet({endpoint:t,request:r,options:n}){return this.buildCodeBlock({endpoint:t,snippetRequest:r,options:n})}generateSnippetSync({endpoint:t,request:r,options:n}){return this.buildCodeBlock({endpoint:t,snippetRequest:r,options:n})}async generateSnippetAst({endpoint:t,request:r,options:n}){throw new Error("Unsupported")}buildCodeBlock({endpoint:t,snippetRequest:r,options:n}){return[this.generateImportFoundationStatement(),this.generateImportModuleStatement(),Br.LineBreak.single(),this.generateMainFunctionDeclarationWithEndpointSnippet({endpoint:t,snippet:r}),Br.LineBreak.single(),this.generateMainFunctionInvocationStatement()].map(o=>o.toString()).join("")}generateImportFoundationStatement(){return Br.Statement.import("Foundation")}generateImportModuleStatement(){let t=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();return Br.Statement.import(t.name)}generateMainFunctionDeclarationWithEndpointSnippet({endpoint:t,snippet:r}){return Br.Statement.functionDeclaration({unsafeName:"main",accessLevel:"private",async:!0,throws:!0,body:Br.CodeBlock.withStatements([this.generateRootClientInitializationStatement({auth:t.auth,snippet:r}),Br.LineBreak.single(),this.generateEndpointMethodCallStatement({endpoint:t,snippet:r})])})}generateRootClientInitializationStatement({auth:t,snippet:r,additionalArgs:n=[]}){let i=[],o=this.getRootClientBaseURLArg({snippet:r});o!=null&&i.push(o);let s=t?this.getRootClientAuthArgs({auth:t,snippet:r}):[];i.push(...s),this.context.ir.headers!=null&&r.headers!=null&&i.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:r.headers})),i.push(...n);let a=i.filter(c=>!c.value.isNop()),u=this.context.nameRegistry.getRootClientSymbolOrThrow();return Br.Statement.constantDeclaration({unsafeName:OXu,value:Br.Expression.classInitialization({unsafeName:u.name,arguments_:a,multiline:a.length>1?!0:void 0})})}getRootClientHeaderArgs({headers:t,values:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow(),i=[];for(let o of t){let s=r[o.name.wireValue],a=this.getRootClientHeaderArg({moduleSymbol:n,header:o,value:s});a!=null&&i.push(a)}return i}getRootClientHeaderArg({moduleSymbol:t,header:r,value:n}){if(r.typeReference.type==="literal")return;let i=this.context.dynamicTypeLiteralMapper.convert({fromSymbol:t,typeReference:r.typeReference,value:n});if(!i.isNop())return Br.functionArgument({label:r.name.name.camelCase.unsafeName,value:i})}getRootClientBaseURLArg({snippet:t}){return t.baseURL!=null&&t.environment!=null?(this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"}),null):t.baseURL!=null?this.context.ir.environments?.environments.type==="multipleBaseUrls"?null:Br.functionArgument({label:"baseURL",value:Br.Expression.stringLiteral(t.baseURL)}):null}getRootClientAuthArgs({auth:t,snippet:r}){let n=[],i=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow(),o=r.auth;if(o==null)return n;switch(t.type){case"basic":if(o.type!=="basic"){this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:o}).message});break}n.push(Br.functionArgument({label:t.username.camelCase.unsafeName,value:Br.Expression.stringLiteral(o.username)}),Br.functionArgument({label:t.password.camelCase.unsafeName,value:Br.Expression.stringLiteral(o.password)}));break;case"bearer":if(o.type!=="bearer")return this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:o}).message}),n;n.push(Br.functionArgument({label:t.token.camelCase.unsafeName,value:Br.Expression.stringLiteral(o.token)}));break;case"header":if(o.type!=="header")return this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:o}).message}),n;n.push(Br.functionArgument({label:t.header.name.name.camelCase.unsafeName,value:this.context.dynamicTypeLiteralMapper.convert({fromSymbol:i,typeReference:t.header.typeReference,value:o.value})}));break;case"oauth":return o.type!=="oauth"&&this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:o}).message}),n;case"inferred":return o.type!=="inferred"&&this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:o}).message}),n;default:Be(t)}return n}generateEndpointMethodCallStatement({endpoint:t,snippet:r}){return Br.Statement.discardAssignment(this.generateEndpointMethodCallExpression({endpoint:t,snippet:r}))}generateEndpointMethodCallExpression({endpoint:t,snippet:r,additionalArguments:n=[]}){let o=[...this.getEndpointMethodArguments({endpoint:t,snippet:r}).filter(s=>!s.value.isNop()),...n];return Br.Expression.try(Br.Expression.await(Br.Expression.methodCall({target:Br.Expression.rawValue(OXu),methodName:this.getEndpointMethodName({endpoint:t}),arguments_:o,multiline:o.length>1?!0:void 0})))}generateMainFunctionInvocationStatement(){return Br.Statement.expressionStatement(Br.Expression.try(Br.Expression.await(Br.Expression.functionCall({unsafeName:"main"}))))}getEndpointMethodName({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${`${t.declaration.fernFilepath.allParts.map(n=>n.camelCase.unsafeName).join(".")}`}.${t.declaration.name.camelCase.unsafeName}`:t.declaration.name.camelCase.unsafeName}getEndpointMethodArguments({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getEndpointMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getEndpointMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getEndpointMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[];t.pathParameters!=null&&i.push(...this.getEndpointMethodPathParameters({namedParameters:t.pathParameters,snippet:r})),this.context.errors.unscope(),n.push(...i),this.context.errors.scope(Lo.QueryParameters);let o=[];t.queryParameters!=null&&o.push(...this.getEndpointMethodQueryParameters({namedParameters:t.queryParameters,snippet:r})),this.context.errors.unscope(),n.push(...o),this.context.errors.scope(Lo.RequestBody);let s=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),t.body!=null&&n.push(Br.functionArgument({label:"request",value:this.getInlinedRequestArg({request:t,snippet:r,filePropertyInfo:s})})),n}getEndpointMethodPathParameters({namedParameters:t,snippet:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();return this.context.getExampleObjectProperties({parameters:t,snippetObject:r.pathParameters??{}}).map(i=>Br.functionArgument({label:i.name.name.camelCase.unsafeName,value:this.context.dynamicTypeLiteralMapper.convert({fromSymbol:n,typeReference:i.typeReference,value:i.value})}))}getEndpointMethodQueryParameters({namedParameters:t,snippet:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();return this.context.getExampleObjectProperties({parameters:t,snippetObject:r.queryParameters??{}}).map(i=>Br.functionArgument({label:i.name.name.camelCase.unsafeName,value:this.context.dynamicTypeLiteralMapper.convert({fromSymbol:n,typeReference:i.typeReference,value:i.value})}))}getFilePropertyInfo({request:t,snippet:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({fromSymbol:n,body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,filePropertyInfo:n}){this.context.errors.scope(Lo.RequestBody);let i=t.body!=null?this.getInlinedRequestBodyObjectFields({body:t.body,value:r.requestBody,filePropertyInfo:n}):[];this.context.errors.unscope();let o=i.filter(s=>!s.value.isNop());return Br.Expression.contextualMethodCall({methodName:"init",arguments_:o,multiline:o.length>1?!0:void 0})}getInlinedRequestBodyObjectFields({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"fileUpload":return[...n.fileFields,...n.bodyPropertyFields];case"properties":return this.getInlinedRequestBodyPropertyObjectFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyObjectField({body:t,value:r})];default:Be(t)}}getInlinedRequestBodyPropertyObjectFields({parameters:t,value:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();return this.context.getExampleObjectProperties({parameters:t,snippetObject:r}).map(i=>Br.functionArgument({label:i.name.name.camelCase.unsafeName,value:this.context.dynamicTypeLiteralMapper.convert({fromSymbol:n,typeReference:i.typeReference,value:i.value})}))}getReferencedRequestBodyPropertyObjectField({body:t,value:r}){return Br.functionArgument({label:t.bodyKey.camelCase.unsafeName,value:this.getReferencedRequestBodyPropertyTypeLiteral({body:t.bodyType,value:r})})}getReferencedRequestBodyPropertyTypeLiteral({body:t,value:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({fromSymbol:n,typeReference:t.value,value:r});default:Be(t)}}getBytesBodyRequestArg({value:t}){return typeof t!="string"?(this.context.errors.add({severity:Ir.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),Br.Expression.dataLiteral("data")):Br.Expression.dataLiteral(t)}getEndpointMethodArgsForBodyRequest({request:t,snippet:r}){let n=[],i=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();this.context.errors.scope(Lo.PathParameters);let o=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];return o.length>0&&n.push(...this.getEndpointMethodPathParameters({namedParameters:o,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),t.body!=null&&n.push(this.getEndpointMethodBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope(),n}getEndpointMethodBodyRequestArg({body:t,value:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();switch(t.type){case"bytes":return Br.functionArgument({label:"request",value:this.getBytesBodyRequestArg({value:r})});case"typeReference":return Br.functionArgument({label:"request",value:this.context.dynamicTypeLiteralMapper.convert({fromSymbol:n,typeReference:t.value,value:r})});default:Be(t)}}};var YLt=class extends Wv{constructor({ir:t,config:r,options:n={}}){super(new ELn({ir:t,config:r,options:n}))}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new vLn({context:t})}};var ILn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new YLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");let n=await this.initializeProject(t);for(let[i,o]of r.entries())try{let s=pS(o);if(s==null)continue;let a=await this.dynamicSnippetsGenerator.generate(s,{config:{},style:CC.Full}),u=this.getTestFilePath({absolutePathToOutputDir:n,idx:i});await(0,XLt.mkdir)(TXu.default.dirname(u),{recursive:!0}),await(0,XLt.writeFile)(u,a.snippet)}catch(s){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(o.endpoint)}: ${s}`)}this.context.logger.debug("Done generating dynamic snippet tests")}async initializeProject(t){let r=Ge(t,Se.of("Snippets"));return await(0,XLt.mkdir)(r,{recursive:!0}),r}getTestFilePath({absolutePathToOutputDir:t,idx:r}){return Ge(t,Se.of(`Example${r}.swift`))}};qt();var Rdt=class extends wC{customConfig;formatter;imports={};defaultImports={};starImportAliases={};starImportAliasesInverse={};constructor({customConfig:t,formatter:r}){super(),this.customConfig=t,this.formatter=r??new B7}addImport(t){if(t.importFrom!=null){switch(t.importFrom.type){case"default":{this.validateDefault(t);break}case"named":{this.validateNamed(t);break}case"star":{this.validateStar(t);break}}let r=this.imports[t.importFrom.moduleName]??=[];r.map(i=>i.name).includes(t.name)||r.push(t)}}validateDefault(t){if(t.importFrom?.type!=="default")return;let r=this.defaultImports[t.importFrom.moduleName]??=t;if(r.name!==t.name)throw new Error(`Cannot have multiple default imports for module ${t.importFrom.moduleName}: got ${t.name} but already had ${r.name}`)}validateNamed(t){if(t.importFrom?.type!=="named")return;let n=(this.imports[t.importFrom.moduleName]??[]).filter(o=>o.importFrom?.type==="star");if(n.length>0)throw new Error(`Cannot add named import ${t.name} because non-named imports ${n.map(o=>o.name)} already exist`);let i=[];for(let o of Object.values(this.imports))for(let s of o)s.importFrom?.type==="named"&&s.importFrom.moduleName!==t.importFrom.moduleName&&s.name===t.name&&i.push(s);if(i.length>0)throw new Error(`Cannot add named import from module ${t.importFrom.moduleName} because it is already imported from ${i[0]?.importFrom?.moduleName}`)}validateStar(t){if(t.importFrom?.type!=="star")return;let r=this.starImportAliases[t.importFrom.moduleName]??=t.importFrom.starImportAlias;if(r!==t.importFrom.starImportAlias)throw new Error(`Cannot have more than one alias for non-named imports from a module: got ${t.importFrom.starImportAlias} but already have ${r}.`);if((this.starImportAliasesInverse[t.importFrom.starImportAlias]??=t.importFrom.moduleName)!==t.importFrom.moduleName)throw new Error(`Attempted to use alias ${t.importFrom.starImportAlias} for more than one module in the same file`)}};var ZLt=class extends Rdt{constructor({customConfig:t,formatter:r}){super({customConfig:t,formatter:r})}async toStringAsync(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.format(t)}catch(r){throw new Error(`Failed to format TypeScript file: ${r}
2579
+ `),t=t.replace(/\x00/g,""),t}};var Cdt=class extends ep{name;accessLevel;indirect;conformances;cases;initializers;methods;nestedTypes;docs;constructor({accessLevel:t,indirect:r,name:n,conformances:i,cases:o,initializers:s,methods:a,nestedTypes:u,docs:c}){super(),this.name=n,this.indirect=r??!1,this.accessLevel=t,this.conformances=i??[],this.cases=o,this.initializers=s??[],this.methods=a??[],this.nestedTypes=u??[],this.docs=c}write(t){this.docs!=null&&this.docs.write(t),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),this.indirect&&t.write("indirect "),t.write(`enum ${this.name}`),this.conformances.forEach((r,n)=>{n===0?t.write(": "):n>0&&t.write(", "),t.write(r)}),t.write(" {"),t.newLine(),t.indent(),this.cases.forEach(r=>{r.docs!=null&&r.docs.write(t),t.write("case "),iLe(r.unsafeName)?t.write(`\`${r.unsafeName}\``):t.write(r.unsafeName),r.associatedValue!=null&&(t.write("("),r.associatedValue.forEach((n,i)=>{i>0&&t.write(", "),n.write(t)}),t.write(")")),t.newLine()}),this.initializers.length>0&&(t.newLine(),this.initializers.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()})),this.methods.length>0&&(t.newLine(),this.methods.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()})),this.nestedTypes.length>0&&(t.newLine(),this.nestedTypes.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()})),t.dedent(),t.write("}")}};var xdt=class extends ep{name;accessLevel;conformances;cases;docs;constructor({accessLevel:t,name:r,conformances:n,cases:i,docs:o}){super(),this.name=r,this.accessLevel=t,this.conformances=n??[],this.cases=i,this.docs=o}write(t){if(this.docs!=null&&this.docs.write(t),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),t.write(`enum ${this.name}`),this.conformances.forEach((r,n)=>{n===0?t.write(": "):n>0&&t.write(", "),t.write(r)}),this.cases.length===0){t.write(" {}");return}t.write(" {"),t.newLine(),t.indent(),this.cases.forEach(r=>{r.docs!=null&&r.docs.write(t),t.write("case "),iLe(r.unsafeName)?t.write(`\`${r.unsafeName}\``):t.write(r.unsafeName),r.rawValue!==r.unsafeName&&(t.write(" = "),t.write(`"${CXu(r.rawValue)}"`)),t.newLine()}),t.dedent(),t.write("}")}};var _dt=class extends ep{name;conformances;initializers;computedProperties;methods;nestedTypes;docs;constructor({name:t,conformances:r,initializers:n,computedProperties:i,methods:o,nestedTypes:s,docs:a}){super(),this.name=t,this.conformances=r??[],this.initializers=n??[],this.computedProperties=i??[],this.methods=o??[],this.nestedTypes=s??[],this.docs=a}write(t){this.docs!=null&&this.docs.write(t),t.write(`extension ${this.name}`),this.conformances.forEach((r,n)=>{n===0?t.write(": "):n>0&&t.write(", "),t.write(r)}),t.write(" {"),this.initializers.length>0&&(t.newLine(),t.indent(),this.initializers.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()}),t.dedent()),this.computedProperties.length>0&&(t.newLine(),t.indent(),this.computedProperties.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()}),t.dedent()),this.methods.length>0&&(t.newLine(),t.indent(),this.methods.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()}),t.dedent()),this.nestedTypes.length>0&&(t.newLine(),t.indent(),this.nestedTypes.forEach((r,n)=>{n>0&&t.newLine(),r.write(t),t.newLine()}),t.dedent()),t.write("}")}};var Sdt=class extends ep{label;value;constructor({label:t,value:r}){super(),this.label=t,this.value=r}write(t){this.label!=null&&(t.write(this.label),t.write(": ")),this.value.write(t)}};var Bdt=class extends ep{argumentLabel;unsafeName;escaping;type;defaultValue;docsContent;constructor({argumentLabel:t,unsafeName:r,escaping:n,type:i,defaultValue:o,docsContent:s}){super(),this.argumentLabel=t,this.unsafeName=r,this.escaping=n,this.type=i,this.defaultValue=o,this.docsContent=s}write(t){this.argumentLabel==null?t.write("_ "):this.argumentLabel!==this.unsafeName&&(t.write(this.argumentLabel),t.write(" ")),t.write(this.unsafeName),t.write(": "),this.escaping&&t.write("@escaping "),this.type.write(t),this.defaultValue!=null&&(t.write(" = "),this.defaultValue.write(t))}};var Odt=class extends ep{accessLevel;convenience;failable;throws;parameters;body;multiline;docs;constructor({accessLevel:t,convenience:r,failable:n,throws:i,parameters:o,body:s,multiline:a,docs:u}){super(),this.accessLevel=t,this.convenience=r,this.failable=n,this.throws=i,this.parameters=o??[],this.body=s??dS.empty(),this.multiline=a,this.docs=u}write(t){this.docs!=null&&this.docs.write(t),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),this.convenience&&t.write("convenience "),t.write("init"),this.failable&&t.write("?"),t.write("("),this.multiline&&(t.newLine(),t.indent()),this.parameters.forEach((r,n)=>{n>0&&(t.write(","),this.multiline?t.newLine():t.write(" ")),r.write(t)}),this.multiline&&(t.newLine(),t.dedent()),t.write(") "),this.throws&&t.write("throws "),this.body.write(t)}};var fLn=class e extends ep{count;constructor({count:t=1}={}){super(),this.count=t}write(t){for(let r=0;r<this.count;r++)t.newLine()}static single(){return new e({count:1})}static double(){return new e({count:2})}static multiple(t){return new e({count:t})}};var Tdt=class extends ep{attributes;unsafeName;accessLevel;static_;parameters;async;throws;returnType;body;docs;constructor({attributes:t,unsafeName:r,accessLevel:n,static_:i,parameters:o,async:s,throws:a,returnType:u,body:c,docs:l}){super(),this.attributes=t??[],this.unsafeName=r,this.accessLevel=n,this.static_=i,this.parameters=o??[],this.async=s,this.throws=a,this.returnType=u,this.body=c??dS.empty(),this.docs=l}write(t){this.docs!=null&&this.docs.write(t),this.attributes.forEach(r=>{r.arguments?.length?kne.functionCall({unsafeName:`@${r.name}`,arguments_:r.arguments}).write(t):(t.write("@"),t.write(r.name)),t.write(" ")}),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),this.static_&&t.write("static "),t.write("func "),t.write(vQ(this.unsafeName)),t.write("("),this.parameters.forEach((r,n)=>{n>0&&t.write(", "),r.write(t)}),t.write(")"),this.async&&t.write(" async"),this.throws&&t.write(" throws"),t.write(" -> "),this.returnType.write(t),t.write(" "),this.body.write(t)}};St();var dLn=class extends ep{internalPattern;constructor(t){super(),this.internalPattern=t}write(t){this.internalPattern.type==="enum-case-value-binding"?(t.write("."),t.write(this.internalPattern.caseName),t.write("("),t.write(this.internalPattern.declarationType),t.write(" "),t.write(this.internalPattern.referenceName),t.write(")")):Be(this.internalPattern.type)}static enumCaseValueBinding(t){return new this({type:"enum-case-value-binding",...t})}};var Pdt=class extends ep{unsafeName;accessLevel;static_;declarationType;type;indirect;defaultValue;docs;constructor({unsafeName:t,accessLevel:r,static_:n,declarationType:i,type:o,indirect:s,defaultValue:a,docs:u}){super(),this.unsafeName=t,this.accessLevel=r,this.static_=n,this.declarationType=i,this.type=o,this.indirect=s,this.defaultValue=a,this.docs=u}write(t){this.docs!=null&&this.docs.write(t),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),this.static_&&t.write("static "),t.write(this.declarationType),t.write(" "),iLe(this.unsafeName)?t.write(`\`${this.unsafeName}\``):t.write(this.unsafeName),t.write(": "),this.type.write(t),this.defaultValue!=null&&(t.write(" = "),this.defaultValue.write(t))}};var xXu={CaseIterable:"CaseIterable",Codable:"Codable",CodingKey:"CodingKey",Decodable:"Decodable",Encodable:"Encodable",Equatable:"Equatable",Error:"Error",Hashable:"Hashable",Sendable:"Sendable",MultipartFormDataConvertible:"MultipartFormDataConvertible"};var Ddt=class extends ep{attributes;name;accessLevel;conformances;properties;initializers;methods;nestedTypes;docs;constructor({attributes:t,accessLevel:r,name:n,conformances:i,properties:o,initializers:s,methods:a,nestedTypes:u,docs:c}){super(),this.attributes=t??[],this.name=n,this.accessLevel=r,this.conformances=i??[],this.properties=o??[],this.initializers=s??[],this.methods=a??[],this.nestedTypes=u??[],this.docs=c}write(t){this.docs!=null&&this.docs.write(t),this.attributes.forEach(a=>{a.arguments?.length?kne.functionCall({unsafeName:`@${a.name}`,arguments_:a.arguments}).write(t):(t.write("@"),t.write(a.name)),t.write(" ")}),this.accessLevel!=null&&(t.write(this.accessLevel),t.write(" ")),t.write(`struct ${this.name}`),this.conformances.forEach((a,u)=>{u===0?t.write(": "):u>0&&t.write(", "),t.write(a)}),t.write(" {"),t.newLine(),t.indent();let r=this.properties.length>0,n=this.initializers.length>0,i=this.methods.length>0,o=this.nestedTypes.length>0;this.properties.forEach(a=>{a.write(t),t.newLine()});let s=r;n&&(s&&t.newLine(),this.initializers.forEach((a,u)=>{u>0&&t.newLine(),a.write(t),t.newLine()}),s=!0),i&&(s&&t.newLine(),this.methods.forEach((a,u)=>{u>0&&t.newLine(),a.write(t),t.newLine()}),s=!0),o&&(s&&t.newLine(),this.nestedTypes.forEach((a,u)=>{u>0&&t.newLine(),a.write(t),t.newLine()})),t.dedent(),t.write("}")}};St();var mLn=class e extends ep{variant;constructor(t){super(),this.variant=t}nonOptional(){return e.nonOptional(this)}nonNullable(){return e.nonNullable(this)}getReferenceIfSymbolType(){return this.variant.type==="symbol"?this.variant.symbol:null}write(t){let{variant:r}=this;switch(r.type){case"symbol":t.write(r.symbol);break;case"generic":{r.reference.write(t),r.arguments.length>0&&(t.write("<"),r.arguments.forEach((n,i)=>{n.write(t),i<r.arguments.length-1&&t.write(", ")}),t.write(">"));break}case"tuple":t.write("("),r.elements.forEach((n,i)=>{i>0&&t.write(", "),n.write(t)}),t.write(")");break;case"array":t.write("["),r.elementType.write(t),t.write("]");break;case"dictionary":t.write("["),r.keyType.write(t),t.write(": "),r.valueType.write(t),t.write("]");break;case"optional":r.valueType.write(t),t.write("?");break;case"nullable":t.write("Nullable<"),r.valueType.write(t),t.write(">");break;case"member-access":r.target.write(t),t.write("."),t.write(r.memberName);break;default:Be(r)}}equals(t){switch(this.variant.type){case"symbol":return t.variant.type==="symbol"&&this.variant.symbol===t.variant.symbol;case"generic":return t.variant.type==="generic"&&this.variant.reference.equals(t.variant.reference)&&this.variant.arguments.every((r,n)=>t.variant.type==="generic"&&t.variant.arguments[n]&&r.equals(t.variant.arguments[n]));case"tuple":return t.variant.type==="tuple"&&this.variant.elements.every((r,n)=>t.variant.type==="tuple"&&t.variant.elements[n]&&r.equals(t.variant.elements[n]));case"array":return t.variant.type==="array"&&this.variant.elementType.equals(t.variant.elementType);case"dictionary":return t.variant.type==="dictionary"&&this.variant.keyType.equals(t.variant.keyType)&&this.variant.valueType.equals(t.variant.valueType);case"optional":return t.variant.type=="optional"&&this.variant.valueType.equals(t.variant.valueType);case"nullable":return t.variant.type==="nullable"&&this.variant.valueType.equals(t.variant.valueType);case"member-access":return t.variant.type==="member-access"&&this.variant.target.equals(t.variant.target)&&this.variant.memberName===t.variant.memberName;default:Be(this.variant)}}static symbol(t){return new this({type:"symbol",symbol:t})}static generic(t,r){return new this({type:"generic",reference:t,arguments:r})}static tuple(t){return new this({type:"tuple",elements:t})}static array(t){return new this({type:"array",elementType:t})}static dictionary(t,r){return new this({type:"dictionary",keyType:t,valueType:r})}static optional(t){return t.variant.type==="optional"?t:new this({type:"optional",valueType:t})}static nullable(t){return t.variant.type==="nullable"?t:new this({type:"nullable",valueType:t})}static memberAccess(t,r){return new this({type:"member-access",target:t,memberName:r})}static nonOptional(t){return t.variant.type==="optional"?e.nonOptional(t.variant.valueType):t}static nonNullable(t){return t.variant.type==="nullable"?e.nonNullable(t.variant.valueType):t}static unqualifiedToSwiftType(t){return e.symbol(t)}static unqualifiedToFoundationType(t){return e.symbol(t)}};var dFm={Http:{relativePathToDir:"Core/Networking",filenameWithoutExtension:"HTTP",symbols:[{name:"HTTP",shape:{type:"enum-container"}}]},MultipartFormData:{relativePathToDir:"Core/Networking",filenameWithoutExtension:"MultipartFormData",symbols:[{name:"MultipartFormData",shape:{type:"class"}}]},MultipartFormDataConvertible:{relativePathToDir:"Core/Networking",filenameWithoutExtension:"MultipartFormDataConvertible",symbols:[{name:"MultipartFormDataConvertible",shape:{type:"protocol"}}]},MultipartFormField:{relativePathToDir:"Core/Networking",filenameWithoutExtension:"MultipartFormField",symbols:[{name:"MultipartFormField",shape:{type:"enum-with-associated-values"}}]},QueryParameter:{relativePathToDir:"Core/Networking",filenameWithoutExtension:"QueryParameter",symbols:[{name:"QueryParameter",shape:{type:"enum-with-associated-values"}}]},DecoderPlusAdditionalProperties:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"Decoder+AdditionalProperties",symbols:[]},EncodableValue:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"EncodableValue",symbols:[{name:"EncodableValue",shape:{type:"struct"}}]},EncoderPlusAdditionalProperties:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"Encoder+AdditionalProperties",symbols:[]},JSONEncoderPlusEncodableValue:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"JSONEncoder+EncodableValue",symbols:[]},KeyedDecodingContainerPlusNullable:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"KeyedDecodingContainer+Nullable",symbols:[]},KeyedEncodingContainerPlusNullable:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"KeyedEncodingContainer+Nullable",symbols:[]},Serde:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"Serde",symbols:[{name:"Serde",shape:{type:"class"}}]},StringKey:{relativePathToDir:"Core/Serde",filenameWithoutExtension:"StringKey",symbols:[{name:"StringKey",shape:{type:"struct"}}]},DataPlusString:{relativePathToDir:"Core",filenameWithoutExtension:"Data+String",symbols:[]},StringPlusUrlEncoding:{relativePathToDir:"Core",filenameWithoutExtension:"String+URLEncoding",symbols:[]},CalendarDate:{relativePathToDir:"Public",filenameWithoutExtension:"CalendarDate",symbols:[{name:"CalendarDate",shape:{type:"struct"}}]},ClientConfig:{relativePathToDir:"Public",filenameWithoutExtension:"ClientConfig",symbols:[{name:"ClientConfig",shape:{type:"class"}}]},FormFile:{relativePathToDir:"Public",filenameWithoutExtension:"FormFile",symbols:[{name:"FormFile",shape:{type:"struct"}}]},HTTPError:{relativePathToDir:"Public",filenameWithoutExtension:"HTTPError",symbols:[{name:"HTTPError",shape:{type:"struct"}}]},Indirect:{relativePathToDir:"Public",filenameWithoutExtension:"Indirect",symbols:[{name:"Indirect",shape:{type:"class"}}]},JsonValue:{relativePathToDir:"Public",filenameWithoutExtension:"JSONValue",symbols:[{name:"JSONValue",shape:{type:"enum-with-associated-values"}}]},Networking:{relativePathToDir:"Public",filenameWithoutExtension:"Networking",symbols:[{name:"Networking",shape:{type:"enum-container"}}]},Nullable:{relativePathToDir:"Public",filenameWithoutExtension:"Nullable",symbols:[{name:"Nullable",shape:{type:"enum-with-associated-values"}}]},RequestOptions:{relativePathToDir:"Public",filenameWithoutExtension:"RequestOptions",symbols:[{name:"RequestOptions",shape:{type:"struct"}}]}};var _C=class e{static SWIFT_SYMBOL_NAME="Swift";static SWIFT_SYMBOL_ID=e.SWIFT_SYMBOL_NAME;static swiftTypeSymbolsByName={String:e.swiftType("String"),Bool:e.swiftType("Bool"),Int:e.swiftType("Int"),Int64:e.swiftType("Int64"),UInt:e.swiftType("UInt"),UInt64:e.swiftType("UInt64"),Float:e.swiftType("Float"),Double:e.swiftType("Double"),Void:e.swiftType("Void"),Encoder:e.swiftType("Encoder"),Decoder:e.swiftType("Decoder"),Any:e.swiftType("Any")};static swiftTypeSymbols=Object.values(e.swiftTypeSymbolsByName);static FOUNDATION_SYMBOL_NAME="Foundation";static FOUNDATION_SYMBOL_ID=e.FOUNDATION_SYMBOL_NAME;static foundationTypeSymbolsByName={Data:e.foundationType("Data"),Date:e.foundationType("Date"),UUID:e.foundationType("UUID")};static foundationTypeSymbols=Object.values(e.foundationTypeSymbolsByName);static isSwiftSymbol(t){return e.SWIFT_SYMBOL_ID===t||t.startsWith(`${e.SWIFT_SYMBOL_ID}.`)}static isSwiftSymbolName(t){return t in e.swiftTypeSymbolsByName}static isFoundationSymbol(t){return e.FOUNDATION_SYMBOL_ID===t||t.startsWith(`${e.FOUNDATION_SYMBOL_ID}.`)}static isFoundationSymbolName(t){return t in e.foundationTypeSymbolsByName}static isCustomSymbol(t){return!e.isSwiftSymbol(t)&&!e.isFoundationSymbol(t)}static create(t,r,n){return new e(t,r,n)}static swiftType(t){return e.create(`${e.SWIFT_SYMBOL_ID}.${t}`,t,{type:"system"})}static foundationType(t){return e.create(`${e.FOUNDATION_SYMBOL_ID}.${t}`,t,{type:"system"})}id;name;shape;constructor(t,r,n){this.id=t,this.name=r,this.shape=n}get isSwiftSymbol(){return e.isSwiftSymbol(this.id)}get isFoundationSymbol(){return e.isFoundationSymbol(this.id)}get isCustomSymbol(){return e.isCustomSymbol(this.id)}};St();St();St();var hLn=class{id;name;childrenByName;constructor(t,r){this.id=t,this.name=r,this.childrenByName=new Map}get children(){return Array.from(this.childrenByName.values())}addChild(t){if(this.childrenByName.has(t.name))throw new Error(`A child with the name '${t.name}' already exists in module '${this.name}'.`);this.childrenByName.set(t.name,t)}getChildByName(t){return this.childrenByName.get(t)}},gLn=class extends hLn{kind="module";imports;parent=null;constructor(t,r){super(t,r),this.imports=[]}addImport(t){this.imports.push(t)}get qualifiedPath(){return[this.name]}get qualifiedName(){return this.name}},ALn=class extends hLn{kind="type";shape;parent;constructor(t,r,n){super(r,t),this.parent=null,this.shape=n}getNearestModuleAncestorOrThrow(){let t=this.parent;for(;t!==null&&t.kind!=="module";)t=t.parent;return DP(t,`No module ancestor found for type symbol '${this.id}'`),t}get qualifiedPath(){return[...this.parent?.qualifiedPath??[],this.name]}get qualifiedName(){return this.qualifiedPath.join(".")}};var JLt=class{symbolsById=new Map;createModuleSymbol({symbolId:t,symbolName:r}){this.validateSymbolNotExists(t);let n=new gLn(t,r);return this.symbolsById.set(t,n),n}createTypeSymbol({symbolId:t,symbolName:r,shape:n}){this.validateSymbolNotExists(t);let i=new ALn(r,t,n);return this.symbolsById.set(t,i),i}addImportRelation({clientSymbolId:t,importedSymbolId:r}){let n=this.getSymbolByIdOrThrow(t),i=this.getSymbolByIdOrThrow(r);if(n.kind!=="module"||i.kind!=="module")throw new Error(`Client module '${n.id}' and imported module '${i.id}' must both be module symbols.`);n.addImport(i)}nestSymbol({parentSymbolId:t,childSymbolId:r}){let n=this.getSymbolByIdOrThrow(t),i=this.getSymbolByIdOrThrow(r);n.addChild(i),i.parent=n}reference({fromSymbolId:t,targetSymbolId:r}){let n=this.getSymbolByIdOrThrow(t),i=this.getSymbolByIdOrThrow(r),o=i.qualifiedPath;for(let s=1;s<=o.length;s++){let a=o.slice(o.length-s);if(this.resolvePath(n,a)?.id===i.id)return a.join(".")}return i.qualifiedName}resolveReference({fromSymbolId:t,reference:r}){let n=this.getSymbolByIdOrThrow(t),i=r.split(".").filter(o=>o.length>0);return this.resolvePath(n,i)}resolvePath(t,r){let[n,...i]=r;if(n===void 0)return null;let o=this.resolveFirstSegment(t,n);if(o===null)return null;let s=o;for(let a=0;a<i.length;a++){let u=i[a];if(Yy(u),s=s.getChildByName(u)??null,s===null)return null}return s}resolveFirstSegment(t,r){let n=t;for(;n!==null;){let s=n.getChildByName(r);if(s)return s;n=n.parent}let i=t.kind==="module"?t:t.getNearestModuleAncestorOrThrow();if(i.name===r)return i;for(let s of i.imports)if(s.name===r)return s;let o=null;for(let s of i.imports){let a=s.getChildByName(r);if(a){if(o!=null&&o.id!==a.id)return null;o=a}}return o}getSymbolByIdOrThrow(t){let r=this.symbolsById.get(t);return Yy(r,`A symbol with the ID '${t}' was not found in the registry.`),r}getSymbolById(t){return this.symbolsById.get(t)??null}validateSymbolNotExists(t){if(this.symbolsById.has(t))throw new Error(`A symbol with the ID '${t}' already exists in the registry.`)}};var Ymo=class e{static create(){let{graph:t,swiftSymbol:r,foundationSymbol:n}=e.createGraph();return new e(t,r,n)}static createGraph(){let t=new JLt,r=()=>{let s=t.createModuleSymbol({symbolId:_C.SWIFT_SYMBOL_ID,symbolName:_C.SWIFT_SYMBOL_NAME});return _C.swiftTypeSymbols.forEach(a=>{let u=t.createTypeSymbol({symbolId:a.id,symbolName:a.name,shape:{type:"system"}});t.nestSymbol({parentSymbolId:s.id,childSymbolId:u.id})}),s},n=()=>{let s=t.createModuleSymbol({symbolId:_C.FOUNDATION_SYMBOL_ID,symbolName:_C.FOUNDATION_SYMBOL_NAME});return _C.foundationTypeSymbols.forEach(a=>{let u=t.createTypeSymbol({symbolId:a.id,symbolName:a.name,shape:{type:"system"}});t.nestSymbol({parentSymbolId:s.id,childSymbolId:u.id})}),s},i=r(),o=n();return{graph:t,swiftSymbol:i,foundationSymbol:o}}graph;swiftSymbol;foundationSymbol;registeredSourceModule;registeredTestModule;constructor(t,r,n){this.graph=t,this.swiftSymbol=r,this.foundationSymbol=n,this.registeredSourceModule=null,this.registeredTestModule=null}getRegisteredSourceModuleSymbolOrThrow(){return DP(this.registeredSourceModule,"Module symbol not found."),_C.create(this.registeredSourceModule.id,this.registeredSourceModule.name,{type:"other"})}getRegisteredTestModuleSymbolOrThrow(){return DP(this.registeredTestModule,"Module symbol not found."),_C.create(this.registeredTestModule.id,this.registeredTestModule.name,{type:"other"})}getSymbolByIdOrThrow(t){let r=this.graph.getSymbolById(t);return DP(r,`Symbol with ID '${t}' not found in registry.`),_C.create(r.id,r.name,r.kind==="type"?r.shape:{type:"other"})}registerSourceModule(t){let r=t,n=this.graph.createModuleSymbol({symbolId:r,symbolName:t});return n.addImport(this.swiftSymbol),n.addImport(this.foundationSymbol),this.registeredSourceModule=n,_C.create(n.id,n.name,{type:"other"})}registerTestModule(t){let r=t,n=this.graph.createModuleSymbol({symbolId:r,symbolName:t});return n.addImport(this.swiftSymbol),n.addImport(this.foundationSymbol),DP(this.registeredSourceModule,"Cannot register a test module before registering a source module."),n.addImport(this.registeredSourceModule),this.registeredTestModule=n,_C.create(n.id,n.name,{type:"other"})}registerSourceModuleType(t,r){DP(this.registeredSourceModule,"Cannot register a type before registering a module.");let n=this.inferSymbolIdForSourceModuleType(t),i=this.graph.createTypeSymbol({symbolId:n,symbolName:t,shape:r});return this.graph.nestSymbol({parentSymbolId:this.registeredSourceModule.id,childSymbolId:i.id}),_C.create(i.id,i.name,r)}registerTestModuleType(t,r){DP(this.registeredTestModule,"Cannot register a type before registering a module.");let n=this.inferSymbolIdForTestModuleType(t),i=this.graph.createTypeSymbol({symbolId:n,symbolName:t,shape:r});return this.graph.nestSymbol({parentSymbolId:this.registeredTestModule.id,childSymbolId:i.id}),_C.create(i.id,i.name,r)}registerNestedType({parentSymbol:t,symbolName:r,shape:n}){let i=typeof t=="string"?t:t.id,o=this.inferSymbolIdForNestedType(i,r),s=this.graph.createTypeSymbol({symbolId:o,symbolName:r,shape:n});return this.graph.nestSymbol({parentSymbolId:i,childSymbolId:s.id}),_C.create(s.id,s.name,n)}reference({fromSymbol:t,toSymbol:r}){let n=typeof t=="string"?t:t.id,i=typeof r=="string"?r:r.id;return this.graph.reference({fromSymbolId:n,targetSymbolId:i})}resolveReference({fromSymbol:t,reference:r}){let n=typeof t=="string"?t:t.id,i=this.graph.resolveReference({fromSymbolId:n,reference:r});return i?_C.create(i.id,i.name,i.kind==="type"?i.shape:{type:"other"}):null}inferSymbolIdForSourceModuleType(t){return DP(this.registeredSourceModule,"Cannot get symbol id for a type before registering a module."),`${this.registeredSourceModule.id}.${t}`}inferSymbolIdForTestModuleType(t){return DP(this.registeredTestModule,"Cannot get symbol id for a type before registering a module."),`${this.registeredTestModule.id}.${t}`}inferSymbolIdForNestedType(t,r){return`${t}.${r}`}};St();var mFm={ClientError:{relativePath:"",filenameWithoutExtension:e=>(y6t(e.errorEnumName),e.errorEnumName)},HTTPClient:{relativePath:"Core/Networking",filenameWithoutExtension:()=>"HTTPClient"}};function hFm(e){return new ydt(e)}function gFm(e){return new dS(e)}function AFm(e){return new bdt(e)}function yFm(e){return new Idt(e)}function bFm(e){return new wdt(e)}function EFm(e){return new Cdt(e)}function vFm(e){return new xdt(e)}function IFm(e){return new _dt(e)}function wFm(e){return new Sdt(e)}function CFm(e){return new Bdt(e)}function xFm(e){return new Odt(e)}function _Fm(e){return new Tdt(e)}function SFm(e){return new Pdt(e)}function BFm(e){return new Ddt(e)}Bi();function _Xu(e){return gc(qn(e))}St();var yLn=class{context;constructor({context:t}){this.context=t}convert(t){let{fromSymbol:r,typeReference:n,value:i,as:o}=t;switch(n.type){case"list":return this.convertList({fromSymbol:r,list:n.value,value:i});case"literal":{if(n.value.type==="string")return Br.Expression.enumCaseShorthand(nLe.generateEnumCaseLabel(n.value.value));if(n.value.type==="boolean")return Br.Expression.nop();Be(n.value);break}case"map":return this.convertMap({fromSymbol:r,map:n,value:i});case"named":{let s=this.context.resolveNamedType({typeId:n.value});return s==null?Br.Expression.nop():this.convertNamed({fromSymbol:r,typeId:n.value,named:s,value:i,as:o})}case"nullable":return this.context.customConfig?.nullableAsOptional?this.convert({fromSymbol:r,typeReference:n.value,value:i,as:o}):this.convertNullable({fromSymbol:r,nullable:n,value:i,as:o});case"optional":return this.convert({fromSymbol:r,typeReference:n.value,value:i,as:o});case"primitive":return this.convertPrimitive({primitive:n.value,value:i,as:o});case"set":return Br.Expression.nop();case"unknown":return this.convertUnknown(i);default:Be(n)}}convertList({fromSymbol:t,list:r,value:n}){return Array.isArray(n)?Br.Expression.arrayLiteral({elements:n.map((i,o)=>{this.context.errors.scope({index:o});try{return this.convert({fromSymbol:t,typeReference:r,value:i})}finally{this.context.errors.unscope()}}),multiline:!0}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof n}`}),Br.Expression.nop())}convertMap({fromSymbol:t,map:r,value:n}){return typeof n!="object"||n==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${n==null?"null":typeof n}`}),Br.Expression.nop()):Br.Expression.dictionaryLiteral({entries:Object.entries(n).map(([i,o])=>{this.context.errors.scope(i);try{return[this.convert({fromSymbol:t,typeReference:r.key,value:i,as:"mapKey"}),this.convert({fromSymbol:t,typeReference:r.value,value:o,as:"mapValue"})]}finally{this.context.errors.unscope()}}),multiline:!0})}convertNamed({fromSymbol:t,typeId:r,named:n,value:i,as:o}){switch(n.type){case"alias":return this.convert({fromSymbol:t,typeReference:n.typeReference,value:i,as:o});case"discriminatedUnion":{let s=this.context.nameRegistry.getSchemaTypeSymbolOrThrow(r);return this.convertDiscriminatedUnion({fromSymbol:t,unionSymbol:s,discriminatedUnion:n,value:i})}case"enum":return this.convertEnum({enum_:n,value:i});case"object":return this.convertObject({fromSymbol:t,typeId:r,object_:n,value:i});case"undiscriminatedUnion":{let s=this.context.nameRegistry.getSchemaTypeSymbolOrThrow(r);return this.convertUndiscriminatedUnion({fromSymbol:t,unionSymbol:s,undiscriminatedUnion:n,value:i})}default:Be(n)}}convertNullable({fromSymbol:t,nullable:r,value:n,as:i}){return n==null?Br.Expression.enumCaseShorthand("null"):Br.Expression.contextualMethodCall({methodName:"value",arguments_:[Br.functionArgument({value:this.convert({fromSymbol:t,typeReference:r.value,value:n,as:i})})]})}convertDiscriminatedUnion({fromSymbol:t,discriminatedUnion:r,unionSymbol:n,value:i}){let o=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:r,value:i});if(o==null)return Br.Expression.nop();let s=o.singleDiscriminatedUnionType,a=oLn.sanitizeToCamelCase(s.discriminantValue.name.camelCase.unsafeName);switch(s.type){case"samePropertiesAsObject":{let u=this.context.resolveNamedType({typeId:s.typeId});if(u==null)return Br.Expression.nop();let c=this.convertNamed({fromSymbol:t,typeId:s.typeId,named:u,value:o.value});return Br.Expression.methodCall({target:Br.Expression.reference(n.name),methodName:a,arguments_:[Br.functionArgument({value:c})],multiline:!0})}case"singleProperty":try{this.context.errors.scope(s.discriminantValue.wireValue);let u=this.context.getRecord(o.value);if(u==null)return Br.Expression.nop();let c=this.convert({fromSymbol:t,typeReference:s.typeReference,value:u[s.discriminantValue.wireValue]});return Br.Expression.methodCall({target:Br.Expression.reference(n.name),methodName:a,arguments_:[Br.functionArgument({value:c})],multiline:!0})}finally{this.context.errors.unscope()}case"noProperties":return Br.Expression.memberAccess({target:Br.Expression.reference(n.name),memberName:a});default:Be(s)}}convertEnum({enum_:t,value:r}){let n=this.getEnumValue({enum_:t,value:r});return n==null?Br.Expression.nop():Br.Expression.enumCaseShorthand(n.name.camelCase.unsafeName)}getEnumValue({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Ir.Critical,message:`Expected enum value string, got: ${typeof r}`});return}let n=t.values.find(i=>i.wireValue===r);if(n==null){this.context.errors.add({severity:Ir.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return n}convertObject({fromSymbol:t,typeId:r,object_:n,value:i}){let o=this.context.nameRegistry.getSchemaTypeSymbolOrThrow(r);return Br.Expression.structInitialization({unsafeName:o.name,arguments_:this.context.getExampleObjectProperties({parameters:n.properties,snippetObject:i}).map(s=>this.convert({fromSymbol:t,typeReference:s.typeReference,value:s.value}).isNop()?null:Br.functionArgument({label:Edt(s.name.name.camelCase.unsafeName),value:this.convert({fromSymbol:t,typeReference:s.typeReference,value:s.value})})).filter(s=>s!=null),multiline:!0})}convertUndiscriminatedUnion({fromSymbol:t,unionSymbol:r,undiscriminatedUnion:n,value:i}){let o=this.findMatchingUndiscriminatedUnionType({fromSymbol:t,unionSymbol:r,undiscriminatedUnion:n,value:i});return o??Br.Expression.nop()}findMatchingUndiscriminatedUnionType({fromSymbol:t,unionSymbol:r,undiscriminatedUnion:n,value:i}){let o=this.context.nameRegistry.getAllUndiscriminatedUnionVariantsOrThrow(r);for(let s of n.types){let a=this.context.errors.size();try{let u=this.convert({fromSymbol:t,typeReference:s,value:i}),c=this.context.getSwiftTypeReferenceFromScope(s,t),l=o.find(p=>p.swiftType.equals(c));if(l==null){this.context.errors.truncate(a);continue}return Br.Expression.methodCall({target:Br.Expression.reference(r.name),methodName:l.caseName,arguments_:[Br.functionArgument({value:u})],multiline:!0})}catch{this.context.errors.truncate(a);continue}}this.context.errors.add({severity:Ir.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof i}" value`})}convertUnknown(t){switch(typeof t){case"boolean":return Br.Expression.contextualMethodCall({methodName:"bool",arguments_:[Br.functionArgument({value:Br.Expression.boolLiteral(t)})]});case"string":return Br.Expression.contextualMethodCall({methodName:"string",arguments_:[Br.functionArgument({value:Br.Expression.stringLiteral(t)})]});case"number":return Br.Expression.contextualMethodCall({methodName:"number",arguments_:[Br.functionArgument({value:Br.Expression.numberLiteral(t)})]});case"object":return t===null?Br.Expression.enumCaseShorthand("null"):Array.isArray(t)?Br.Expression.contextualMethodCall({methodName:"array",arguments_:[Br.functionArgument({value:Br.Expression.arrayLiteral({elements:t.map(r=>this.convertUnknown(r)),multiline:!0})})]}):Br.Expression.contextualMethodCall({methodName:"object",arguments_:[Br.functionArgument({value:Br.Expression.dictionaryLiteral({entries:Object.entries(t).map(([r,n])=>[Br.Expression.stringLiteral(r),this.convertUnknown(n)]),multiline:!0})})]});default:throw new Error(`Internal error; unsupported unknown type: ${typeof t}`)}}convertPrimitive({primitive:t,value:r,as:n}){switch(t){case"INTEGER":case"UINT":case"LONG":case"UINT_64":case"FLOAT":case"DOUBLE":{let i=this.getValueAsNumber({value:r,as:n});return i==null?Br.Expression.nop():Br.Expression.numberLiteral(i)}case"BOOLEAN":{let i=this.getValueAsBoolean({value:r,as:n});return i==null?Br.Expression.nop():Br.Expression.boolLiteral(i)}case"STRING":{let i=this.context.getValueAsString({value:r});return i==null?Br.Expression.nop():Br.Expression.stringLiteral(i)}case"DATE":{let i=this.context.getValueAsString({value:r});return i==null?Br.Expression.nop():Br.Expression.calendarDateLiteral(i)}case"DATE_TIME":{let i=this.context.getValueAsString({value:r});if(i==null)return Br.Expression.nop();let o=new Date(i).getTime(),s=Math.round(o/1e3),u=new Date(s*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return Br.Expression.dateLiteral(u)}case"UUID":{let i=this.context.getValueAsString({value:r});return i==null?Br.Expression.nop():Br.Expression.uuidLiteral(i)}case"BASE_64":{let i=this.context.getValueAsString({value:r});return i==null?Br.Expression.nop():Br.Expression.stringLiteral(i)}case"BIG_INTEGER":return this.context.getValueAsString({value:r})==null?Br.Expression.nop():Br.Expression.nop();default:Be(t)}}getValueAsNumber({value:t,as:r}){let n=r==="mapKey"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=(()=>{switch(r){case"mapKey":return t==="true"?!0:t==="false"?!1:t;case"mapValue":case void 0:return t;default:Be(r)}})();return this.context.getValueAsBoolean({value:n})}};St();var bLn=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({fromSymbol:t,body:r,value:n}){let i={fileFields:[],bodyPropertyFields:[]},o=this.context.getRecord(n)??{};for(let s of r.properties)switch(s.type){case"file":{let a=Br.functionArgument({label:Edt(s.name.camelCase.unsafeName),value:this.getSingleFileProperty({property:s,record:o})});i.fileFields.push(a);break}case"fileArray":{let a=Br.functionArgument({label:Edt(s.name.camelCase.unsafeName),value:this.getArrayFileProperty({property:s,record:o})});i.fileFields.push(a);break}case"bodyProperty":{let a=Br.functionArgument({label:Edt(s.name.name.camelCase.unsafeName),value:this.getBodyProperty({fromSymbol:t,property:s,record:o})});i.bodyPropertyFields.push(a);break}default:Be(s)}return i}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r});return Br.Expression.contextualMethodCall({methodName:"init",arguments_:[Br.functionArgument({label:"data",value:Br.Expression.dataLiteral(n??"")})]})}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});return Br.Expression.arrayLiteral({elements:(n??[]).map(i=>Br.Expression.contextualMethodCall({methodName:"init",arguments_:[Br.functionArgument({label:"data",value:Br.Expression.dataLiteral(i)})]})),multiline:!0})}getBodyProperty({fromSymbol:t,property:r,record:n}){let i=n[r.name.wireValue];return i==null?Br.Expression.nop():this.context.dynamicTypeLiteralMapper.convert({fromSymbol:t,typeReference:r.typeReference,value:i})}};St();function SXu({parentSymbol:e,registry:t,namedType:r,context:n}){zw(r,"type")._visit({object:i=>{Xmo({parentSymbol:e,registry:t,properties:i.properties})},discriminatedUnion:i=>{Object.values(i.types).forEach(o=>{zw(o,"type")._visit({noProperties:ft,samePropertiesAsObject:ft,singleProperty:s=>{Ife({parentSymbol:e,registry:t,typeReference:s.typeReference})},_other:ft})})},undiscriminatedUnion:i=>{i.types.forEach(o=>{Ife({parentSymbol:e,registry:t,typeReference:o})})},alias:ft,enum:ft,_other:ft})}function Xmo({parentSymbol:e,registry:t,properties:r}){r.forEach(n=>{Ife({parentSymbol:e,registry:t,typeReference:n.typeReference})})}function Ife({parentSymbol:e,registry:t,typeReference:r}){zw(r,"type")._visit({list:n=>{Ife({parentSymbol:e,registry:t,typeReference:n.value})},literal:n=>{zw(n.value,"type")._visit({string:i=>{t.registerNestedLiteralEnumSymbol({parentSymbol:e,literalValue:i.value})},boolean:ft,_other:ft})},map:n=>{Ife({parentSymbol:e,registry:t,typeReference:n.key}),Ife({parentSymbol:e,registry:t,typeReference:n.value})},named:ft,nullable:n=>{Ife({parentSymbol:e,registry:t,typeReference:n.value})},optional:n=>{Ife({parentSymbol:e,registry:t,typeReference:n.value})},primitive:ft,set:n=>{Ife({parentSymbol:e,registry:t,typeReference:n.value})},unknown:ft,_other:ft})}function BXu({parentSymbol:e,registry:t,namedType:r,context:n}){if(r.type==="undiscriminatedUnion"){let i=r.types.map(o=>{let s=n.getSwiftTypeReferenceFromScope(o,e);return{swiftType:s,caseName:aLn.inferCaseNameForTypeReference(e,s,t),docsContent:void 0}});t.registerUndiscriminatedUnionVariants({parentSymbol:e,variants:i})}}var ELn=class e extends $v{ir;customConfig;dynamicTypeLiteralMapper;filePropertyMapper;nameRegistry;constructor({ir:t,config:r,options:n,sharedNameRegistry:i}){super({ir:t,config:r,options:n}),this.ir=t,this.customConfig=r.customConfig!=null?r.customConfig:void 0,this.dynamicTypeLiteralMapper=new yLn({context:this}),this.filePropertyMapper=new bLn({context:this}),i!=null?this.nameRegistry=i:(this.nameRegistry=pLn.create(),this.registerSourceSymbols(this.nameRegistry,t))}registerSourceSymbols(t,r){let n=_Xu(this.config.workspaceName),i=t.registerSourceModuleSymbol({configModuleName:this.customConfig?.moduleName,apiNamePascalCase:n,asIsSymbols:Object.values(Br.SourceAsIsFileSpecs).flatMap(s=>s.symbols)});return t.registerRootClientSymbol({configClientClassName:this.customConfig?.clientClassName,registeredSourceModuleName:i.name}),Xy(Br.SourceTemplateFileSpecs).forEach(([s])=>{switch(s){case"ClientError":t.registerErrorEnumSymbol(i.name);break;case"HTTPClient":t.registerSourceStaticSymbol(s,{type:"class"});break;default:Be(s)}}),t.registerEnvironmentSymbol({configEnvironmentEnumName:this.customConfig?.environmentEnumName,registeredSourceModuleName:i.name}),Object.entries(r.types).map(([s,a])=>{let u=zw(a,"type")._visit({alias:()=>({type:"struct"}),enum:()=>({type:"enum-with-raw-values"}),object:()=>({type:"struct"}),discriminatedUnion:()=>({type:"enum-with-associated-values"}),undiscriminatedUnion:()=>({type:"enum-with-associated-values"}),_other:()=>({type:"other"})}),c=t.registerSchemaTypeSymbol(s,a.declaration.name.pascalCase.unsafeName,u);return{namedType:a,registeredSymbol:c}}).forEach(({namedType:s,registeredSymbol:a})=>{SXu({parentSymbol:a,registry:t,namedType:s,context:this}),BXu({parentSymbol:a,registry:t,namedType:s,context:this})}),t.registerRequestsContainerSymbol(),Object.entries(r.endpoints).forEach(([s,a])=>{if(a.request.type==="inlined"){if(a.request.body?.type==="properties"){let u=t.registerRequestTypeSymbol({endpointId:s,requestNamePascalCase:a.request.declaration.name.pascalCase.unsafeName});Xmo({parentSymbol:u,registry:t,properties:a.request.body.value})}a.request.body?.type==="fileUpload"&&t.registerRequestTypeSymbol({endpointId:s,requestNamePascalCase:a.request.declaration.name.pascalCase.unsafeName})}}),t}getNamedTypeOrThrow(t){let r=this.ir.types[t];return Yy(r,`Type declaration with the id '${t}' not found`),r}getPropertiesOfDiscriminatedUnionVariant(t){let r=this.getNamedTypeOrThrow(t);return zw(r,"type")._visit({alias:()=>[],enum:()=>[],object:n=>n.properties,discriminatedUnion:()=>[],undiscriminatedUnion:()=>[],_other:()=>[]})}getSwiftTypeReferenceFromScope(t,r){let n=this.createReferencer(r);return zw(t,"type")._visit({list:i=>Br.TypeReference.array(this.getSwiftTypeReferenceFromScope(i.value,r)),literal:i=>zw(i.value,"type")._visit({boolean:()=>n.referenceAsIsType("JSONValue"),string:o=>{let s=this.nameRegistry.getNestedLiteralEnumSymbolOrThrow(r,o.value);return n.referenceType(s)},_other:()=>n.referenceAsIsType("JSONValue")}),map:i=>Br.TypeReference.dictionary(this.getSwiftTypeReferenceFromScope(i.key,r),this.getSwiftTypeReferenceFromScope(i.value,r)),named:i=>{let o=this.nameRegistry.getSchemaTypeSymbolOrThrow(i.value),s=this.nameRegistry.reference({fromSymbol:r,toSymbol:o});return Br.TypeReference.symbol(s)},nullable:i=>this.customConfig?.nullableAsOptional?Br.TypeReference.optional(this.getSwiftTypeReferenceFromScope(i.value,r)):Br.TypeReference.nullable(this.getSwiftTypeReferenceFromScope(i.value,r)),optional:i=>Br.TypeReference.optional(this.getSwiftTypeReferenceFromScope(i.value,r)),primitive:i=>zw(i,"value")._visit({STRING:()=>n.referenceSwiftType("String"),BOOLEAN:()=>n.referenceSwiftType("Bool"),INTEGER:()=>n.referenceSwiftType("Int"),UINT:()=>n.referenceSwiftType("UInt"),UINT_64:()=>n.referenceSwiftType("UInt64"),LONG:()=>n.referenceSwiftType("Int64"),FLOAT:()=>n.referenceSwiftType("Float"),DOUBLE:()=>n.referenceSwiftType("Double"),BIG_INTEGER:()=>n.referenceSwiftType("String"),DATE:()=>n.referenceAsIsType("CalendarDate"),DATE_TIME:()=>n.referenceFoundationType("Date"),BASE_64:()=>n.referenceSwiftType("String"),UUID:()=>n.referenceFoundationType("UUID"),_other:()=>n.referenceAsIsType("JSONValue")}),set:()=>n.referenceAsIsType("JSONValue"),unknown:()=>n.referenceAsIsType("JSONValue"),_other:()=>n.referenceAsIsType("JSONValue")})}createReferencer(t){return new sLn(this.nameRegistry,t)}clone(){return new e({ir:this.ir,config:this.config,options:this.options,sharedNameRegistry:this.nameRegistry})}};St();var OXu="client",vLn=class{context;constructor({context:t}){this.context=t}async generateSnippet({endpoint:t,request:r,options:n}){return this.buildCodeBlock({endpoint:t,snippetRequest:r,options:n})}generateSnippetSync({endpoint:t,request:r,options:n}){return this.buildCodeBlock({endpoint:t,snippetRequest:r,options:n})}async generateSnippetAst({endpoint:t,request:r,options:n}){throw new Error("Unsupported")}buildCodeBlock({endpoint:t,snippetRequest:r,options:n}){return[this.generateImportFoundationStatement(),this.generateImportModuleStatement(),Br.LineBreak.single(),this.generateMainFunctionDeclarationWithEndpointSnippet({endpoint:t,snippet:r}),Br.LineBreak.single(),this.generateMainFunctionInvocationStatement()].map(o=>o.toString()).join("")}generateImportFoundationStatement(){return Br.Statement.import("Foundation")}generateImportModuleStatement(){let t=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();return Br.Statement.import(t.name)}generateMainFunctionDeclarationWithEndpointSnippet({endpoint:t,snippet:r}){return Br.Statement.functionDeclaration({unsafeName:"main",accessLevel:"private",async:!0,throws:!0,body:Br.CodeBlock.withStatements([this.generateRootClientInitializationStatement({auth:t.auth,snippet:r}),Br.LineBreak.single(),this.generateEndpointMethodCallStatement({endpoint:t,snippet:r})])})}generateRootClientInitializationStatement({auth:t,snippet:r,additionalArgs:n=[]}){let i=[],o=this.getRootClientBaseURLArg({snippet:r});o!=null&&i.push(o);let s=t?this.getRootClientAuthArgs({auth:t,snippet:r}):[];i.push(...s),this.context.ir.headers!=null&&r.headers!=null&&i.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:r.headers})),i.push(...n);let a=i.filter(c=>!c.value.isNop()),u=this.context.nameRegistry.getRootClientSymbolOrThrow();return Br.Statement.constantDeclaration({unsafeName:OXu,value:Br.Expression.classInitialization({unsafeName:u.name,arguments_:a,multiline:a.length>1?!0:void 0})})}getRootClientHeaderArgs({headers:t,values:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow(),i=[];for(let o of t){let s=r[o.name.wireValue],a=this.getRootClientHeaderArg({moduleSymbol:n,header:o,value:s});a!=null&&i.push(a)}return i}getRootClientHeaderArg({moduleSymbol:t,header:r,value:n}){if(r.typeReference.type==="literal")return;let i=this.context.dynamicTypeLiteralMapper.convert({fromSymbol:t,typeReference:r.typeReference,value:n});if(!i.isNop())return Br.functionArgument({label:r.name.name.camelCase.unsafeName,value:i})}getRootClientBaseURLArg({snippet:t}){return t.baseURL!=null&&t.environment!=null?(this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"}),null):t.baseURL!=null?this.context.ir.environments?.environments.type==="multipleBaseUrls"?null:Br.functionArgument({label:"baseURL",value:Br.Expression.stringLiteral(t.baseURL)}):null}getRootClientAuthArgs({auth:t,snippet:r}){let n=[],i=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow(),o=r.auth;if(o==null)return n;switch(t.type){case"basic":if(o.type!=="basic"){this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:o}).message});break}n.push(Br.functionArgument({label:t.username.camelCase.unsafeName,value:Br.Expression.stringLiteral(o.username)}),Br.functionArgument({label:t.password.camelCase.unsafeName,value:Br.Expression.stringLiteral(o.password)}));break;case"bearer":if(o.type!=="bearer")return this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:o}).message}),n;n.push(Br.functionArgument({label:t.token.camelCase.unsafeName,value:Br.Expression.stringLiteral(o.token)}));break;case"header":if(o.type!=="header")return this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:o}).message}),n;n.push(Br.functionArgument({label:t.header.name.name.camelCase.unsafeName,value:this.context.dynamicTypeLiteralMapper.convert({fromSymbol:i,typeReference:t.header.typeReference,value:o.value})}));break;case"oauth":return o.type!=="oauth"&&this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:o}).message}),n;case"inferred":return o.type!=="inferred"&&this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:o}).message}),n;default:Be(t)}return n}generateEndpointMethodCallStatement({endpoint:t,snippet:r}){return Br.Statement.discardAssignment(this.generateEndpointMethodCallExpression({endpoint:t,snippet:r}))}generateEndpointMethodCallExpression({endpoint:t,snippet:r,additionalArguments:n=[]}){let o=[...this.getEndpointMethodArguments({endpoint:t,snippet:r}).filter(s=>!s.value.isNop()),...n];return Br.Expression.try(Br.Expression.await(Br.Expression.methodCall({target:Br.Expression.rawValue(OXu),methodName:this.getEndpointMethodName({endpoint:t}),arguments_:o,multiline:o.length>1?!0:void 0})))}generateMainFunctionInvocationStatement(){return Br.Statement.expressionStatement(Br.Expression.try(Br.Expression.await(Br.Expression.functionCall({unsafeName:"main"}))))}getEndpointMethodName({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${`${t.declaration.fernFilepath.allParts.map(n=>n.camelCase.unsafeName).join(".")}`}.${t.declaration.name.camelCase.unsafeName}`:t.declaration.name.camelCase.unsafeName}getEndpointMethodArguments({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getEndpointMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getEndpointMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getEndpointMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[];t.pathParameters!=null&&i.push(...this.getEndpointMethodPathParameters({namedParameters:t.pathParameters,snippet:r})),this.context.errors.unscope(),n.push(...i),this.context.errors.scope(Lo.QueryParameters);let o=[];t.queryParameters!=null&&o.push(...this.getEndpointMethodQueryParameters({namedParameters:t.queryParameters,snippet:r})),this.context.errors.unscope(),n.push(...o),this.context.errors.scope(Lo.RequestBody);let s=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),t.body!=null&&n.push(Br.functionArgument({label:"request",value:this.getInlinedRequestArg({request:t,snippet:r,filePropertyInfo:s})})),n}getEndpointMethodPathParameters({namedParameters:t,snippet:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();return this.context.getExampleObjectProperties({parameters:t,snippetObject:r.pathParameters??{}}).map(i=>Br.functionArgument({label:i.name.name.camelCase.unsafeName,value:this.context.dynamicTypeLiteralMapper.convert({fromSymbol:n,typeReference:i.typeReference,value:i.value})}))}getEndpointMethodQueryParameters({namedParameters:t,snippet:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();return this.context.getExampleObjectProperties({parameters:t,snippetObject:r.queryParameters??{}}).map(i=>Br.functionArgument({label:i.name.name.camelCase.unsafeName,value:this.context.dynamicTypeLiteralMapper.convert({fromSymbol:n,typeReference:i.typeReference,value:i.value})}))}getFilePropertyInfo({request:t,snippet:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({fromSymbol:n,body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,filePropertyInfo:n}){this.context.errors.scope(Lo.RequestBody);let i=t.body!=null?this.getInlinedRequestBodyObjectFields({body:t.body,value:r.requestBody,filePropertyInfo:n}):[];this.context.errors.unscope();let o=i.filter(s=>!s.value.isNop());return Br.Expression.contextualMethodCall({methodName:"init",arguments_:o,multiline:o.length>1?!0:void 0})}getInlinedRequestBodyObjectFields({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"fileUpload":return[...n.fileFields,...n.bodyPropertyFields];case"properties":return this.getInlinedRequestBodyPropertyObjectFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyObjectField({body:t,value:r})];default:Be(t)}}getInlinedRequestBodyPropertyObjectFields({parameters:t,value:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();return this.context.getExampleObjectProperties({parameters:t,snippetObject:r}).map(i=>Br.functionArgument({label:i.name.name.camelCase.unsafeName,value:this.context.dynamicTypeLiteralMapper.convert({fromSymbol:n,typeReference:i.typeReference,value:i.value})}))}getReferencedRequestBodyPropertyObjectField({body:t,value:r}){return Br.functionArgument({label:t.bodyKey.camelCase.unsafeName,value:this.getReferencedRequestBodyPropertyTypeLiteral({body:t.bodyType,value:r})})}getReferencedRequestBodyPropertyTypeLiteral({body:t,value:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({fromSymbol:n,typeReference:t.value,value:r});default:Be(t)}}getBytesBodyRequestArg({value:t}){return typeof t!="string"?(this.context.errors.add({severity:Ir.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),Br.Expression.dataLiteral("data")):Br.Expression.dataLiteral(t)}getEndpointMethodArgsForBodyRequest({request:t,snippet:r}){let n=[],i=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();this.context.errors.scope(Lo.PathParameters);let o=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];return o.length>0&&n.push(...this.getEndpointMethodPathParameters({namedParameters:o,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),t.body!=null&&n.push(this.getEndpointMethodBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope(),n}getEndpointMethodBodyRequestArg({body:t,value:r}){let n=this.context.nameRegistry.getRegisteredSourceModuleSymbolOrThrow();switch(t.type){case"bytes":return Br.functionArgument({label:"request",value:this.getBytesBodyRequestArg({value:r})});case"typeReference":return Br.functionArgument({label:"request",value:this.context.dynamicTypeLiteralMapper.convert({fromSymbol:n,typeReference:t.value,value:r})});default:Be(t)}}};var YLt=class extends Wv{constructor({ir:t,config:r,options:n={}}){super(new ELn({ir:t,config:r,options:n}))}async generate(t,r={}){return super.generate(t,r)}generateSync(t,r={}){return super.generateSync(t,r)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new vLn({context:t})}};var ILn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new YLt({ir:fS(this.ir),config:this.generatorConfig})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");let n=await this.initializeProject(t);for(let[i,{endpointId:o,request:s}]of r.entries())try{let a=pS(s);if(a==null)continue;let u=await this.dynamicSnippetsGenerator.generate(a,{config:{},style:CC.Full,endpointId:o}),c=this.getTestFilePath({absolutePathToOutputDir:n,idx:i});await(0,XLt.mkdir)(TXu.default.dirname(c),{recursive:!0}),await(0,XLt.writeFile)(c,u.snippet)}catch(a){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(s.endpoint)}: ${a}`)}this.context.logger.debug("Done generating dynamic snippet tests")}async initializeProject(t){let r=Ge(t,Se.of("Snippets"));return await(0,XLt.mkdir)(r,{recursive:!0}),r}getTestFilePath({absolutePathToOutputDir:t,idx:r}){return Ge(t,Se.of(`Example${r}.swift`))}};qt();var Rdt=class extends wC{customConfig;formatter;imports={};defaultImports={};starImportAliases={};starImportAliasesInverse={};constructor({customConfig:t,formatter:r}){super(),this.customConfig=t,this.formatter=r??new B7}addImport(t){if(t.importFrom!=null){switch(t.importFrom.type){case"default":{this.validateDefault(t);break}case"named":{this.validateNamed(t);break}case"star":{this.validateStar(t);break}}let r=this.imports[t.importFrom.moduleName]??=[];r.map(i=>i.name).includes(t.name)||r.push(t)}}validateDefault(t){if(t.importFrom?.type!=="default")return;let r=this.defaultImports[t.importFrom.moduleName]??=t;if(r.name!==t.name)throw new Error(`Cannot have multiple default imports for module ${t.importFrom.moduleName}: got ${t.name} but already had ${r.name}`)}validateNamed(t){if(t.importFrom?.type!=="named")return;let n=(this.imports[t.importFrom.moduleName]??[]).filter(o=>o.importFrom?.type==="star");if(n.length>0)throw new Error(`Cannot add named import ${t.name} because non-named imports ${n.map(o=>o.name)} already exist`);let i=[];for(let o of Object.values(this.imports))for(let s of o)s.importFrom?.type==="named"&&s.importFrom.moduleName!==t.importFrom.moduleName&&s.name===t.name&&i.push(s);if(i.length>0)throw new Error(`Cannot add named import from module ${t.importFrom.moduleName} because it is already imported from ${i[0]?.importFrom?.moduleName}`)}validateStar(t){if(t.importFrom?.type!=="star")return;let r=this.starImportAliases[t.importFrom.moduleName]??=t.importFrom.starImportAlias;if(r!==t.importFrom.starImportAlias)throw new Error(`Cannot have more than one alias for non-named imports from a module: got ${t.importFrom.starImportAlias} but already have ${r}.`);if((this.starImportAliasesInverse[t.importFrom.starImportAlias]??=t.importFrom.moduleName)!==t.importFrom.moduleName)throw new Error(`Attempted to use alias ${t.importFrom.starImportAlias} for more than one module in the same file`)}};var ZLt=class extends Rdt{constructor({customConfig:t,formatter:r}){super({customConfig:t,formatter:r})}async toStringAsync(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.format(t)}catch(r){throw new Error(`Failed to format TypeScript file: ${r}
2580
2580
  ${t}`)}return t}toString(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.formatSync(t)}catch(r){throw new Error(`Failed to format TypeScript file: ${r}
2581
2581
  ${t}`)}return t}getContent(){let t=this.stringifyImports();return t.length>0?t+`
2582
2582
  `+this.buffer:this.buffer}stringifyImports(){let t="";for(let[r,n]of Object.entries(this.imports)){let i=this.defaultImports[r],o="",s=n.filter(u=>u.importFrom?.type==="named"),a=this.starImportAliases[r];if(s.length>0||i!=null||a!=null){if(t+="import",i!=null&&(t+=` ${i.name}`),s.length>0){for(let c of s.slice(0,-1))o+=`${c.name}, `;let u=s[s.length-1];u!=null&&(o+=`${u.name}`),i!=null&&(t+=","),t+=` { ${o} }`}a!=null&&((i!=null||s.length>0)&&(t+=", "),t+=` * as ${a}`),t+=` from "${r}";
@@ -2585,7 +2585,7 @@ ${t}`)}return t}getContent(){let t=this.stringifyImports();return t.length>0?t+`
2585
2585
  `)?this.writeStringWithBackticks({writer:t,value:this.internalType.value}):t.write(`"${this.internalType.value.replaceAll('"','\\"')}"`);break}case"tuple":{this.writeIterable({writer:t,iterable:this.internalType});break}case"unknown":{this.writeUnknown({writer:t,value:this.internalType.value});break}case"null":{t.write("null");break}case"nop":break;default:Be(this.internalType)}}isObject(){return this.internalType.type==="object"}asObjectOrThrow(){if(this.isObject())return this.internalType;throw new Error("Internal error; ts.TypeLiteral is not an object")}isSet(){return this.internalType.type==="set"}asSetOrThrow(){if(this.isSet())return this.internalType;throw new Error("Internal error; ts.TypeLiteral is not a set")}isSetOfObjects(){return this.isSet()&&this.asSetOrThrow().values.every(t=>t.isObject())}writeStringWithBackticks({writer:t,value:r}){t.write("`");let n=r.split(`
2586
2586
  `),i=n[0]+`
2587
2587
  `,o=n.slice(1).join(`
2588
- `);t.write(i.replaceAll("`","\\`")),t.writeNoIndent(o.replaceAll("`","\\`")),t.write("`")}writeIterable({writer:t,iterable:r}){let n=PFm({values:r.values});if(n.length===0){t.write("[]");return}t.writeLine("["),t.indent();for(let i of n)i.write(t),t.writeLine(",");t.dedent(),t.write("]")}writeRecord({writer:t,record:r}){let n=TFm({entries:r.entries});if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let i of n)i.key.write(t),t.write(": "),i.value.write(t),t.writeLine(",");t.dedent(),t.write("}")}writeObject({writer:t,object:r}){let n=OFm({fields:r.fields});if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let i of n)t.write(`${i.name}: `),i.value.write(t),t.writeLine(",");t.dedent(),t.write("}")}static array({values:t}){return new this({type:"array",values:t})}static bigint(t){return new this({type:"bigint",value:t})}static blob(t){return new this({type:"blob",value:t})}static boolean(t){return new this({type:"boolean",value:t})}static datetime(t){return new this({type:"datetime",value:t})}static number(t){return new this({type:"number",value:t})}static object({fields:t}){return new this({type:"object",fields:t})}static record({entries:t}){return new this({type:"record",entries:t})}static reference(t){return new this({type:"reference",value:t})}static set({values:t}){return new this({type:"set",values:t})}static string(t){return new this({type:"string",value:t})}static tuple({values:t}){return new this({type:"tuple",values:t})}static unknown(t){return new this({type:"unknown",value:t})}static null(){return new this({type:"null"})}static nop(){return new this({type:"nop"})}static isNop(t){return t.internalType.type==="nop"}writeUnknown({writer:t,value:r}){switch(typeof r){case"boolean":t.write(r.toString());return;case"string":t.write(r.includes('"')?`\`${r}\``:`"${r}"`);return;case"number":t.write(r.toString());return;case"object":if(r==null){t.write("null");return}if(Array.isArray(r)){this.writeUnknownArray({writer:t,value:r});return}this.writeUnknownObject({writer:t,value:r});return;default:throw new Error(`Internal error; unsupported unknown type: ${typeof r}`)}}writeUnknownArray({writer:t,value:r}){if(r.length===0){t.write("[]");return}t.writeLine("["),t.indent();for(let n of r)t.writeNode(e.unknown(n)),t.writeLine(",");t.dedent(),t.write("]")}writeUnknownObject({writer:t,value:r}){let n=Object.entries(r);if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let[i,o]of n)t.write(`${i}: `),t.writeNode(e.unknown(o)),t.writeLine(",");t.dedent(),t.write("}")}};function OFm({fields:e}){return e.filter(t=>!wfe.isNop(t.value))}function TFm({entries:e}){return e.filter(t=>!wfe.isNop(t.key)&&!wfe.isNop(t.value))}function PFm({values:e}){return e.filter(t=>!wfe.isNop(t))}var Ldt=class extends XA{args;constructor(t){super(),this.args=t}write(t){this.args.export&&t.write("export "),this.args.const?t.write("const "):t.write("let "),t.write(`${this.args.name} = `),t.writeNode(this.args.initializer)}};function RFm(e){return new Ndt(e)}function FFm(e){return new kdt(e)}function NFm(e){return new Fdt(e)}function kFm(e){return new Qdt(e)}function QFm(e){return new jdt(e)}function jFm(e){return new Mdt(e)}function MFm(e){return new sLe(e)}function LFm(e){return new Ldt(e)}function PXu({generatorConfig:e,isPackagePrivate:t}){let r=e.output.mode;switch(r.type){case"downloadFiles":return;case"publish":return{packageName:r.registriesV2.npm.packageName,version:r.version,private:t,publishInfo:{registryUrl:r.registriesV2.npm.registryUrl,token:r.registriesV2.npm.token},license:void 0,repoUrl:void 0};case"github":if(r.publishInfo!=null&&r.publishInfo.type!=="npm")throw new Error(`Expected to receive npm publish info but received ${r.publishInfo.type} instead`);return{packageName:r.publishInfo!=null?r.publishInfo.packageName:"",version:r.version,private:t,publishInfo:void 0,repoUrl:UFm(r.repoUrl),license:e.license?._visit({basic:n=>n.id,custom:n=>`See ${n.filename}`,_other:()=>{}})};default:throw new Error(`Encountered unknown output mode: ${r}`)}}function UFm(e){if(e!=null)return e.startsWith("https://github.com/")?`git+${e}`:e.startsWith("ssh://github.com/")?`github:${eUt(e).replace("ssh://github.com/","")}`:e.startsWith("https://bitbucket.org/")?`bitbucket:${eUt(e).replace("https://bitbucket.org/","")}`:e.startsWith("ssh://bitbucket.org/")?`bitbucket:${eUt(e).replace("ssh://bitbucket.org/","")}`:e.startsWith("https://gitlab.com/")?`gitlab:${eUt(e).replace("https://gitlab.com/","")}`:e.startsWith("ssh://gitlab.com/")?`gitlab:${eUt(e).replace("ssh://gitlab.com/","")}`:(e.startsWith("git+")||(e=`git+${e}`),e.endsWith(".git")||(e=`${e}.git`),e)}function eUt(e){return e.endsWith(".git")?e.slice(0,-4):e}Bi();function Zmo({organization:e,workspaceName:t,namespaceExport:r,naming:n}){return(typeof n=="string"?n:n?.namespace)??r??`${gc(qn(e))}${gc(qn(t))}`}function eho({namespaceExport:e,naming:t}){let r=typeof t=="string"?{}:t,n=t!=null?gc(qn(e)):e;return{namespace:e,client:r?.client??`${n}Client`,error:r?.error??`${n}Error`,timeoutError:r?.timeoutError??`${n}TimeoutError`,environment:r?.environment??`${n}Environment`,environmentUrls:r?.environmentUrls??`${n}EnvironmentUrls`,version:r?.version??`${n}Version`}}St();var tUt={};Z(tUt,{commons:()=>DXu,dynamic:()=>iho,generatorExec:()=>sho});var DXu={};var iho={};Z(iho,{ErrorSeverity:()=>LXu,HttpMethod:()=>jXu,ObjectPropertyAccess:()=>UXu,PrimitiveTypeV1:()=>zXu,auth:()=>RXu,commons:()=>FXu,declaration:()=>NXu,endpoints:()=>kXu,environment:()=>QXu,http:()=>tho,ir:()=>MXu,snippets:()=>rho,types:()=>nho,variables:()=>VXu});var RXu={};var FXu={};var NXu={};var kXu={};var QXu={};var tho={};Z(tho,{HttpMethod:()=>jXu});var jXu={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD"};var MXu={};var rho={};Z(rho,{ErrorSeverity:()=>LXu});var LXu={Critical:"CRITICAL",Warning:"WARNING"};var nho={};Z(nho,{ObjectPropertyAccess:()=>UXu,PrimitiveTypeV1:()=>zXu});var UXu={ReadOnly:"READ_ONLY",WriteOnly:"WRITE_ONLY"};var zXu={Integer:"INTEGER",Long:"LONG",Uint:"UINT",Uint64:"UINT_64",Float:"FLOAT",Double:"DOUBLE",Boolean:"BOOLEAN",String:"STRING",Date:"DATE",DateTime:"DATE_TIME",Uuid:"UUID",Base64:"BASE_64",BigInteger:"BIG_INTEGER"};var VXu={};var sho={};Z(sho,{LicenseId:()=>qXu,config:()=>oho});var oho={};Z(oho,{LicenseId:()=>qXu});var qXu={Mit:"MIT",Apache2:"Apache-2.0"};var zFm="value",wLn=class{context;constructor({context:t}){this.context=t}convert(t){let r=t.convertOpts;if(t.value===null)return this.context.isNullable(t.typeReference)?Ui.TypeLiteral.null():(this.context.errors.add({severity:Ir.Critical,message:"Expected non-null value, but got null"}),Ui.TypeLiteral.nop());if(t.value===void 0)return Ui.TypeLiteral.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value,convertOpts:r});case"literal":return this.convertLiteral({literalType:t.typeReference.value,value:t.value,convertOpts:r});case"map":return this.convertMap({map:t.typeReference,value:t.value,convertOpts:r});case"named":{let n=this.context.resolveNamedType({typeId:t.typeReference.value});return n==null?Ui.TypeLiteral.nop():this.convertNamed({named:n,value:t.value,as:t.as,convertOpts:r})}case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as,convertOpts:r});case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as,convertOpts:r});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as,convertOpts:r});case"set":return this.convertSet({set:t.typeReference.value,value:t.value,convertOpts:r});case"unknown":return this.convertUnknown({value:t.value,convertOpts:r});default:Be(t.typeReference)}}convertLiteral({literalType:t,value:r}){switch(t.type){case"boolean":{let n=this.context.getValueAsBoolean({value:r});return n==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.boolean(n)}case"string":{let n=this.context.getValueAsString({value:r});return n==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.string(n)}default:Be(t)}}convertList({list:t,value:r,convertOpts:n}){return Array.isArray(r)?Ui.TypeLiteral.array({values:r.map((i,o)=>{this.context.errors.scope({index:o});try{return this.convert({typeReference:t,value:i,convertOpts:n})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),Ui.TypeLiteral.nop())}convertSet({set:t,value:r,convertOpts:n}){return Array.isArray(r)?Ui.TypeLiteral.set({values:r.map((i,o)=>{this.context.errors.scope({index:o});try{return this.convert({typeReference:t,value:i,convertOpts:n})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),Ui.TypeLiteral.nop())}convertMap({map:t,value:r,convertOpts:n}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),Ui.TypeLiteral.nop()):Ui.TypeLiteral.record({entries:Object.entries(r).map(([i,o])=>{this.context.errors.scope(i);try{return{key:this.convert({typeReference:t.key,value:i,as:"key",convertOpts:n}),value:this.convert({typeReference:t.value,value:o,convertOpts:n})}}finally{this.context.errors.unscope()}})})}convertNamed({named:t,value:r,as:n,convertOpts:i}){switch(t.type){case"alias":return this.context.customConfig?.useBrandedStringAliases?Ui.TypeLiteral.reference(Ui.codeblock(o=>{o.writeNode(Ui.reference({name:this.context.namespaceExport,importFrom:this.context.getModuleImport(),memberName:this.context.getFullyQualifiedReference({declaration:t.declaration})})),o.write("("),o.writeNode(this.convert({typeReference:t.typeReference,value:r,as:n,convertOpts:i})),o.write(")")})):this.convert({typeReference:t.typeReference,value:r,as:n,convertOpts:i});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:r,convertOpts:i});case"enum":return this.convertEnum({enum_:t,value:r,convertOpts:i});case"object":return this.convertObject({object_:t,value:r,convertOpts:i});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,convertOpts:i});default:Be(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r,convertOpts:n}){let i=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(i==null)return Ui.TypeLiteral.nop();let o=i.singleDiscriminatedUnionType,s=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:i,unionVariant:o,convertOpts:n});if(s==null)return Ui.TypeLiteral.nop();if(this.context.customConfig?.includeUtilsOnUnionMembers)return Ui.TypeLiteral.reference(Ui.codeblock(u=>{u.writeNode(Ui.invokeMethod({on:Ui.reference({name:this.context.namespaceExport,importFrom:this.context.getModuleImport(),memberName:this.context.getFullyQualifiedReference({declaration:t.declaration})}),method:this.context.getMethodName(o.discriminantValue.name),arguments_:this.convertDiscriminatedUnionUtilsArgs({discriminatedUnionTypeInstance:i,unionVariant:o,unionProperties:s,convertOpts:n})}))}));let a={name:this.context.getPropertyName(t.discriminant.name),value:Ui.TypeLiteral.string(o.discriminantValue.wireValue)};return Ui.TypeLiteral.object({fields:[a,...s]})}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:t,unionVariant:r,convertOpts:n}){let i=this.getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r});switch(r.type){case"samePropertiesAsObject":{let o=this.context.resolveNamedType({typeId:r.typeId});if(o==null)return;let s=this.convertNamed({named:o,value:t.value,convertOpts:n});if(!s.isObject()){this.context.errors.add({severity:Ir.Critical,message:"Internal error; expected union value to be an object"});return}let a=s.asObjectOrThrow();return[...i,...a.fields]}case"singleProperty":try{this.context.errors.scope(r.discriminantValue.wireValue);let o=this.context.getRecord(t.value);return o==null?[...i,{name:zFm,value:this.convert({typeReference:r.typeReference,value:t.value,convertOpts:n})}]:[...i,{name:this.context.getPropertyName(r.discriminantValue.name),value:this.convert({typeReference:r.typeReference,value:o[r.discriminantValue.wireValue],convertOpts:n})}]}finally{this.context.errors.unscope()}case"noProperties":return i;default:Be(r)}}convertDiscriminatedUnionUtilsArgs({discriminatedUnionTypeInstance:t,unionVariant:r,unionProperties:n,convertOpts:i}){return r.type==="singleProperty"&&this.context.getRecord(t.value)==null&&n.length===1?[this.convert({typeReference:r.typeReference,value:t.value,convertOpts:i})]:n.length>0?[Ui.TypeLiteral.object({fields:n})]:[]}getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r,convertOpts:n}){return this.context.associateByWireValue({parameters:r.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(o=>{this.context.errors.scope(o.name.wireValue);try{return{name:this.context.getPropertyName(o.name.name),value:this.convert({...o,convertOpts:n})}}finally{this.context.errors.unscope()}})}convertObject({object_:t,value:r,convertOpts:n}){let i=this.context.associateByWireValue({parameters:this.filterReadWriteProperties(t.properties,n),values:this.context.getRecord(r)??{}});return Ui.TypeLiteral.object({fields:i.map(o=>{this.context.errors.scope(o.name.wireValue);try{return{name:this.context.getPropertyName(o.name.name),value:this.convert({...o,convertOpts:n})}}finally{this.context.errors.unscope()}})})}filterReadWriteProperties(t,r){return this.context.customConfig?.experimentalGenerateReadWriteOnlyTypes!==!0||typeof r>"u"||(r.isForRequest&&(t=t.filter(n=>n.propertyAccess!==tUt.dynamic.ObjectPropertyAccess.ReadOnly)),r.isForResponse&&(t=t.filter(n=>n.propertyAccess!==tUt.dynamic.ObjectPropertyAccess.WriteOnly))),t}convertEnum({enum_:t,value:r}){let n=this.getEnumValue({enum_:t,value:r});return n==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.string(n)}getEnumValue({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Ir.Critical,message:`Expected enum value string, got: ${typeof r}`});return}if(t.values.find(i=>i.wireValue===r)==null){this.context.errors.add({severity:Ir.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return r}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,convertOpts:n}){let i=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r,convertOpts:n});return i??Ui.TypeLiteral.nop()}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r,convertOpts:n}){for(let i of t.types){let o=this.context.errors.size();try{let s=this.convert({typeReference:i,value:r,convertOpts:n});if(Ui.TypeLiteral.isNop(s)){this.context.errors.truncate(o);continue}return s}catch{this.context.errors.truncate(o);continue}}this.context.errors.add({severity:Ir.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}convertUnknown({value:t,convertOpts:r}){return Ui.TypeLiteral.unknown(t)}convertPrimitive({primitive:t,value:r,as:n,convertOpts:i}){switch(t){case"INTEGER":case"UINT":{let o=this.getValueAsNumber({value:r,as:n});return o==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.number(o)}case"LONG":case"UINT_64":{let o=this.getValueAsNumber({value:r,as:n});return o==null?Ui.TypeLiteral.nop():this.context.customConfig?.useBigInt?Ui.TypeLiteral.bigint(BigInt(o)):Ui.TypeLiteral.number(o)}case"FLOAT":case"DOUBLE":{let o=this.getValueAsNumber({value:r});return o==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.number(o)}case"BOOLEAN":{let o=this.getValueAsBoolean({value:r,as:n});return o==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.boolean(o)}case"BASE_64":case"DATE":case"UUID":case"STRING":{let o=this.context.getValueAsString({value:r});return o==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.string(o)}case"DATE_TIME":{let o=this.context.getValueAsString({value:r});return o==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.datetime(o)}case"BIG_INTEGER":{let o=this.context.getValueAsString({value:r});return o==null?Ui.TypeLiteral.nop():this.context.customConfig?.useBigInt?Ui.TypeLiteral.bigint(BigInt(o)):Ui.TypeLiteral.string(o)}default:Be(t)}}getValueAsNumber({value:t,as:r}){let n=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:n})}};St();var CLn=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({body:t,value:r}){let n={fileFields:[],bodyPropertyFields:[]},i=this.context.getRecord(r)??{};for(let o of t.properties)switch(o.type){case"file":n.fileFields.push({name:this.context.getPropertyName(o.name),value:this.getSingleFileProperty({property:o,record:i})});break;case"fileArray":n.fileFields.push({name:this.context.getPropertyName(o.name),value:this.getArrayFileProperty({property:o,record:i})});break;case"bodyProperty":n.bodyPropertyFields.push({name:this.context.getPropertyName(o.name.name),value:this.getBodyProperty({property:o,record:i})});break;default:Be(o)}return n}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r});return n==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.blob(n)}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});return n==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.array({values:n.map(i=>Ui.TypeLiteral.blob(i))})}getBodyProperty({property:t,record:r}){let n=r[t.name.wireValue];return n==null?Ui.TypeLiteral.nop():this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:n})}};var xLn=class e extends $v{ir;customConfig;dynamicTypeLiteralMapper;filePropertyMapper;moduleName;namespaceExport;resolvedClientName;resolvedEnvironmentName;constructor({ir:t,config:r}){super({ir:t,config:r}),this.ir=t,this.customConfig=r.customConfig!=null?r.customConfig:void 0,this.dynamicTypeLiteralMapper=new wLn({context:this}),this.filePropertyMapper=new CLn({context:this}),this.moduleName=VFm({config:r,customConfig:this.customConfig}),this.namespaceExport=Zmo({organization:r.organization,workspaceName:r.workspaceName,namespaceExport:this.customConfig?.namespaceExport,naming:this.customConfig?.naming});let n=eho({namespaceExport:this.namespaceExport,naming:this.customConfig?.naming});this.resolvedClientName=n.client,this.resolvedEnvironmentName=n.environment}clone(){return new e({ir:this.ir,config:this.config})}getModuleImport(){return{type:"named",moduleName:this.moduleName}}getRootClientName(){return this.resolvedClientName}getPropertyName(t){return this.customConfig?.retainOriginalCasing||this.customConfig?.noSerdeLayer?this.formatOriginalPropertyName(t.originalName):t.camelCase.unsafeName}getMethodName(t){return t.camelCase.unsafeName}getTypeName(t){return t.pascalCase.unsafeName}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return this.getEnvironmentsTypeReference(r)}getFullyQualifiedReference({declaration:t}){return t.fernFilepath.allParts.length>0?`${t.fernFilepath.allParts.map(r=>r.camelCase.unsafeName).join(".")}.${this.getTypeName(t.name)}`:`${this.getTypeName(t.name)}`}getEnvironmentsTypeReference(t){return Ui.reference({name:this.resolvedEnvironmentName,importFrom:this.getModuleImport(),memberName:this.getTypeName(t)})}formatOriginalPropertyName(t){return t.includes("-")?`"${t}"`:t}};function VFm({config:e,customConfig:t}){return PXu({generatorConfig:e,isPackagePrivate:t?.private??!1})?.packageName??e.organization}St();var GXu="client",WXu="main",qFm={type:"primitive",value:"STRING"},_Ln=class{context;constructor({context:t}){this.context=t}async generateSnippet({endpoint:t,request:r}){return await this.buildCodeBlock({endpoint:t,snippet:r}).toStringAsync({customConfig:this.context.customConfig})}generateSnippetSync({endpoint:t,request:r}){return this.buildCodeBlock({endpoint:t,snippet:r}).toString({customConfig:this.context.customConfig})}async generateSnippetAst({endpoint:t,request:r}){return this.buildCodeBlock({endpoint:t,snippet:r})}buildCodeBlock({endpoint:t,snippet:r}){return Ui.codeblock(n=>{n.writeNode(Ui.function_({name:WXu,async:!0,parameters:[],body:Ui.codeblock(i=>{i.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),i.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))})})),n.writeNodeStatement(Ui.invokeFunction({function_:Ui.reference({name:WXu}),arguments_:[]}))})}constructClient({endpoint:t,snippet:r}){return Ui.variable({name:GXu,const:!0,initializer:Ui.instantiateClass({class_:Ui.reference({name:this.context.getRootClientName(),importFrom:this.context.getModuleImport()}),arguments_:[this.getConstructorArgs({endpoint:t,snippet:r})]})})}getConstructorArgs({endpoint:t,snippet:r}){let n=[],i=this.getConstructorEnvironmentArgs({baseUrl:r.baseURL,environment:r.environment});return i.length>0&&n.push(...i),t.auth!=null&&(r.auth!=null?n.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Ir.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`})),this.context.errors.scope(Lo.PathParameters),this.context.ir.pathParameters!=null&&n.push(...this.getPathParameters({namedParameters:this.context.ir.pathParameters,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),n.length===0?Ui.TypeLiteral.nop():Ui.TypeLiteral.object({fields:n})}getConstructorEnvironmentArgs({baseUrl:t,environment:r}){let n=this.getEnvironmentValue({baseUrl:t,environment:r});return n==null?[]:[{name:"environment",value:n}]}getEnvironmentValue({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null)return Ui.TypeLiteral.string(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);if(n==null){this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return Ui.TypeLiteral.reference(n)}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?Ui.TypeLiteral.object({fields:Object.entries(r).map(([n,i])=>({name:n,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:qFm,value:i})}))}):void 0}}getConstructorAuthArgs({auth:t,values:r}){switch(t.type){case"basic":return r.type!=="basic"?(this.addAuthMismatchError(t,r),[]):this.getConstructorBasicAuthArg({auth:t,values:r});case"bearer":return r.type!=="bearer"?(this.addAuthMismatchError(t,r),[]):this.getConstructorBearerAuthArgs({auth:t,values:r});case"header":return r.type!=="header"?(this.addAuthMismatchError(t,r),[]):this.getConstructorHeaderAuthArgs({auth:t,values:r});case"oauth":return r.type!=="oauth"?(this.addAuthMismatchError(t,r),[]):this.getConstructorOAuthArgs({auth:t,values:r});case"inferred":return r.type!=="inferred"?(this.addAuthMismatchError(t,r),[]):(this.addWarning("The TypeScript SDK v2 Generator does not support Inferred auth scheme yet"),[]);default:Be(t)}}addAuthMismatchError(t,r){this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:r}).message})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:r}){return[{name:this.context.getPropertyName(t.username),value:Ui.TypeLiteral.string(r.username)},{name:this.context.getPropertyName(t.password),value:Ui.TypeLiteral.string(r.password)}]}getConstructorBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.token),value:Ui.TypeLiteral.string(r.token)}]}getConstructorHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.header.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value})}]}getConstructorOAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.clientId),value:Ui.TypeLiteral.string(r.clientId)},{name:this.context.getPropertyName(t.clientSecret),value:Ui.TypeLiteral.string(r.clientSecret)}]}getConstructorHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getConstructorHeaderArg({header:i,value:o});s!=null&&n.push(s)}return n}getConstructorHeaderArg({header:t,value:r}){let n=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:r});if(!Ui.TypeLiteral.isNop(n))return{name:this.context.getPropertyName(t.name.name),value:n}}callMethod({endpoint:t,snippet:r}){return Ui.invokeMethod({on:Ui.reference({name:GXu}),method:this.getMethod({endpoint:t}),async:!0,arguments_:this.getMethodArgs({endpoint:t,snippet:r})})}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];return i.length>0&&n.push(...this.getPathParameters({namedParameters:i,snippet:r}).map(o=>o.value)),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),t.body!=null&&n.push(this.getBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope(),n}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,convertOpts:{isForRequest:!0}});default:Be(t)}}getBytesBodyRequestArg({value:t}){return typeof t!="string"?(this.context.errors.add({severity:Ir.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),Ui.TypeLiteral.nop()):Ui.TypeLiteral.blob(t)}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[],{inlinePathParameters:i,inlineFileProperties:o}={inlinePathParameters:this.context.customConfig?.inlinePathParameters??!1,inlineFileProperties:this.context.customConfig?.inlineFileProperties??!1};this.context.errors.scope(Lo.PathParameters);let s=[];t.pathParameters!=null&&s.push(...this.getPathParameters({namedParameters:t.pathParameters,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let a=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})||n.push(...s.map(u=>u.value)),o||n.push(...a.fileFields.map(u=>u.value)),this.context.needsRequestParameter({request:t,inlinePathParameters:i,inlineFileProperties:o})&&n.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})?s:[],filePropertyInfo:a})),n}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Lo.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...l,convertOpts:{isForRequest:!0}})}));this.context.errors.unscope(),this.context.errors.scope(Lo.Headers);let u=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...l,convertOpts:{isForRequest:!0}})}));this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let c=t.body!=null?this.getInlinedRequestBodyObjectFields({body:t.body,value:r.requestBody,filePropertyInfo:i}):[];return this.context.errors.unscope(),Ui.TypeLiteral.object({fields:[...n,...s,...u,...c]})}getInlinedRequestBodyObjectFields({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyObjectFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyObjectField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyObjectFields({filePropertyInfo:n});default:Be(t)}}getFileUploadRequestBodyObjectFields({filePropertyInfo:t}){return this.context.customConfig?.inlineFileProperties?[...t.fileFields,...t.bodyPropertyFields]:t.bodyPropertyFields}getReferencedRequestBodyPropertyObjectField({body:t,value:r}){return{name:this.context.getPropertyName(t.bodyKey),value:this.getReferencedRequestBodyPropertyTypeLiteral({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyTypeLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,convertOpts:{isForRequest:!0}});default:Be(t)}}getInlinedRequestBodyPropertyObjectFields({parameters:t,value:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...o,convertOpts:{isForRequest:!0}})});return n}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:r.pathParameters??{},ignoreMissingParameters:!0});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...o,convertOpts:{isForRequest:!0}})});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getMethodName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}};var rUt=class extends Wv{constructor({ir:t,config:r}){super(new xLn({ir:t,config:r}))}async generate(t){return super.generate(t)}generateSync(t){return super.generateSync(t)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new _Ln({context:t})}};var BLn=require("fs/promises"),$Xu=Ae(require("path"),1);var SLn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new rUt({ir:fS(this.ir),config:this.buildGeneratorConfig(this.generatorConfig)})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");for(let[n,i]of r.entries())try{let o=pS(i);if(o==null)continue;let s=await this.dynamicSnippetsGenerator.generate(o),a=this.getTestFilePath({outputDir:t,idx:n});await(0,BLn.mkdir)($Xu.default.dirname(a),{recursive:!0}),await(0,BLn.writeFile)(a,s.snippet)}catch(o){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(i.endpoint)}: ${o}`)}this.context.logger.debug("Done generating dynamic snippet tests")}getTestFilePath({outputDir:t,idx:r}){return Ge(t,Se.of(`src/dynamic-snippets/example${r}/snippet.ts`))}buildGeneratorConfig(t){let r=t.output.mode;if(r.type!=="github")throw new Error("GitHub output mode is required for TypeScript dynamic snippet tests");let n=r.publishInfo;if(!n||n.type!=="npm")throw new Error("NPM publish info is required for TypeScript dynamic snippet tests");return{...t,output:{...t.output,mode:{...r,publishInfo:{...n,packageName:"../.."}}}}}};var OLn=class e{context;testSuite;static GENERATORS={csharp:{generator:rMn},go:{generator:lMn},java:{generator:EMn},php:{generator:SMn},typescript:{generator:SLn,unstable:!0},python:{generator:NMn,unstable:!0},ruby:{generator:GMn},rust:{generator:nLn},swift:{generator:ILn}};constructor(t,r){this.context=t,this.testSuite=r}async generateTests({outputDir:t,language:r,skipUnstable:n}){let i=e.GENERATORS[r];if(i==null||i.unstable&&n){this.context.logger.debug(`Skipping dynamic snippets test generation for language "${r}"`);return}return new i.generator(this.context,this.testSuite.ir,this.testSuite.config).generateTests({outputDir:t,requests:this.testSuite.requests})}};async function HXu({ir:e,config:t}){if(e.dynamic==null)throw new Error("Internal error; dynamic IR is not available");return{ir:e.dynamic,config:t,requests:Object.values(e.dynamic.endpoints).flatMap(r=>(r.examples??[]).map(n=>({...n,baseUrl:"https://api.fern.com"})))}}async function KXu({context:e,ir:t,config:r,language:n,outputDir:i,skipUnstable:o}){let s=await HXu({ir:t,config:r});return new OLn(e,s).generateTests({language:n,outputDir:i,skipUnstable:o})}qt();var pZu=Ae(On(),1),aLe=require("fs/promises"),$dt=Ae(require("path"),1),Wdt=require("path"),fZu=Ae(YC(),1);e$();var XXu=Ae(Hc(),1),xB=Ae(pJu(),1),IQ=Ae($h(),1),ZXu=Ae(require("path"),1),GFm="0.0.1";function aho(e){if(e.raw?.github!=null&&typeof e.raw.github=="object"&&"license"in e.raw.github){let t=e.raw.github;if(t.license!=null){if(typeof t.license=="string")return{type:"basic",value:t.license};if(typeof t.license=="object"&&"custom"in t.license)return{type:"custom",value:t.license.custom}}}if(e.raw?.metadata?.license!=null){let t=e.raw.metadata.license;if(typeof t=="string")return{type:"basic",value:t};if(typeof t=="object"&&"custom"in t)return{type:"custom",value:t.custom}}}function WFm(e,t){let r=aho(e);if(r!=null){if(r.type==="basic"){if(r.value==="MIT"||r.value==="Apache-2.0")return xB.FernGeneratorExec.LicenseConfig.basic({id:r.value==="MIT"?xB.FernGeneratorExec.LicenseId.Mit:xB.FernGeneratorExec.LicenseId.Apache2})}else if(r.type==="custom")return xB.FernGeneratorExec.LicenseConfig.custom({filename:ZXu.basename(r.value)})}}function JXu(e){return e!=null?XXu.GithubPublishInfo._visit(e,{npm:t=>{let r=(t.token??"").trim(),n=r==="<USE_OIDC>"||r==="OIDC",i=r!=="";return xB.FernGeneratorExec.GithubPublishInfo.npm({registryUrl:t.registryUrl,packageName:t.packageName,tokenEnvironmentVariable:(0,IQ.EnvironmentVariable)(n?"<USE_OIDC>":r.startsWith("${")&&r.endsWith("}")?r.slice(2,-1).trim():""),shouldGeneratePublishWorkflow:n||i})},maven:t=>xB.FernGeneratorExec.GithubPublishInfo.maven({registryUrl:t.registryUrl,coordinate:t.coordinate,usernameEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.credentials?.username??""),passwordEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.credentials?.password??""),signature:t.signature!=null?{keyIdEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.signature.keyId??""),passwordEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.signature.password??""),secretKeyEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.signature.secretKey??"")}:void 0}),pypi:t=>xB.FernGeneratorExec.GithubPublishInfo.pypi({registryUrl:t.registryUrl,packageName:t.packageName,usernameEnvironmentVariable:(0,IQ.EnvironmentVariable)("PYPI_USERNAME"),passwordEnvironmentVariable:(0,IQ.EnvironmentVariable)("PYPI_PASSWORD"),pypiMetadata:t.pypiMetadata}),rubygems:t=>xB.FernGeneratorExec.GithubPublishInfo.rubygems({registryUrl:t.registryUrl,packageName:t.packageName,apiKeyEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.apiKey??"")}),postman:t=>xB.FernGeneratorExec.GithubPublishInfo.postman({apiKeyEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.apiKey??""),workspaceIdEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.workspaceId??"")}),nuget:t=>xB.FernGeneratorExec.GithubPublishInfo.nuget({registryUrl:t.registryUrl,packageName:t.packageName,apiKeyEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.apiKey??"")}),crates:t=>xB.FernGeneratorExec.GithubPublishInfo.crates({registryUrl:t.registryUrl,packageName:t.packageName,tokenEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.token??"")}),_other:()=>{}}):void 0}function eZu({generatorInvocation:e,customConfig:t,workspaceName:r,organization:n,outputVersion:i=GFm,absolutePathToSnippet:o,absolutePathToSnippetTemplates:s,absolutePathToFernConfig:a,writeUnitTests:u,generateOauthClients:c,generatePaginatedClients:l,whiteLabel:p,paths:d}){let f=WFm(e,a),{snippetPath:m,snippetTemplatePath:h,irPath:g,outputDirectory:A}=d,b=e.outputMode._visit({publish:v=>({...YXu(i,v,e,d),snippetFilepath:m,publishingMetadata:e.publishMetadata}),publishV2:v=>({...YXu(i,v,e,d),snippetFilepath:m,publishingMetadata:e.publishMetadata}),downloadFiles:()=>({mode:xB.FernGeneratorExec.OutputMode.downloadFiles(),path:A,snippetFilepath:m,publishingMetadata:e.publishMetadata}),github:v=>{let E={mode:xB.FernGeneratorExec.OutputMode.github({repoUrl:`https://github.com/${v.owner}/${v.repo}`,version:i,publishInfo:JXu(v.publishInfo),installationToken:void 0}),path:A,publishingMetadata:e.publishMetadata};return o!==void 0&&(E.snippetFilepath=m),s!==void 0&&(E.snippetTemplateFilepath=h),E},githubV2:v=>{let E=v._visit({commitAndRelease:w=>`https://github.com/${w.owner}/${w.repo}`,push:w=>`https://github.com/${w.owner}/${w.repo}`,pullRequest:w=>`https://github.com/${w.owner}/${w.repo}`,_other:()=>{throw new Error("Encountered unknown github mode")}}),I={mode:xB.FernGeneratorExec.OutputMode.github({repoUrl:E,version:i,publishInfo:JXu(v.publishInfo)}),path:A,publishingMetadata:e.publishMetadata};return o!==void 0&&(I.snippetFilepath=m),s!==void 0&&(I.snippetTemplateFilepath=h),I},_other:()=>{throw new Error("Output type did not match any of the types supported by Fern")}});return{irFilepath:g,output:b,publish:void 0,customConfig:t,workspaceName:r,organization:n,environment:xB.FernGeneratorExec.GeneratorEnvironment.local(),dryRun:!1,whitelabel:p??!1,writeUnitTests:u,generateOauthClients:c,generatePaginatedClients:l,license:f}}function YXu(e,t,r,n){let{outputDirectory:i}=n,o;"registryOverrides"in t?o=t.registryOverrides.maven??t.registryOverrides.npm:o!=null&&(o=t._visit({mavenOverride:a=>a,npmOverride:a=>a,pypiOverride:a=>a,rubyGemsOverride:a=>a,postman:a=>a,nugetOverride:a=>a,cratesOverride:a=>a,_other:()=>{}}));let s="";return r.raw?.github!=null&&(GAe(r.raw.github)?s=px(r.raw.github.uri).repoUrl:s=r.raw?.github.repository),{mode:xB.FernGeneratorExec.OutputMode.github({repoUrl:s,version:e}),path:i}}async function tZu({workspace:e,audiences:t,generatorInvocation:r,context:n,irVersionOverride:i,version:o,packageName:s,sourceConfig:a,includeOptionalRequestPropertyExamples:u,ir:c}){let l=c??Nh({workspace:e,audiences:t,generationLanguage:r.language,keywords:r.keywords,smartCasing:r.smartCasing,exampleGeneration:{includeOptionalRequestPropertyExamples:u,disabled:r.disableExamples},readme:r.readme,version:o,packageName:s,context:n,sourceResolver:new Rm(n,e),generationMetadata:{cliVersion:e.cliVersion,generatorName:r.name,generatorVersion:r.version,generatorConfig:r.config,originGitCommit:t$()}});a!=null&&(l.sourceConfig=a),l.generationMetadata={cliVersion:e.cliVersion,generatorName:r.name,generatorVersion:r.version,generatorConfig:r.config,originGitCommit:t$()},n.logger.debug("Generated IR");let p=await DFe(r).then(m=>m==null?void 0:"v"+m.toString()),d=i??p,f=d!=null?await aQe({intermediateRepresentation:l,context:n,version:d}):await m2t({intermediateRepresentation:l,context:n,targetGenerator:{name:r.name,version:r.version}});return{latest:l,migrated:f}}var iZu=require("@boundaryml/baml");var Hv=require("@boundaryml/baml");var Qne=require("@boundaryml/baml"),TLn=class{runtime;ctxManager;constructor(t,r){this.runtime=t,this.ctxManager=r}async AnalyzeSdkDiff(t,r,n,i,o,s){try{let a=s?.env?{...process.env,...s.env}:{...process.env},u=Object.fromEntries(Object.entries(a).filter(([l,p])=>p!==void 0)),c=s?.clientRegistry;return s?.client&&(c=c||new Qne.ClientRegistry,c.setPrimary(s.client)),await this.runtime.buildRequest("AnalyzeSdkDiff",{diff:t,language:r,previous_version:n,prior_changelog:i,spec_commit_message:o},this.ctxManager.cloneContext(),s?.tb?.__tb(),c,!1,u)}catch(a){throw(0,Qne.toBamlError)(a)}}async ConsolidateChangelog(t,r,n,i){try{let o=i?.env?{...process.env,...i.env}:{...process.env},s=Object.fromEntries(Object.entries(o).filter(([u,c])=>c!==void 0)),a=i?.clientRegistry;return i?.client&&(a=a||new Qne.ClientRegistry,a.setPrimary(i.client)),await this.runtime.buildRequest("ConsolidateChangelog",{raw_entries:t,version_bump:r,language:n},this.ctxManager.cloneContext(),i?.tb?.__tb(),a,!1,s)}catch(o){throw(0,Qne.toBamlError)(o)}}},PLn=class{runtime;ctxManager;constructor(t,r){this.runtime=t,this.ctxManager=r}async AnalyzeSdkDiff(t,r,n,i,o,s){try{let a=s?.env?{...process.env,...s.env}:{...process.env},u=Object.fromEntries(Object.entries(a).filter(([l,p])=>p!==void 0)),c=s?.clientRegistry;return s?.client&&(c=c||new Qne.ClientRegistry,c.setPrimary(s.client)),await this.runtime.buildRequest("AnalyzeSdkDiff",{diff:t,language:r,previous_version:n,prior_changelog:i,spec_commit_message:o},this.ctxManager.cloneContext(),s?.tb?.__tb(),c,!0,u)}catch(a){throw(0,Qne.toBamlError)(a)}}async ConsolidateChangelog(t,r,n,i){try{let o=i?.env?{...process.env,...i.env}:{...process.env},s=Object.fromEntries(Object.entries(o).filter(([u,c])=>c!==void 0)),a=i?.clientRegistry;return i?.client&&(a=a||new Qne.ClientRegistry,a.setPrimary(i.client)),await this.runtime.buildRequest("ConsolidateChangelog",{raw_entries:t,version_bump:r,language:n},this.ctxManager.cloneContext(),i?.tb?.__tb(),a,!0,s)}catch(o){throw(0,Qne.toBamlError)(o)}}};var nUt=require("@boundaryml/baml"),DLn=class{runtime;ctxManager;constructor(t,r){this.runtime=t,this.ctxManager=r}AnalyzeSdkDiff(t,r){try{let n=r?.env?{...process.env,...r.env}:{...process.env},i=Object.fromEntries(Object.entries(n).filter(([o,s])=>s!==void 0));return this.runtime.parseLlmResponse("AnalyzeSdkDiff",t,!1,this.ctxManager.cloneContext(),r?.tb?.__tb(),r?.clientRegistry,i)}catch(n){throw(0,nUt.toBamlError)(n)}}ConsolidateChangelog(t,r){try{let n=r?.env?{...process.env,...r.env}:{...process.env},i=Object.fromEntries(Object.entries(n).filter(([o,s])=>s!==void 0));return this.runtime.parseLlmResponse("ConsolidateChangelog",t,!1,this.ctxManager.cloneContext(),r?.tb?.__tb(),r?.clientRegistry,i)}catch(n){throw(0,nUt.toBamlError)(n)}}},RLn=class{runtime;ctxManager;constructor(t,r){this.runtime=t,this.ctxManager=r}AnalyzeSdkDiff(t,r){try{let n=r?.env?{...process.env,...r.env}:{...process.env},i=Object.fromEntries(Object.entries(n).filter(([o,s])=>s!==void 0));return this.runtime.parseLlmResponse("AnalyzeSdkDiff",t,!0,this.ctxManager.cloneContext(),r?.tb?.__tb(),r?.clientRegistry,i)}catch(n){throw(0,nUt.toBamlError)(n)}}ConsolidateChangelog(t,r){try{let n=r?.env?{...process.env,...r.env}:{...process.env},i=Object.fromEntries(Object.entries(n).filter(([o,s])=>s!==void 0));return this.runtime.parseLlmResponse("ConsolidateChangelog",t,!0,this.ctxManager.cloneContext(),r?.tb?.__tb(),r?.clientRegistry,i)}catch(n){throw(0,nUt.toBamlError)(n)}}};var FLn=require("@boundaryml/baml");var $Fm={"diff_analyzer.baml":`// SDK Diff Analyzer
2588
+ `);t.write(i.replaceAll("`","\\`")),t.writeNoIndent(o.replaceAll("`","\\`")),t.write("`")}writeIterable({writer:t,iterable:r}){let n=PFm({values:r.values});if(n.length===0){t.write("[]");return}t.writeLine("["),t.indent();for(let i of n)i.write(t),t.writeLine(",");t.dedent(),t.write("]")}writeRecord({writer:t,record:r}){let n=TFm({entries:r.entries});if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let i of n)i.key.write(t),t.write(": "),i.value.write(t),t.writeLine(",");t.dedent(),t.write("}")}writeObject({writer:t,object:r}){let n=OFm({fields:r.fields});if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let i of n)t.write(`${i.name}: `),i.value.write(t),t.writeLine(",");t.dedent(),t.write("}")}static array({values:t}){return new this({type:"array",values:t})}static bigint(t){return new this({type:"bigint",value:t})}static blob(t){return new this({type:"blob",value:t})}static boolean(t){return new this({type:"boolean",value:t})}static datetime(t){return new this({type:"datetime",value:t})}static number(t){return new this({type:"number",value:t})}static object({fields:t}){return new this({type:"object",fields:t})}static record({entries:t}){return new this({type:"record",entries:t})}static reference(t){return new this({type:"reference",value:t})}static set({values:t}){return new this({type:"set",values:t})}static string(t){return new this({type:"string",value:t})}static tuple({values:t}){return new this({type:"tuple",values:t})}static unknown(t){return new this({type:"unknown",value:t})}static null(){return new this({type:"null"})}static nop(){return new this({type:"nop"})}static isNop(t){return t.internalType.type==="nop"}writeUnknown({writer:t,value:r}){switch(typeof r){case"boolean":t.write(r.toString());return;case"string":t.write(r.includes('"')?`\`${r}\``:`"${r}"`);return;case"number":t.write(r.toString());return;case"object":if(r==null){t.write("null");return}if(Array.isArray(r)){this.writeUnknownArray({writer:t,value:r});return}this.writeUnknownObject({writer:t,value:r});return;default:throw new Error(`Internal error; unsupported unknown type: ${typeof r}`)}}writeUnknownArray({writer:t,value:r}){if(r.length===0){t.write("[]");return}t.writeLine("["),t.indent();for(let n of r)t.writeNode(e.unknown(n)),t.writeLine(",");t.dedent(),t.write("]")}writeUnknownObject({writer:t,value:r}){let n=Object.entries(r);if(n.length===0){t.write("{}");return}t.writeLine("{"),t.indent();for(let[i,o]of n)t.write(`${i}: `),t.writeNode(e.unknown(o)),t.writeLine(",");t.dedent(),t.write("}")}};function OFm({fields:e}){return e.filter(t=>!wfe.isNop(t.value))}function TFm({entries:e}){return e.filter(t=>!wfe.isNop(t.key)&&!wfe.isNop(t.value))}function PFm({values:e}){return e.filter(t=>!wfe.isNop(t))}var Ldt=class extends XA{args;constructor(t){super(),this.args=t}write(t){this.args.export&&t.write("export "),this.args.const?t.write("const "):t.write("let "),t.write(`${this.args.name} = `),t.writeNode(this.args.initializer)}};function RFm(e){return new Ndt(e)}function FFm(e){return new kdt(e)}function NFm(e){return new Fdt(e)}function kFm(e){return new Qdt(e)}function QFm(e){return new jdt(e)}function jFm(e){return new Mdt(e)}function MFm(e){return new sLe(e)}function LFm(e){return new Ldt(e)}function PXu({generatorConfig:e,isPackagePrivate:t}){let r=e.output.mode;switch(r.type){case"downloadFiles":return;case"publish":return{packageName:r.registriesV2.npm.packageName,version:r.version,private:t,publishInfo:{registryUrl:r.registriesV2.npm.registryUrl,token:r.registriesV2.npm.token},license:void 0,repoUrl:void 0};case"github":if(r.publishInfo!=null&&r.publishInfo.type!=="npm")throw new Error(`Expected to receive npm publish info but received ${r.publishInfo.type} instead`);return{packageName:r.publishInfo!=null?r.publishInfo.packageName:"",version:r.version,private:t,publishInfo:void 0,repoUrl:UFm(r.repoUrl),license:e.license?._visit({basic:n=>n.id,custom:n=>`See ${n.filename}`,_other:()=>{}})};default:throw new Error(`Encountered unknown output mode: ${r}`)}}function UFm(e){if(e!=null)return e.startsWith("https://github.com/")?`git+${e}`:e.startsWith("ssh://github.com/")?`github:${eUt(e).replace("ssh://github.com/","")}`:e.startsWith("https://bitbucket.org/")?`bitbucket:${eUt(e).replace("https://bitbucket.org/","")}`:e.startsWith("ssh://bitbucket.org/")?`bitbucket:${eUt(e).replace("ssh://bitbucket.org/","")}`:e.startsWith("https://gitlab.com/")?`gitlab:${eUt(e).replace("https://gitlab.com/","")}`:e.startsWith("ssh://gitlab.com/")?`gitlab:${eUt(e).replace("ssh://gitlab.com/","")}`:(e.startsWith("git+")||(e=`git+${e}`),e.endsWith(".git")||(e=`${e}.git`),e)}function eUt(e){return e.endsWith(".git")?e.slice(0,-4):e}Bi();function Zmo({organization:e,workspaceName:t,namespaceExport:r,naming:n}){return(typeof n=="string"?n:n?.namespace)??r??`${gc(qn(e))}${gc(qn(t))}`}function eho({namespaceExport:e,naming:t}){let r=typeof t=="string"?{}:t,n=t!=null?gc(qn(e)):e;return{namespace:e,client:r?.client??`${n}Client`,error:r?.error??`${n}Error`,timeoutError:r?.timeoutError??`${n}TimeoutError`,environment:r?.environment??`${n}Environment`,environmentUrls:r?.environmentUrls??`${n}EnvironmentUrls`,version:r?.version??`${n}Version`}}St();var tUt={};Z(tUt,{commons:()=>DXu,dynamic:()=>iho,generatorExec:()=>sho});var DXu={};var iho={};Z(iho,{ErrorSeverity:()=>LXu,HttpMethod:()=>jXu,ObjectPropertyAccess:()=>UXu,PrimitiveTypeV1:()=>zXu,auth:()=>RXu,commons:()=>FXu,declaration:()=>NXu,endpoints:()=>kXu,environment:()=>QXu,http:()=>tho,ir:()=>MXu,snippets:()=>rho,types:()=>nho,variables:()=>VXu});var RXu={};var FXu={};var NXu={};var kXu={};var QXu={};var tho={};Z(tho,{HttpMethod:()=>jXu});var jXu={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD"};var MXu={};var rho={};Z(rho,{ErrorSeverity:()=>LXu});var LXu={Critical:"CRITICAL",Warning:"WARNING"};var nho={};Z(nho,{ObjectPropertyAccess:()=>UXu,PrimitiveTypeV1:()=>zXu});var UXu={ReadOnly:"READ_ONLY",WriteOnly:"WRITE_ONLY"};var zXu={Integer:"INTEGER",Long:"LONG",Uint:"UINT",Uint64:"UINT_64",Float:"FLOAT",Double:"DOUBLE",Boolean:"BOOLEAN",String:"STRING",Date:"DATE",DateTime:"DATE_TIME",Uuid:"UUID",Base64:"BASE_64",BigInteger:"BIG_INTEGER"};var VXu={};var sho={};Z(sho,{LicenseId:()=>qXu,config:()=>oho});var oho={};Z(oho,{LicenseId:()=>qXu});var qXu={Mit:"MIT",Apache2:"Apache-2.0"};var zFm="value",wLn=class{context;constructor({context:t}){this.context=t}convert(t){let r=t.convertOpts;if(t.value===null)return this.context.isNullable(t.typeReference)?Ui.TypeLiteral.null():(this.context.errors.add({severity:Ir.Critical,message:"Expected non-null value, but got null"}),Ui.TypeLiteral.nop());if(t.value===void 0)return Ui.TypeLiteral.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value,convertOpts:r});case"literal":return this.convertLiteral({literalType:t.typeReference.value,value:t.value,convertOpts:r});case"map":return this.convertMap({map:t.typeReference,value:t.value,convertOpts:r});case"named":{let n=this.context.resolveNamedType({typeId:t.typeReference.value});return n==null?Ui.TypeLiteral.nop():this.convertNamed({named:n,value:t.value,as:t.as,convertOpts:r})}case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as,convertOpts:r});case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as,convertOpts:r});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as,convertOpts:r});case"set":return this.convertSet({set:t.typeReference.value,value:t.value,convertOpts:r});case"unknown":return this.convertUnknown({value:t.value,convertOpts:r});default:Be(t.typeReference)}}convertLiteral({literalType:t,value:r}){switch(t.type){case"boolean":{let n=this.context.getValueAsBoolean({value:r});return n==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.boolean(n)}case"string":{let n=this.context.getValueAsString({value:r});return n==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.string(n)}default:Be(t)}}convertList({list:t,value:r,convertOpts:n}){return Array.isArray(r)?Ui.TypeLiteral.array({values:r.map((i,o)=>{this.context.errors.scope({index:o});try{return this.convert({typeReference:t,value:i,convertOpts:n})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),Ui.TypeLiteral.nop())}convertSet({set:t,value:r,convertOpts:n}){return Array.isArray(r)?Ui.TypeLiteral.set({values:r.map((i,o)=>{this.context.errors.scope({index:o});try{return this.convert({typeReference:t,value:i,convertOpts:n})}finally{this.context.errors.unscope()}})}):(this.context.errors.add({severity:Ir.Critical,message:`Expected array but got: ${typeof r}`}),Ui.TypeLiteral.nop())}convertMap({map:t,value:r,convertOpts:n}){return typeof r!="object"||r==null?(this.context.errors.add({severity:Ir.Critical,message:`Expected object but got: ${r==null?"null":typeof r}`}),Ui.TypeLiteral.nop()):Ui.TypeLiteral.record({entries:Object.entries(r).map(([i,o])=>{this.context.errors.scope(i);try{return{key:this.convert({typeReference:t.key,value:i,as:"key",convertOpts:n}),value:this.convert({typeReference:t.value,value:o,convertOpts:n})}}finally{this.context.errors.unscope()}})})}convertNamed({named:t,value:r,as:n,convertOpts:i}){switch(t.type){case"alias":return this.context.customConfig?.useBrandedStringAliases?Ui.TypeLiteral.reference(Ui.codeblock(o=>{o.writeNode(Ui.reference({name:this.context.namespaceExport,importFrom:this.context.getModuleImport(),memberName:this.context.getFullyQualifiedReference({declaration:t.declaration})})),o.write("("),o.writeNode(this.convert({typeReference:t.typeReference,value:r,as:n,convertOpts:i})),o.write(")")})):this.convert({typeReference:t.typeReference,value:r,as:n,convertOpts:i});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:r,convertOpts:i});case"enum":return this.convertEnum({enum_:t,value:r,convertOpts:i});case"object":return this.convertObject({object_:t,value:r,convertOpts:i});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,convertOpts:i});default:Be(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:r,convertOpts:n}){let i=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:r});if(i==null)return Ui.TypeLiteral.nop();let o=i.singleDiscriminatedUnionType,s=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:i,unionVariant:o,convertOpts:n});if(s==null)return Ui.TypeLiteral.nop();if(this.context.customConfig?.includeUtilsOnUnionMembers)return Ui.TypeLiteral.reference(Ui.codeblock(u=>{u.writeNode(Ui.invokeMethod({on:Ui.reference({name:this.context.namespaceExport,importFrom:this.context.getModuleImport(),memberName:this.context.getFullyQualifiedReference({declaration:t.declaration})}),method:this.context.getMethodName(o.discriminantValue.name),arguments_:this.convertDiscriminatedUnionUtilsArgs({discriminatedUnionTypeInstance:i,unionVariant:o,unionProperties:s,convertOpts:n})}))}));let a={name:this.context.getPropertyName(t.discriminant.name),value:Ui.TypeLiteral.string(o.discriminantValue.wireValue)};return Ui.TypeLiteral.object({fields:[a,...s]})}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:t,unionVariant:r,convertOpts:n}){let i=this.getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r});switch(r.type){case"samePropertiesAsObject":{let o=this.context.resolveNamedType({typeId:r.typeId});if(o==null)return;let s=this.convertNamed({named:o,value:t.value,convertOpts:n});if(!s.isObject()){this.context.errors.add({severity:Ir.Critical,message:"Internal error; expected union value to be an object"});return}let a=s.asObjectOrThrow();return[...i,...a.fields]}case"singleProperty":try{this.context.errors.scope(r.discriminantValue.wireValue);let o=this.context.getRecord(t.value);return o==null?[...i,{name:zFm,value:this.convert({typeReference:r.typeReference,value:t.value,convertOpts:n})}]:[...i,{name:this.context.getPropertyName(r.discriminantValue.name),value:this.convert({typeReference:r.typeReference,value:o[r.discriminantValue.wireValue],convertOpts:n})}]}finally{this.context.errors.unscope()}case"noProperties":return i;default:Be(r)}}convertDiscriminatedUnionUtilsArgs({discriminatedUnionTypeInstance:t,unionVariant:r,unionProperties:n,convertOpts:i}){return r.type==="singleProperty"&&this.context.getRecord(t.value)==null&&n.length===1?[this.convert({typeReference:r.typeReference,value:t.value,convertOpts:i})]:n.length>0?[Ui.TypeLiteral.object({fields:n})]:[]}getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:r,convertOpts:n}){return this.context.associateByWireValue({parameters:r.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(o=>{this.context.errors.scope(o.name.wireValue);try{return{name:this.context.getPropertyName(o.name.name),value:this.convert({...o,convertOpts:n})}}finally{this.context.errors.unscope()}})}convertObject({object_:t,value:r,convertOpts:n}){let i=this.context.associateByWireValue({parameters:this.filterReadWriteProperties(t.properties,n),values:this.context.getRecord(r)??{}});return Ui.TypeLiteral.object({fields:i.map(o=>{this.context.errors.scope(o.name.wireValue);try{return{name:this.context.getPropertyName(o.name.name),value:this.convert({...o,convertOpts:n})}}finally{this.context.errors.unscope()}})})}filterReadWriteProperties(t,r){return this.context.customConfig?.experimentalGenerateReadWriteOnlyTypes!==!0||typeof r>"u"||(r.isForRequest&&(t=t.filter(n=>n.propertyAccess!==tUt.dynamic.ObjectPropertyAccess.ReadOnly)),r.isForResponse&&(t=t.filter(n=>n.propertyAccess!==tUt.dynamic.ObjectPropertyAccess.WriteOnly))),t}convertEnum({enum_:t,value:r}){let n=this.getEnumValue({enum_:t,value:r});return n==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.string(n)}getEnumValue({enum_:t,value:r}){if(typeof r!="string"){this.context.errors.add({severity:Ir.Critical,message:`Expected enum value string, got: ${typeof r}`});return}if(t.values.find(i=>i.wireValue===r)==null){this.context.errors.add({severity:Ir.Critical,message:`An enum value named "${r}" does not exist in this context`});return}return r}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:r,convertOpts:n}){let i=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r,convertOpts:n});return i??Ui.TypeLiteral.nop()}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:r,convertOpts:n}){for(let i of t.types){let o=this.context.errors.size();try{let s=this.convert({typeReference:i,value:r,convertOpts:n});if(Ui.TypeLiteral.isNop(s)){this.context.errors.truncate(o);continue}return s}catch{this.context.errors.truncate(o);continue}}this.context.errors.add({severity:Ir.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof r}" value`})}convertUnknown({value:t,convertOpts:r}){return Ui.TypeLiteral.unknown(t)}convertPrimitive({primitive:t,value:r,as:n,convertOpts:i}){switch(t){case"INTEGER":case"UINT":{let o=this.getValueAsNumber({value:r,as:n});return o==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.number(o)}case"LONG":case"UINT_64":{let o=this.getValueAsNumber({value:r,as:n});return o==null?Ui.TypeLiteral.nop():this.context.customConfig?.useBigInt?Ui.TypeLiteral.bigint(BigInt(o)):Ui.TypeLiteral.number(o)}case"FLOAT":case"DOUBLE":{let o=this.getValueAsNumber({value:r});return o==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.number(o)}case"BOOLEAN":{let o=this.getValueAsBoolean({value:r,as:n});return o==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.boolean(o)}case"BASE_64":case"DATE":case"UUID":case"STRING":{let o=this.context.getValueAsString({value:r});return o==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.string(o)}case"DATE_TIME":{let o=this.context.getValueAsString({value:r});return o==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.datetime(o)}case"BIG_INTEGER":{let o=this.context.getValueAsString({value:r});return o==null?Ui.TypeLiteral.nop():this.context.customConfig?.useBigInt?Ui.TypeLiteral.bigint(BigInt(o)):Ui.TypeLiteral.string(o)}default:Be(t)}}getValueAsNumber({value:t,as:r}){let n=r==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:n})}getValueAsBoolean({value:t,as:r}){let n=r==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:n})}};St();var CLn=class{context;constructor({context:t}){this.context=t}getFilePropertyInfo({body:t,value:r}){let n={fileFields:[],bodyPropertyFields:[]},i=this.context.getRecord(r)??{};for(let o of t.properties)switch(o.type){case"file":n.fileFields.push({name:this.context.getPropertyName(o.name),value:this.getSingleFileProperty({property:o,record:i})});break;case"fileArray":n.fileFields.push({name:this.context.getPropertyName(o.name),value:this.getArrayFileProperty({property:o,record:i})});break;case"bodyProperty":n.bodyPropertyFields.push({name:this.context.getPropertyName(o.name.name),value:this.getBodyProperty({property:o,record:i})});break;default:Be(o)}return n}getSingleFileProperty({property:t,record:r}){let n=this.context.getSingleFileValue({property:t,record:r});return n==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.blob(n)}getArrayFileProperty({property:t,record:r}){let n=this.context.getFileArrayValues({property:t,record:r});return n==null?Ui.TypeLiteral.nop():Ui.TypeLiteral.array({values:n.map(i=>Ui.TypeLiteral.blob(i))})}getBodyProperty({property:t,record:r}){let n=r[t.name.wireValue];return n==null?Ui.TypeLiteral.nop():this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:n})}};var xLn=class e extends $v{ir;customConfig;dynamicTypeLiteralMapper;filePropertyMapper;moduleName;namespaceExport;resolvedClientName;resolvedEnvironmentName;constructor({ir:t,config:r}){super({ir:t,config:r}),this.ir=t,this.customConfig=r.customConfig!=null?r.customConfig:void 0,this.dynamicTypeLiteralMapper=new wLn({context:this}),this.filePropertyMapper=new CLn({context:this}),this.moduleName=VFm({config:r,customConfig:this.customConfig}),this.namespaceExport=Zmo({organization:r.organization,workspaceName:r.workspaceName,namespaceExport:this.customConfig?.namespaceExport,naming:this.customConfig?.naming});let n=eho({namespaceExport:this.namespaceExport,naming:this.customConfig?.naming});this.resolvedClientName=n.client,this.resolvedEnvironmentName=n.environment}clone(){return new e({ir:this.ir,config:this.config})}getModuleImport(){return{type:"named",moduleName:this.moduleName}}getRootClientName(){return this.resolvedClientName}getPropertyName(t){return this.customConfig?.retainOriginalCasing||this.customConfig?.noSerdeLayer?this.formatOriginalPropertyName(t.originalName):t.camelCase.unsafeName}getMethodName(t){return t.camelCase.unsafeName}getTypeName(t){return t.pascalCase.unsafeName}getEnvironmentTypeReferenceFromID(t){let r=this.resolveEnvironmentName(t);if(r!=null)return this.getEnvironmentsTypeReference(r)}getFullyQualifiedReference({declaration:t}){return t.fernFilepath.allParts.length>0?`${t.fernFilepath.allParts.map(r=>r.camelCase.unsafeName).join(".")}.${this.getTypeName(t.name)}`:`${this.getTypeName(t.name)}`}getEnvironmentsTypeReference(t){return Ui.reference({name:this.resolvedEnvironmentName,importFrom:this.getModuleImport(),memberName:this.getTypeName(t)})}formatOriginalPropertyName(t){return t.includes("-")?`"${t}"`:t}};function VFm({config:e,customConfig:t}){return PXu({generatorConfig:e,isPackagePrivate:t?.private??!1})?.packageName??e.organization}St();var GXu="client",WXu="main",qFm={type:"primitive",value:"STRING"},_Ln=class{context;constructor({context:t}){this.context=t}async generateSnippet({endpoint:t,request:r}){return await this.buildCodeBlock({endpoint:t,snippet:r}).toStringAsync({customConfig:this.context.customConfig})}generateSnippetSync({endpoint:t,request:r}){return this.buildCodeBlock({endpoint:t,snippet:r}).toString({customConfig:this.context.customConfig})}async generateSnippetAst({endpoint:t,request:r}){return this.buildCodeBlock({endpoint:t,snippet:r})}buildCodeBlock({endpoint:t,snippet:r}){return Ui.codeblock(n=>{n.writeNode(Ui.function_({name:WXu,async:!0,parameters:[],body:Ui.codeblock(i=>{i.writeNodeStatement(this.constructClient({endpoint:t,snippet:r})),i.writeNodeStatement(this.callMethod({endpoint:t,snippet:r}))})})),n.writeNodeStatement(Ui.invokeFunction({function_:Ui.reference({name:WXu}),arguments_:[]}))})}constructClient({endpoint:t,snippet:r}){return Ui.variable({name:GXu,const:!0,initializer:Ui.instantiateClass({class_:Ui.reference({name:this.context.getRootClientName(),importFrom:this.context.getModuleImport()}),arguments_:[this.getConstructorArgs({endpoint:t,snippet:r})]})})}getConstructorArgs({endpoint:t,snippet:r}){let n=[],i=this.getConstructorEnvironmentArgs({baseUrl:r.baseURL,environment:r.environment});return i.length>0&&n.push(...i),t.auth!=null&&(r.auth!=null?n.push(...this.getConstructorAuthArgs({auth:t.auth,values:r.auth})):this.context.errors.add({severity:Ir.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`})),this.context.errors.scope(Lo.PathParameters),this.context.ir.pathParameters!=null&&n.push(...this.getPathParameters({namedParameters:this.context.ir.pathParameters,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.Headers),this.context.ir.headers!=null&&r.headers!=null&&n.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:r.headers})),this.context.errors.unscope(),n.length===0?Ui.TypeLiteral.nop():Ui.TypeLiteral.object({fields:n})}getConstructorEnvironmentArgs({baseUrl:t,environment:r}){let n=this.getEnvironmentValue({baseUrl:t,environment:r});return n==null?[]:[{name:"environment",value:n}]}getEnvironmentValue({baseUrl:t,environment:r}){if(t!=null&&r!=null){this.context.errors.add({severity:Ir.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null)return Ui.TypeLiteral.string(t);if(r!=null){if(this.context.isSingleEnvironmentID(r)){let n=this.context.getEnvironmentTypeReferenceFromID(r);if(n==null){this.context.errors.add({severity:Ir.Warning,message:`Environment ${JSON.stringify(r)} was not found`});return}return Ui.TypeLiteral.reference(n)}if(this.context.isMultiEnvironmentValues(r))return this.context.validateMultiEnvironmentUrlValues(r)?Ui.TypeLiteral.object({fields:Object.entries(r).map(([n,i])=>({name:n,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:qFm,value:i})}))}):void 0}}getConstructorAuthArgs({auth:t,values:r}){switch(t.type){case"basic":return r.type!=="basic"?(this.addAuthMismatchError(t,r),[]):this.getConstructorBasicAuthArg({auth:t,values:r});case"bearer":return r.type!=="bearer"?(this.addAuthMismatchError(t,r),[]):this.getConstructorBearerAuthArgs({auth:t,values:r});case"header":return r.type!=="header"?(this.addAuthMismatchError(t,r),[]):this.getConstructorHeaderAuthArgs({auth:t,values:r});case"oauth":return r.type!=="oauth"?(this.addAuthMismatchError(t,r),[]):this.getConstructorOAuthArgs({auth:t,values:r});case"inferred":return r.type!=="inferred"?(this.addAuthMismatchError(t,r),[]):(this.addWarning("The TypeScript SDK v2 Generator does not support Inferred auth scheme yet"),[]);default:Be(t)}}addAuthMismatchError(t,r){this.context.errors.add({severity:Ir.Critical,message:this.context.newAuthMismatchError({auth:t,values:r}).message})}addWarning(t){this.context.errors.add({severity:Ir.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:r}){return[{name:this.context.getPropertyName(t.username),value:Ui.TypeLiteral.string(r.username)},{name:this.context.getPropertyName(t.password),value:Ui.TypeLiteral.string(r.password)}]}getConstructorBearerAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.token),value:Ui.TypeLiteral.string(r.token)}]}getConstructorHeaderAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.header.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:r.value})}]}getConstructorOAuthArgs({auth:t,values:r}){return[{name:this.context.getPropertyName(t.clientId),value:Ui.TypeLiteral.string(r.clientId)},{name:this.context.getPropertyName(t.clientSecret),value:Ui.TypeLiteral.string(r.clientSecret)}]}getConstructorHeaderArgs({headers:t,values:r}){let n=[];for(let i of t){let o=r[i.name.wireValue],s=this.getConstructorHeaderArg({header:i,value:o});s!=null&&n.push(s)}return n}getConstructorHeaderArg({header:t,value:r}){let n=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:r});if(!Ui.TypeLiteral.isNop(n))return{name:this.context.getPropertyName(t.name.name),value:n}}callMethod({endpoint:t,snippet:r}){return Ui.invokeMethod({on:Ui.reference({name:GXu}),method:this.getMethod({endpoint:t}),async:!0,arguments_:this.getMethodArgs({endpoint:t,snippet:r})})}getMethodArgs({endpoint:t,snippet:r}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:r});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:r});default:Be(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:r}){let n=[];this.context.errors.scope(Lo.PathParameters);let i=[...this.context.ir.pathParameters??[],...t.pathParameters??[]];return i.length>0&&n.push(...this.getPathParameters({namedParameters:i,snippet:r}).map(o=>o.value)),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody),t.body!=null&&n.push(this.getBodyRequestArg({body:t.body,value:r.requestBody})),this.context.errors.unscope(),n}getBodyRequestArg({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,convertOpts:{isForRequest:!0}});default:Be(t)}}getBytesBodyRequestArg({value:t}){return typeof t!="string"?(this.context.errors.add({severity:Ir.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),Ui.TypeLiteral.nop()):Ui.TypeLiteral.blob(t)}getMethodArgsForInlinedRequest({request:t,snippet:r}){let n=[],{inlinePathParameters:i,inlineFileProperties:o}={inlinePathParameters:this.context.customConfig?.inlinePathParameters??!1,inlineFileProperties:this.context.customConfig?.inlineFileProperties??!1};this.context.errors.scope(Lo.PathParameters);let s=[];t.pathParameters!=null&&s.push(...this.getPathParameters({namedParameters:t.pathParameters,snippet:r})),this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let a=this.getFilePropertyInfo({request:t,snippet:r});return this.context.errors.unscope(),this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})||n.push(...s.map(u=>u.value)),o||n.push(...a.fileFields.map(u=>u.value)),this.context.needsRequestParameter({request:t,inlinePathParameters:i,inlineFileProperties:o})&&n.push(this.getInlinedRequestArg({request:t,snippet:r,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:i})?s:[],filePropertyInfo:a})),n}getFilePropertyInfo({request:t,snippet:r}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:r.requestBody})}getInlinedRequestArg({request:t,snippet:r,pathParameterFields:n,filePropertyInfo:i}){this.context.errors.scope(Lo.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:r.queryParameters??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...l,convertOpts:{isForRequest:!0}})}));this.context.errors.unscope(),this.context.errors.scope(Lo.Headers);let u=this.context.associateByWireValue({parameters:t.headers??[],values:r.headers??{}}).map(l=>({name:this.context.getPropertyName(l.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...l,convertOpts:{isForRequest:!0}})}));this.context.errors.unscope(),this.context.errors.scope(Lo.RequestBody);let c=t.body!=null?this.getInlinedRequestBodyObjectFields({body:t.body,value:r.requestBody,filePropertyInfo:i}):[];return this.context.errors.unscope(),Ui.TypeLiteral.object({fields:[...n,...s,...u,...c]})}getInlinedRequestBodyObjectFields({body:t,value:r,filePropertyInfo:n}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyObjectFields({parameters:t.value,value:r});case"referenced":return[this.getReferencedRequestBodyPropertyObjectField({body:t,value:r})];case"fileUpload":return this.getFileUploadRequestBodyObjectFields({filePropertyInfo:n});default:Be(t)}}getFileUploadRequestBodyObjectFields({filePropertyInfo:t}){return this.context.customConfig?.inlineFileProperties?[...t.fileFields,...t.bodyPropertyFields]:t.bodyPropertyFields}getReferencedRequestBodyPropertyObjectField({body:t,value:r}){return{name:this.context.getPropertyName(t.bodyKey),value:this.getReferencedRequestBodyPropertyTypeLiteral({body:t.bodyType,value:r})}}getReferencedRequestBodyPropertyTypeLiteral({body:t,value:r}){switch(t.type){case"bytes":return this.getBytesBodyRequestArg({value:r});case"typeReference":return this.context.dynamicTypeLiteralMapper.convert({typeReference:t.value,value:r,convertOpts:{isForRequest:!0}});default:Be(t)}}getInlinedRequestBodyPropertyObjectFields({parameters:t,value:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(r)??{}});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...o,convertOpts:{isForRequest:!0}})});return n}getPathParameters({namedParameters:t,snippet:r}){let n=[],i=this.context.associateByWireValue({parameters:t,values:r.pathParameters??{},ignoreMissingParameters:!0});for(let o of i)n.push({name:this.context.getPropertyName(o.name.name),value:this.context.dynamicTypeLiteralMapper.convert({...o,convertOpts:{isForRequest:!0}})});return n}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(r=>this.context.getMethodName(r)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}};var rUt=class extends Wv{constructor({ir:t,config:r}){super(new xLn({ir:t,config:r}))}async generate(t,r={}){return super.generate(t,r)}generateSync(t){return super.generateSync(t)}async generateSnippetAst(t){return super.generateSnippetAst(t)}createSnippetGenerator(t){return new _Ln({context:t})}};var BLn=require("fs/promises"),$Xu=Ae(require("path"),1);var SLn=class{context;ir;generatorConfig;dynamicSnippetsGenerator;constructor(t,r,n){this.context=t,this.ir=r,this.generatorConfig=n,this.dynamicSnippetsGenerator=new rUt({ir:fS(this.ir),config:this.buildGeneratorConfig(this.generatorConfig)})}async generateTests({outputDir:t,requests:r}){this.context.logger.debug("Generating dynamic snippet tests...");for(let[n,{endpointId:i,request:o}]of r.entries())try{let s=pS(o);if(s==null)continue;let a=await this.dynamicSnippetsGenerator.generate(s,{endpointId:i}),u=this.getTestFilePath({outputDir:t,idx:n});await(0,BLn.mkdir)($Xu.default.dirname(u),{recursive:!0}),await(0,BLn.writeFile)(u,a.snippet)}catch(s){this.context.logger.error(`Failed to generate dynamic snippet for endpoint ${JSON.stringify(o.endpoint)}: ${s}`)}this.context.logger.debug("Done generating dynamic snippet tests")}getTestFilePath({outputDir:t,idx:r}){return Ge(t,Se.of(`src/dynamic-snippets/example${r}/snippet.ts`))}buildGeneratorConfig(t){let r=t.output.mode;if(r.type!=="github")throw new Error("GitHub output mode is required for TypeScript dynamic snippet tests");let n=r.publishInfo;if(!n||n.type!=="npm")throw new Error("NPM publish info is required for TypeScript dynamic snippet tests");return{...t,output:{...t.output,mode:{...r,publishInfo:{...n,packageName:"../.."}}}}}};var OLn=class e{context;testSuite;static GENERATORS={csharp:{generator:rMn},go:{generator:lMn},java:{generator:EMn},php:{generator:SMn},typescript:{generator:SLn,unstable:!0},python:{generator:NMn,unstable:!0},ruby:{generator:GMn},rust:{generator:nLn},swift:{generator:ILn}};constructor(t,r){this.context=t,this.testSuite=r}async generateTests({outputDir:t,language:r,skipUnstable:n}){let i=e.GENERATORS[r];if(i==null||i.unstable&&n){this.context.logger.debug(`Skipping dynamic snippets test generation for language "${r}"`);return}return new i.generator(this.context,this.testSuite.ir,this.testSuite.config).generateTests({outputDir:t,requests:this.testSuite.requests})}};async function HXu({ir:e,config:t}){if(e.dynamic==null)throw new Error("Internal error; dynamic IR is not available");return{ir:e.dynamic,config:t,requests:Object.entries(e.dynamic.endpoints).flatMap(([r,n])=>(n.examples??[]).map(i=>({endpointId:r,request:{...i,baseUrl:"https://api.fern.com"}})))}}async function KXu({context:e,ir:t,config:r,language:n,outputDir:i,skipUnstable:o}){let s=await HXu({ir:t,config:r});return new OLn(e,s).generateTests({language:n,outputDir:i,skipUnstable:o})}qt();var pZu=Ae(On(),1),aLe=require("fs/promises"),$dt=Ae(require("path"),1),Wdt=require("path"),fZu=Ae(YC(),1);e$();var XXu=Ae(Hc(),1),xB=Ae(pJu(),1),IQ=Ae($h(),1),ZXu=Ae(require("path"),1),GFm="0.0.1";function aho(e){if(e.raw?.github!=null&&typeof e.raw.github=="object"&&"license"in e.raw.github){let t=e.raw.github;if(t.license!=null){if(typeof t.license=="string")return{type:"basic",value:t.license};if(typeof t.license=="object"&&"custom"in t.license)return{type:"custom",value:t.license.custom}}}if(e.raw?.metadata?.license!=null){let t=e.raw.metadata.license;if(typeof t=="string")return{type:"basic",value:t};if(typeof t=="object"&&"custom"in t)return{type:"custom",value:t.custom}}}function WFm(e,t){let r=aho(e);if(r!=null){if(r.type==="basic"){if(r.value==="MIT"||r.value==="Apache-2.0")return xB.FernGeneratorExec.LicenseConfig.basic({id:r.value==="MIT"?xB.FernGeneratorExec.LicenseId.Mit:xB.FernGeneratorExec.LicenseId.Apache2})}else if(r.type==="custom")return xB.FernGeneratorExec.LicenseConfig.custom({filename:ZXu.basename(r.value)})}}function JXu(e){return e!=null?XXu.GithubPublishInfo._visit(e,{npm:t=>{let r=(t.token??"").trim(),n=r==="<USE_OIDC>"||r==="OIDC",i=r!=="";return xB.FernGeneratorExec.GithubPublishInfo.npm({registryUrl:t.registryUrl,packageName:t.packageName,tokenEnvironmentVariable:(0,IQ.EnvironmentVariable)(n?"<USE_OIDC>":r.startsWith("${")&&r.endsWith("}")?r.slice(2,-1).trim():""),shouldGeneratePublishWorkflow:n||i})},maven:t=>xB.FernGeneratorExec.GithubPublishInfo.maven({registryUrl:t.registryUrl,coordinate:t.coordinate,usernameEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.credentials?.username??""),passwordEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.credentials?.password??""),signature:t.signature!=null?{keyIdEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.signature.keyId??""),passwordEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.signature.password??""),secretKeyEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.signature.secretKey??"")}:void 0}),pypi:t=>xB.FernGeneratorExec.GithubPublishInfo.pypi({registryUrl:t.registryUrl,packageName:t.packageName,usernameEnvironmentVariable:(0,IQ.EnvironmentVariable)("PYPI_USERNAME"),passwordEnvironmentVariable:(0,IQ.EnvironmentVariable)("PYPI_PASSWORD"),pypiMetadata:t.pypiMetadata}),rubygems:t=>xB.FernGeneratorExec.GithubPublishInfo.rubygems({registryUrl:t.registryUrl,packageName:t.packageName,apiKeyEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.apiKey??"")}),postman:t=>xB.FernGeneratorExec.GithubPublishInfo.postman({apiKeyEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.apiKey??""),workspaceIdEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.workspaceId??"")}),nuget:t=>xB.FernGeneratorExec.GithubPublishInfo.nuget({registryUrl:t.registryUrl,packageName:t.packageName,apiKeyEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.apiKey??"")}),crates:t=>xB.FernGeneratorExec.GithubPublishInfo.crates({registryUrl:t.registryUrl,packageName:t.packageName,tokenEnvironmentVariable:(0,IQ.EnvironmentVariable)(t.token??"")}),_other:()=>{}}):void 0}function eZu({generatorInvocation:e,customConfig:t,workspaceName:r,organization:n,outputVersion:i=GFm,absolutePathToSnippet:o,absolutePathToSnippetTemplates:s,absolutePathToFernConfig:a,writeUnitTests:u,generateOauthClients:c,generatePaginatedClients:l,whiteLabel:p,paths:d}){let f=WFm(e,a),{snippetPath:m,snippetTemplatePath:h,irPath:g,outputDirectory:A}=d,b=e.outputMode._visit({publish:v=>({...YXu(i,v,e,d),snippetFilepath:m,publishingMetadata:e.publishMetadata}),publishV2:v=>({...YXu(i,v,e,d),snippetFilepath:m,publishingMetadata:e.publishMetadata}),downloadFiles:()=>({mode:xB.FernGeneratorExec.OutputMode.downloadFiles(),path:A,snippetFilepath:m,publishingMetadata:e.publishMetadata}),github:v=>{let E={mode:xB.FernGeneratorExec.OutputMode.github({repoUrl:`https://github.com/${v.owner}/${v.repo}`,version:i,publishInfo:JXu(v.publishInfo),installationToken:void 0}),path:A,publishingMetadata:e.publishMetadata};return o!==void 0&&(E.snippetFilepath=m),s!==void 0&&(E.snippetTemplateFilepath=h),E},githubV2:v=>{let E=v._visit({commitAndRelease:w=>`https://github.com/${w.owner}/${w.repo}`,push:w=>`https://github.com/${w.owner}/${w.repo}`,pullRequest:w=>`https://github.com/${w.owner}/${w.repo}`,_other:()=>{throw new Error("Encountered unknown github mode")}}),I={mode:xB.FernGeneratorExec.OutputMode.github({repoUrl:E,version:i,publishInfo:JXu(v.publishInfo)}),path:A,publishingMetadata:e.publishMetadata};return o!==void 0&&(I.snippetFilepath=m),s!==void 0&&(I.snippetTemplateFilepath=h),I},_other:()=>{throw new Error("Output type did not match any of the types supported by Fern")}});return{irFilepath:g,output:b,publish:void 0,customConfig:t,workspaceName:r,organization:n,environment:xB.FernGeneratorExec.GeneratorEnvironment.local(),dryRun:!1,whitelabel:p??!1,writeUnitTests:u,generateOauthClients:c,generatePaginatedClients:l,license:f}}function YXu(e,t,r,n){let{outputDirectory:i}=n,o;"registryOverrides"in t?o=t.registryOverrides.maven??t.registryOverrides.npm:o!=null&&(o=t._visit({mavenOverride:a=>a,npmOverride:a=>a,pypiOverride:a=>a,rubyGemsOverride:a=>a,postman:a=>a,nugetOverride:a=>a,cratesOverride:a=>a,_other:()=>{}}));let s="";return r.raw?.github!=null&&(GAe(r.raw.github)?s=px(r.raw.github.uri).repoUrl:s=r.raw?.github.repository),{mode:xB.FernGeneratorExec.OutputMode.github({repoUrl:s,version:e}),path:i}}async function tZu({workspace:e,audiences:t,generatorInvocation:r,context:n,irVersionOverride:i,version:o,packageName:s,sourceConfig:a,includeOptionalRequestPropertyExamples:u,ir:c}){let l=c??Nh({workspace:e,audiences:t,generationLanguage:r.language,keywords:r.keywords,smartCasing:r.smartCasing,exampleGeneration:{includeOptionalRequestPropertyExamples:u,disabled:r.disableExamples},readme:r.readme,version:o,packageName:s,context:n,sourceResolver:new Rm(n,e),generationMetadata:{cliVersion:e.cliVersion,generatorName:r.name,generatorVersion:r.version,generatorConfig:r.config,originGitCommit:t$()}});a!=null&&(l.sourceConfig=a),l.generationMetadata={cliVersion:e.cliVersion,generatorName:r.name,generatorVersion:r.version,generatorConfig:r.config,originGitCommit:t$()},n.logger.debug("Generated IR");let p=await DFe(r).then(m=>m==null?void 0:"v"+m.toString()),d=i??p,f=d!=null?await aQe({intermediateRepresentation:l,context:n,version:d}):await m2t({intermediateRepresentation:l,context:n,targetGenerator:{name:r.name,version:r.version}});return{latest:l,migrated:f}}var iZu=require("@boundaryml/baml");var Hv=require("@boundaryml/baml");var Qne=require("@boundaryml/baml"),TLn=class{runtime;ctxManager;constructor(t,r){this.runtime=t,this.ctxManager=r}async AnalyzeSdkDiff(t,r,n,i,o,s){try{let a=s?.env?{...process.env,...s.env}:{...process.env},u=Object.fromEntries(Object.entries(a).filter(([l,p])=>p!==void 0)),c=s?.clientRegistry;return s?.client&&(c=c||new Qne.ClientRegistry,c.setPrimary(s.client)),await this.runtime.buildRequest("AnalyzeSdkDiff",{diff:t,language:r,previous_version:n,prior_changelog:i,spec_commit_message:o},this.ctxManager.cloneContext(),s?.tb?.__tb(),c,!1,u)}catch(a){throw(0,Qne.toBamlError)(a)}}async ConsolidateChangelog(t,r,n,i){try{let o=i?.env?{...process.env,...i.env}:{...process.env},s=Object.fromEntries(Object.entries(o).filter(([u,c])=>c!==void 0)),a=i?.clientRegistry;return i?.client&&(a=a||new Qne.ClientRegistry,a.setPrimary(i.client)),await this.runtime.buildRequest("ConsolidateChangelog",{raw_entries:t,version_bump:r,language:n},this.ctxManager.cloneContext(),i?.tb?.__tb(),a,!1,s)}catch(o){throw(0,Qne.toBamlError)(o)}}},PLn=class{runtime;ctxManager;constructor(t,r){this.runtime=t,this.ctxManager=r}async AnalyzeSdkDiff(t,r,n,i,o,s){try{let a=s?.env?{...process.env,...s.env}:{...process.env},u=Object.fromEntries(Object.entries(a).filter(([l,p])=>p!==void 0)),c=s?.clientRegistry;return s?.client&&(c=c||new Qne.ClientRegistry,c.setPrimary(s.client)),await this.runtime.buildRequest("AnalyzeSdkDiff",{diff:t,language:r,previous_version:n,prior_changelog:i,spec_commit_message:o},this.ctxManager.cloneContext(),s?.tb?.__tb(),c,!0,u)}catch(a){throw(0,Qne.toBamlError)(a)}}async ConsolidateChangelog(t,r,n,i){try{let o=i?.env?{...process.env,...i.env}:{...process.env},s=Object.fromEntries(Object.entries(o).filter(([u,c])=>c!==void 0)),a=i?.clientRegistry;return i?.client&&(a=a||new Qne.ClientRegistry,a.setPrimary(i.client)),await this.runtime.buildRequest("ConsolidateChangelog",{raw_entries:t,version_bump:r,language:n},this.ctxManager.cloneContext(),i?.tb?.__tb(),a,!0,s)}catch(o){throw(0,Qne.toBamlError)(o)}}};var nUt=require("@boundaryml/baml"),DLn=class{runtime;ctxManager;constructor(t,r){this.runtime=t,this.ctxManager=r}AnalyzeSdkDiff(t,r){try{let n=r?.env?{...process.env,...r.env}:{...process.env},i=Object.fromEntries(Object.entries(n).filter(([o,s])=>s!==void 0));return this.runtime.parseLlmResponse("AnalyzeSdkDiff",t,!1,this.ctxManager.cloneContext(),r?.tb?.__tb(),r?.clientRegistry,i)}catch(n){throw(0,nUt.toBamlError)(n)}}ConsolidateChangelog(t,r){try{let n=r?.env?{...process.env,...r.env}:{...process.env},i=Object.fromEntries(Object.entries(n).filter(([o,s])=>s!==void 0));return this.runtime.parseLlmResponse("ConsolidateChangelog",t,!1,this.ctxManager.cloneContext(),r?.tb?.__tb(),r?.clientRegistry,i)}catch(n){throw(0,nUt.toBamlError)(n)}}},RLn=class{runtime;ctxManager;constructor(t,r){this.runtime=t,this.ctxManager=r}AnalyzeSdkDiff(t,r){try{let n=r?.env?{...process.env,...r.env}:{...process.env},i=Object.fromEntries(Object.entries(n).filter(([o,s])=>s!==void 0));return this.runtime.parseLlmResponse("AnalyzeSdkDiff",t,!0,this.ctxManager.cloneContext(),r?.tb?.__tb(),r?.clientRegistry,i)}catch(n){throw(0,nUt.toBamlError)(n)}}ConsolidateChangelog(t,r){try{let n=r?.env?{...process.env,...r.env}:{...process.env},i=Object.fromEntries(Object.entries(n).filter(([o,s])=>s!==void 0));return this.runtime.parseLlmResponse("ConsolidateChangelog",t,!0,this.ctxManager.cloneContext(),r?.tb?.__tb(),r?.clientRegistry,i)}catch(n){throw(0,nUt.toBamlError)(n)}}};var FLn=require("@boundaryml/baml");var $Fm={"diff_analyzer.baml":`// SDK Diff Analyzer
2589
2589
  // Analyzes git diffs of SDK code and produces semantic commit messages and version bumps
2590
2590
 
2591
2591
  enum VersionBump {
@@ -3640,7 +3640,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
3640
3640
  Run ${be.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
3641
3641
  Run ${be.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),lJe(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function zjo({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!YSc(e))return;let i=t??"",o=e.filter(a=>a.isUpgradeAvailable);r!=null&&(o=o.slice(0,r+1));let s=o.sort((a,u)=>a.generatorName.localeCompare(u.generatorName)||a.currentVersion.localeCompare(u.currentVersion));for(let a of s)i+=`
3642
3642
  ${await uQh(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+be.dim(a.currentVersion)+be.reset(" \u2192 ")+be.green(a.latestVersion);return i+=`
3643
- `,n?lJe(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function uQh(e){let r=await new JSc.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 cQh({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let a={type:"singleApi",versions:{}};return await ZSc({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(u,c,l,p)=>{a.versions[c]==null&&(a.versions[c]={});let d=TRe(l.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${l.name}`);return}let f=await DO({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:p});f!=null&&(a.versions[c][l.name]={previousVersion:l.version,latestVersion:f})},generatorFilter:r,groupFilter:n}),a}let s={type:"multiApi",versions:{}};return await ZSc({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(a,u,c,l)=>{if(a==null)return;s.versions[a]==null&&(s.versions[a]={}),s.versions[a][u]==null&&(s.versions[a][u]={});let p=TRe(c.name);if(p==null){l.logger.debug(`Skipping unknown generator: ${c.name}`);return}let d=await DO({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:c.version,channel:i,includeMajor:o,context:l});d!=null&&(s.versions[a][u][c.name]={previousVersion:c.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),s}async function ZSc({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async s=>{let a=await zj({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let u=n!=null?Lx(n):void 0;for(let c of a.groups)if(!(i!=null&&c.groupName!==i))for(let l of c.generators)u!=null&&l.name!==u||await r(o.workspaceName,c.groupName,l,s)})}))}function e1c(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let u=ck(a.latestVersion,a.previousVersion);r.debug(`Latest version: ${a.latestVersion}. `+(u?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:u,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function GGn({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await cQh({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[u,c]of Object.entries(a.versions))s.push(...e1c(c,u,t.logger));else s.push(...e1c(a.versions,void 0,t.logger))}return s}async function bde({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:QEt(e.packageName,{version:t?"prerelease":"latest"})}var t1c=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],WGn=class{environment;sentryClient;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Wn.Info;isLocal;stdoutRedirector=new qGn;jsonMode=!1;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new PFe(t,r),this.isLocal=n??!1;let i=this.getPackageName(),o=this.getPackageVersion(),s=this.getCliName();(i==null||o==null||s==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:o,cliName:s},this.sentryClient=new VGn({release:`cli@${this.environment.packageVersion}`})}getPackageName(){return"fern-api"}getPackageVersion(){return"4.43.3"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${be.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new xm}failWithoutThrowing(t,r){this.didSucceed=!1,O1t({message:t,error:r,logger:this.logger})}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}writeJsonToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(JSON.stringify(t,null,2)+`
3643
+ `,n?lJe(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function uQh(e){let r=await new JSc.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 cQh({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let a={type:"singleApi",versions:{}};return await ZSc({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(u,c,l,p)=>{a.versions[c]==null&&(a.versions[c]={});let d=TRe(l.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${l.name}`);return}let f=await DO({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:p});f!=null&&(a.versions[c][l.name]={previousVersion:l.version,latestVersion:f})},generatorFilter:r,groupFilter:n}),a}let s={type:"multiApi",versions:{}};return await ZSc({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(a,u,c,l)=>{if(a==null)return;s.versions[a]==null&&(s.versions[a]={}),s.versions[a][u]==null&&(s.versions[a][u]={});let p=TRe(c.name);if(p==null){l.logger.debug(`Skipping unknown generator: ${c.name}`);return}let d=await DO({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:c.version,channel:i,includeMajor:o,context:l});d!=null&&(s.versions[a][u][c.name]={previousVersion:c.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),s}async function ZSc({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async s=>{let a=await zj({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let u=n!=null?Lx(n):void 0;for(let c of a.groups)if(!(i!=null&&c.groupName!==i))for(let l of c.generators)u!=null&&l.name!==u||await r(o.workspaceName,c.groupName,l,s)})}))}function e1c(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let u=ck(a.latestVersion,a.previousVersion);r.debug(`Latest version: ${a.latestVersion}. `+(u?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:u,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function GGn({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await cQh({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[u,c]of Object.entries(a.versions))s.push(...e1c(c,u,t.logger));else s.push(...e1c(a.versions,void 0,t.logger))}return s}async function bde({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:QEt(e.packageName,{version:t?"prerelease":"latest"})}var t1c=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],WGn=class{environment;sentryClient;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Wn.Info;isLocal;stdoutRedirector=new qGn;jsonMode=!1;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new PFe(t,r),this.isLocal=n??!1;let i=this.getPackageName(),o=this.getPackageVersion(),s=this.getCliName();(i==null||o==null||s==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:o,cliName:s},this.sentryClient=new VGn({release:`cli@${this.environment.packageVersion}`})}getPackageName(){return"fern-api"}getPackageVersion(){return"4.43.4"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${be.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new xm}failWithoutThrowing(t,r){this.didSucceed=!1,O1t({message:t,error:r,logger:this.logger})}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}writeJsonToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(JSON.stringify(t,null,2)+`
3644
3644
  `),this.jsonMode&&this.stdoutRedirector.redirect()}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await cJe()).flush(),await this.sentryClient.flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await XSc({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
3645
3645
  `)||(r+=`
3646
3646
  `),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=CJn(t.map(n=>n.type==="docs"?"docs":n.workspaceName??"api"),n=>n.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new $zt(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let n=this.addTaskWithInit(t).start(),i;try{i=await r(n)}catch(o){throw o.message.includes("globalThis")?(n.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),n.failWithoutThrowing()):n.failWithoutThrowing(void 0,o),new xm}finally{n.finish()}return i}async instrumentPostHogEvent(t){this.isLocal||(await cJe()).sendEvent(t)}async captureException(t){await this.sentryClient.captureException(t)}logger=oD((t,...r)=>this.log(t,...r));stderr=oD((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=r1c(t.type==="docs"?"docs":t.workspaceName??"api"),n=1+(this.longestWorkspaceName!=null?r1c(this.longestWorkspaceName):r).length,i=r.padEnd(n),o=t1c[this.numTasks++%t1c.length],s=be.hex(o)(i);return{...this.constructTaskInit(),logPrefix:s}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===ef.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let n=t.filter(i=>u1.indexOf(i.level)>=u1.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===Wn.Debug,stderr:r||this.jsonMode})}_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 bde({cliEnvironment:this.environment,includePreReleases:t}),n=ck(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},o=await GGn({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:o}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await Ljo({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:be.yellow("?"),style:{answer:i=>be.cyan(i),message:i=>be.bold(i),highlight:i=>be.cyan(i)}}})}catch(n){throw n?.name==="ExitPromptError"?(this.logger.info(`