fern-api 5.183.0 → 5.183.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +6 -6
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -536,7 +536,7 @@ For more information, see https://buildwithfern.com/learn/api-definition/introdu
|
|
|
536
536
|
`,s+1),c=a===-1?"":o.slice(a+1);String(n.stack).endsWith(c)||(n.stack+=`
|
|
537
537
|
`+o)}}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=vJ(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:o}=r;n!==void 0&&P9t.assertOptions(n,{silentJSONParsing:R8.transitional(R8.boolean),forcedJSONParsing:R8.transitional(R8.boolean),clarifyTimeoutError:R8.transitional(R8.boolean),legacyInterceptorReqResOrdering:R8.transitional(R8.boolean)},!1),i!=null&&(lr.isFunction(i)?r.paramsSerializer={serialize:i}:P9t.assertOptions(i,{encode:R8.function,serialize:R8.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),P9t.assertOptions(r,{baseUrl:R8.spelling("baseURL"),withXsrfToken:R8.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=o&&lr.merge(o.common,o[r.method]);o&&lr.forEach(["delete","get","head","post","put","patch","query","common"],m=>{delete o[m]}),r.headers=C0.concat(s,o);let a=[],c=!0;this.interceptors.request.forEach(function(g){if(typeof g.runWhen=="function"&&g.runWhen(r)===!1)return;c=c&&g.synchronous;let A=r.transitional||YSe;A&&A.legacyInterceptorReqResOrdering?a.unshift(g.fulfilled,g.rejected):a.push(g.fulfilled,g.rejected)});let u=[];this.interceptors.response.forEach(function(g){u.push(g.fulfilled,g.rejected)});let l,p=0,d;if(!c){let m=[sJr.bind(this),void 0];for(m.unshift(...a),m.push(...u),d=m.length,l=Promise.resolve(r);p<d;)l=l.then(m[p++],m[p++]);return l}d=a.length;let f=r;for(;p<d;){let m=a[p++],g=a[p++];try{f=m(f)}catch(A){g.call(this,A);break}}try{l=sJr.call(this,f)}catch(m){return Promise.reject(m)}for(p=0,d=u.length;p<d;)l=l.then(u[p++],u[p++]);return l}getUri(t){t=vJ(this.defaults,t);let r=eVe(t.baseURL,t.url,t.allowAbsoluteUrls);return ZUe(r,t.params,t.paramsSerializer)}};lr.forEach(["delete","get","head","options"],function(t){qut.prototype[t]=function(r,n){return this.request(vJ(n||{},{method:t,url:r,data:(n||{}).data}))}});lr.forEach(["post","put","patch","query"],function(t){function r(n){return function(o,s,a){return this.request(vJ(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:s}))}}qut.prototype[t]=r(),t!=="query"&&(qut.prototype[t+"Form"]=r(!0))});B9t=qut});var I8o,AVu,yVu=h(()=>{"use strict";$Ue();I8o=class e{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(i=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](i);n._listeners=null}),this.promise.then=i=>{let o,s=new Promise(a=>{n.subscribe(a),o=a}).then(i);return s.cancel=function(){n.unsubscribe(o)},s},t(function(o,s,a){n.reason||(n.reason=new D4(o,s,a),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new e(function(i){t=i}),cancel:t}}},AVu=I8o});function v8o(e){return function(r){return e.apply(null,r)}}var bVu=h(()=>{"use strict"});function C8o(e){return lr.isObject(e)&&e.isAxiosError===!0}var EVu=h(()=>{"use strict";ub()});var x8o,IVu,vVu=h(()=>{"use strict";x8o={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(x8o).forEach(([e,t])=>{x8o[t]=e});IVu=x8o});function CVu(e){let t=new B9t(e),r=f9t(B9t.prototype.request,t);return lr.extend(r,B9t.prototype,t,{allOwnKeys:!0}),lr.extend(r,t,null,{allOwnKeys:!0}),r.create=function(i){return CVu(vJ(e,i))},r}var AS,um,xVu=h(()=>{"use strict";ub();v5o();gVu();rJr();YKr();j5o();$Ue();yVu();Q5o();S9t();A9t();R4();bVu();EVu();EJ();b8o();vVu();AS=CVu(Uut);AS.Axios=B9t;AS.CanceledError=D4;AS.CancelToken=AVu;AS.isCancel=E9t;AS.VERSION=phe;AS.toFormData=JSe;AS.AxiosError=Ai;AS.Cancel=AS.CanceledError;AS.all=function(t){return Promise.all(t)};AS.spread=v8o;AS.isAxiosError=C8o;AS.mergeConfig=vJ;AS.AxiosHeaders=C0;AS.formToJSON=e=>JKr(lr.isHTMLForm(e)?new FormData(e):e);AS.getAdapter=oJr.getAdapter;AS.HttpStatusCode=IVu;AS.default=AS;um=AS});var kxv,R9t,Fxv,Nxv,jxv,zxv,Qxv,Mxv,Lxv,_xv,Uxv,Vxv,Gxv,qxv,Wxv,Hxv,Kxv,yM=h(()=>{"use strict";xVu();({Axios:kxv,AxiosError:R9t,CanceledError:Fxv,isCancel:Nxv,CancelToken:jxv,VERSION:zxv,all:Qxv,Cancel:Mxv,isAxiosError:Lxv,spread:_xv,toFormData:Uxv,AxiosHeaders:Vxv,HttpStatusCode:Gxv,formToJSON:qxv,getAdapter:Wxv,mergeConfig:Hxv,create:Kxv}=um)});function IDm(e,t,r){let n=t,i=t?t.next:e.head,o=new TGo(r,n,i,e);return o.next===void 0&&(e.tail=o),o.prev===void 0&&(e.head=o),e.length++,o}function vDm(e,t){e.tail=new TGo(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function CDm(e,t){e.head=new TGo(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}var n5u,ON,QJr,bGo,i5u,IGo,dVe,LJr,a5u,FJr,swe,PVu,c5u,fVe,h5u,tWt,wJ,tGo,b5u,uGo,PGo,S5u,BGo,Md,bS,RGo,iWt,tlt,EM,F5u,rWt,DGo,bM,FGo,cRm,uRm,SVu,lRm,pRm,fRm,mhe,hhe,XSe,cJr,D9t,uJr,wVu,lJr,TVu,CJ,Wut,ZT,k9t,Yut,$T,TN,eO,S8o,pJr,ek,GC,w8o,T8o,OVu,O8o,Yre,P8o,fJr,F9t,iVe,k4,N9t,dRm,mRm,hRm,gRm,o5u,ARm,yRm,bRm,AVe,ERm,cwe,OJ,j9t,Og,B8o,bhe,R8o,X8o,Z8o,H9t,dJr,elt,rlt,D8o,Xut,uwe,TJ,rwe,Xre,Zut,k8o,yhe,z9t,F8o,CJr,oVe,xJr,mVe,EGo,IRm,MJr,s5u,vRm,CRm,xRm,SRm,wRm,TRm,ORm,vGo,nWt,PRm,ene,BRm,BVu,RRm,N8o,hVe,mJr,j8o,CGo,u5u,DRm,kRm,l5u,FRm,NRm,p5u,jRm,zRm,QRm,MRm,LRm,_Rm,URm,VRm,f5u,d5u,GRm,SJr,qRm,m5u,_Jr,xGo,gVe,WRm,sVe,z8o,HRm,nwe,KRm,JRm,YRm,iwe,XRm,ZRm,$Rm,Q8o,eDm,aVe,NJr,tDm,rDm,nDm,iDm,Pf,oDm,UJr,sDm,$8o,eGo,aDm,D8,cVe,ghe,M8o,RVu,Zre,Q9t,ZSe,DVu,x0,Ahe,$Se,L8o,uVe,yS,hJr,gJr,_8o,kVu,FVu,M9t,U8o,AJr,Hut,ewe,yJr,lVe,bJr,EJr,NVu,cDm,eWt,K9t,uDm,A5u,lDm,pDm,VJr,y5u,fDm,jVu,SGo,GJr,wGo,dDm,mDm,zVu,hDm,E5u,gDm,QVu,MVu,LVu,rGo,_Vu,L9t,wJr,nGo,TJr,iGo,oGo,sGo,aGo,owe,jJr,cGo,V8o,$re,I5u,ADm,yDm,bDm,EDm,TGo,UVu,VVu,OJr,_9t,xJ,U9t,twe,pVe,V9t,IJr,SJ,G8o,PJr,GVu,lGo,pGo,BJr,RJr,qVu,q8o,DJr,v5u,W8o,qJr,OGo,xDm,SDm,C5u,x5u,wDm,TDm,WJr,ODm,w5u,T5u,WVu,O5u,P5u,B5u,PDm,BDm,RDm,HVu,R5u,fGo,zJr,DDm,D5u,kDm,k5u,N5u,HJr,FDm,NDm,dGo,j5u,jDm,zDm,H8o,KVu,Kut,QDm,MDm,LDm,_Dm,UDm,VDm,JVu,mGo,YVu,hGo,k8,gGo,AGo,kJr,XVu,ZVu,W9t,$Vu,e5u,K8o,awe,tO,vJr,t5u,Jut,J8o,Y8o,yGo,J9t,Y9t,X9t,Z9t,GDm,$9t,qDm,WDm,HDm,r5u,kGo,G9t,z5u,KDm,JDm,Q5u,YDm,XDm,ZDm,$Dm,ekm,q9t,Yxv,tkm,KJr=h(()=>{"use strict";n5u=ye(require("events"),1),ON=ye(require("fs"),1),QJr=require("events"),bGo=ye(require("stream"),1),i5u=require("string_decoder"),IGo=ye(require("path"),1),dVe=ye(require("fs"),1),LJr=require("path"),a5u=require("events"),FJr=ye(require("assert"),1),swe=require("buffer"),PVu=ye(require("zlib"),1),c5u=ye(require("zlib"),1),fVe=require("path"),h5u=require("path"),tWt=ye(require("fs"),1),wJ=ye(require("fs"),1),tGo=ye(require("path"),1),b5u=require("path"),uGo=ye(require("path"),1),PGo=ye(require("fs"),1),S5u=ye(require("assert"),1),BGo=require("crypto"),Md=ye(require("fs"),1),bS=ye(require("path"),1),RGo=ye(require("fs"),1),iWt=ye(require("fs"),1),tlt=ye(require("path"),1),EM=ye(require("fs"),1),F5u=ye(require("fs/promises"),1),rWt=ye(require("path"),1),DGo=require("path"),bM=ye(require("fs"),1),FGo=ye(require("path"),1),cRm=Object.defineProperty,uRm=(e,t)=>{for(var r in t)cRm(e,r,{get:t[r],enumerable:!0})},SVu=typeof process=="object"&&process?process:{stdout:null,stderr:null},lRm=e=>!!e&&typeof e=="object"&&(e instanceof AVe||e instanceof bGo.default||pRm(e)||fRm(e)),pRm=e=>!!e&&typeof e=="object"&&e instanceof QJr.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==bGo.default.Writable.prototype.pipe,fRm=e=>!!e&&typeof e=="object"&&e instanceof QJr.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",mhe=Symbol("EOF"),hhe=Symbol("maybeEmitEnd"),XSe=Symbol("emittedEnd"),cJr=Symbol("emittingEnd"),D9t=Symbol("emittedError"),uJr=Symbol("closed"),wVu=Symbol("read"),lJr=Symbol("flush"),TVu=Symbol("flushChunk"),CJ=Symbol("encoding"),Wut=Symbol("decoder"),ZT=Symbol("flowing"),k9t=Symbol("paused"),Yut=Symbol("resume"),$T=Symbol("buffer"),TN=Symbol("pipes"),eO=Symbol("bufferLength"),S8o=Symbol("bufferPush"),pJr=Symbol("bufferShift"),ek=Symbol("objectMode"),GC=Symbol("destroyed"),w8o=Symbol("error"),T8o=Symbol("emitData"),OVu=Symbol("emitEnd"),O8o=Symbol("emitEnd2"),Yre=Symbol("async"),P8o=Symbol("abort"),fJr=Symbol("aborted"),F9t=Symbol("signal"),iVe=Symbol("dataListeners"),k4=Symbol("discarded"),N9t=e=>Promise.resolve().then(e),dRm=e=>e(),mRm=e=>e==="end"||e==="finish"||e==="prefinish",hRm=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,gRm=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),o5u=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[Yut](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},ARm=class extends o5u{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,r){super(e,t,r),this.proxyErrors=n=>this.dest.emit("error",n),e.on("error",this.proxyErrors)}},yRm=e=>!!e.objectMode,bRm=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",AVe=class extends QJr.EventEmitter{[ZT]=!1;[k9t]=!1;[TN]=[];[$T]=[];[ek];[CJ];[Yre];[Wut];[mhe]=!1;[XSe]=!1;[cJr]=!1;[uJr]=!1;[D9t]=null;[eO]=0;[GC]=!1;[F9t];[fJr]=!1;[iVe]=0;[k4]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");yRm(t)?(this[ek]=!0,this[CJ]=null):bRm(t)?(this[CJ]=t.encoding,this[ek]=!1):(this[ek]=!1,this[CJ]=null),this[Yre]=!!t.async,this[Wut]=this[CJ]?new i5u.StringDecoder(this[CJ]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[$T]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[TN]});let{signal:r}=t;r&&(this[F9t]=r,r.aborted?this[P8o]():r.addEventListener("abort",()=>this[P8o]()))}get bufferLength(){return this[eO]}get encoding(){return this[CJ]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[ek]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Yre]}set async(e){this[Yre]=this[Yre]||!!e}[P8o](){this[fJr]=!0,this.emit("abort",this[F9t]?.reason),this.destroy(this[F9t]?.reason)}get aborted(){return this[fJr]}set aborted(e){}write(e,t,r){if(this[fJr])return!1;if(this[mhe])throw new Error("write after end");if(this[GC])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(r=t,t="utf8"),t||(t="utf8");let n=this[Yre]?N9t:dRm;if(!this[ek]&&!Buffer.isBuffer(e)){if(gRm(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(hRm(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[ek]?(this[ZT]&&this[eO]!==0&&this[lJr](!0),this[ZT]?this.emit("data",e):this[S8o](e),this[eO]!==0&&this.emit("readable"),r&&n(r),this[ZT]):e.length?(typeof e=="string"&&!(t===this[CJ]&&!this[Wut]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[CJ]&&(e=this[Wut].write(e)),this[ZT]&&this[eO]!==0&&this[lJr](!0),this[ZT]?this.emit("data",e):this[S8o](e),this[eO]!==0&&this.emit("readable"),r&&n(r),this[ZT]):(this[eO]!==0&&this.emit("readable"),r&&n(r),this[ZT])}read(e){if(this[GC])return null;if(this[k4]=!1,this[eO]===0||e===0||e&&e>this[eO])return this[hhe](),null;this[ek]&&(e=null),this[$T].length>1&&!this[ek]&&(this[$T]=[this[CJ]?this[$T].join(""):Buffer.concat(this[$T],this[eO])]);let t=this[wVu](e||null,this[$T][0]);return this[hhe](),t}[wVu](e,t){if(this[ek])this[pJr]();else{let r=t;e===r.length||e===null?this[pJr]():typeof r=="string"?(this[$T][0]=r.slice(e),t=r.slice(0,e),this[eO]-=e):(this[$T][0]=r.subarray(e),t=r.subarray(0,e),this[eO]-=e)}return this.emit("data",t),!this[$T].length&&!this[mhe]&&this.emit("drain"),t}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t="utf8"),e!==void 0&&this.write(e,t),r&&this.once("end",r),this[mhe]=!0,this.writable=!1,(this[ZT]||!this[k9t])&&this[hhe](),this}[Yut](){this[GC]||(!this[iVe]&&!this[TN].length&&(this[k4]=!0),this[k9t]=!1,this[ZT]=!0,this.emit("resume"),this[$T].length?this[lJr]():this[mhe]?this[hhe]():this.emit("drain"))}resume(){return this[Yut]()}pause(){this[ZT]=!1,this[k9t]=!0,this[k4]=!1}get destroyed(){return this[GC]}get flowing(){return this[ZT]}get paused(){return this[k9t]}[S8o](e){this[ek]?this[eO]+=1:this[eO]+=e.length,this[$T].push(e)}[pJr](){return this[ek]?this[eO]-=1:this[eO]-=this[$T][0].length,this[$T].shift()}[lJr](e=!1){do;while(this[TVu](this[pJr]())&&this[$T].length);!e&&!this[$T].length&&!this[mhe]&&this.emit("drain")}[TVu](e){return this.emit("data",e),this[ZT]}pipe(e,t){if(this[GC])return e;this[k4]=!1;let r=this[XSe];return t=t||{},e===SVu.stdout||e===SVu.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[TN].push(t.proxyErrors?new ARm(this,e,t):new o5u(this,e,t)),this[Yre]?N9t(()=>this[Yut]()):this[Yut]()),e}unpipe(e){let t=this[TN].find(r=>r.dest===e);t&&(this[TN].length===1?(this[ZT]&&this[iVe]===0&&(this[ZT]=!1),this[TN]=[]):this[TN].splice(this[TN].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let r=super.on(e,t);if(e==="data")this[k4]=!1,this[iVe]++,!this[TN].length&&!this[ZT]&&this[Yut]();else if(e==="readable"&&this[eO]!==0)super.emit("readable");else if(mRm(e)&&this[XSe])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[D9t]){let n=t;this[Yre]?N9t(()=>n.call(this,this[D9t])):n.call(this,this[D9t])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[iVe]=this.listeners("data").length,this[iVe]===0&&!this[k4]&&!this[TN].length&&(this[ZT]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[iVe]=0,!this[k4]&&!this[TN].length&&(this[ZT]=!1)),t}get emittedEnd(){return this[XSe]}[hhe](){!this[cJr]&&!this[XSe]&&!this[GC]&&this[$T].length===0&&this[mhe]&&(this[cJr]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[uJr]&&this.emit("close"),this[cJr]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==GC&&this[GC])return!1;if(e==="data")return!this[ek]&&!r?!1:this[Yre]?(N9t(()=>this[T8o](r)),!0):this[T8o](r);if(e==="end")return this[OVu]();if(e==="close"){if(this[uJr]=!0,!this[XSe]&&!this[GC])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[D9t]=r,super.emit(w8o,r);let i=!this[F9t]||this.listeners("error").length?super.emit("error",r):!1;return this[hhe](),i}else if(e==="resume"){let i=super.emit("resume");return this[hhe](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let n=super.emit(e,...t);return this[hhe](),n}[T8o](e){for(let r of this[TN])r.dest.write(e)===!1&&this.pause();let t=this[k4]?!1:super.emit("data",e);return this[hhe](),t}[OVu](){return this[XSe]?!1:(this[XSe]=!0,this.readable=!1,this[Yre]?(N9t(()=>this[O8o]()),!0):this[O8o]())}[O8o](){if(this[Wut]){let t=this[Wut].end();if(t){for(let r of this[TN])r.dest.write(t);this[k4]||super.emit("data",t)}}for(let t of this[TN])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[ek]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[ek]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[ek])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[CJ]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(GC,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[k4]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[mhe])return t();let n,i,o=u=>{this.off("data",s),this.off("end",a),this.off(GC,c),t(),i(u)},s=u=>{this.off("error",o),this.off("end",a),this.off(GC,c),this.pause(),n({value:u,done:!!this[mhe]})},a=()=>{this.off("error",o),this.off("data",s),this.off(GC,c),t(),n({done:!0,value:void 0})},c=()=>o(new Error("stream destroyed"));return new Promise((u,l)=>{i=l,n=u,this.once(GC,c),this.once("error",o),this.once("end",a),this.once("data",s)})},throw:t,return:t,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[k4]=!1;let e=!1,t=()=>(this.pause(),this.off(w8o,t),this.off(GC,t),this.off("end",t),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return t();let n=this.read();return n===null?t():{done:!1,value:n}};return this.once("end",t),this.once(w8o,t),this.once(GC,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[GC])return e?this.emit("error",e):this.emit(GC),this;this[GC]=!0,this[k4]=!0,this[$T].length=0,this[eO]=0;let t=this;return typeof t.close=="function"&&!this[uJr]&&t.close(),e?this.emit("error",e):this.emit(GC),this}static get isStream(){return lRm}},ERm=ON.default.writev,cwe=Symbol("_autoClose"),OJ=Symbol("_close"),j9t=Symbol("_ended"),Og=Symbol("_fd"),B8o=Symbol("_finished"),bhe=Symbol("_flags"),R8o=Symbol("_flush"),X8o=Symbol("_handleChunk"),Z8o=Symbol("_makeBuf"),H9t=Symbol("_mode"),dJr=Symbol("_needDrain"),elt=Symbol("_onerror"),rlt=Symbol("_onopen"),D8o=Symbol("_onread"),Xut=Symbol("_onwrite"),uwe=Symbol("_open"),TJ=Symbol("_path"),rwe=Symbol("_pos"),Xre=Symbol("_queue"),Zut=Symbol("_read"),k8o=Symbol("_readSize"),yhe=Symbol("_reading"),z9t=Symbol("_remain"),F8o=Symbol("_size"),CJr=Symbol("_write"),oVe=Symbol("_writing"),xJr=Symbol("_defaultFlag"),mVe=Symbol("_errored"),EGo=class extends AVe{[mVe]=!1;[Og];[TJ];[k8o];[yhe]=!1;[F8o];[z9t];[cwe];constructor(e,t){if(t=t||{},super(t),this.readable=!0,this.writable=!1,typeof e!="string")throw new TypeError("path must be a string");this[mVe]=!1,this[Og]=typeof t.fd=="number"?t.fd:void 0,this[TJ]=e,this[k8o]=t.readSize||16*1024*1024,this[yhe]=!1,this[F8o]=typeof t.size=="number"?t.size:1/0,this[z9t]=this[F8o],this[cwe]=typeof t.autoClose=="boolean"?t.autoClose:!0,typeof this[Og]=="number"?this[Zut]():this[uwe]()}get fd(){return this[Og]}get path(){return this[TJ]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[uwe](){ON.default.open(this[TJ],"r",(e,t)=>this[rlt](e,t))}[rlt](e,t){e?this[elt](e):(this[Og]=t,this.emit("open",t),this[Zut]())}[Z8o](){return Buffer.allocUnsafe(Math.min(this[k8o],this[z9t]))}[Zut](){if(!this[yhe]){this[yhe]=!0;let e=this[Z8o]();if(e.length===0)return process.nextTick(()=>this[D8o](null,0,e));ON.default.read(this[Og],e,0,e.length,null,(t,r,n)=>this[D8o](t,r,n))}}[D8o](e,t,r){this[yhe]=!1,e?this[elt](e):this[X8o](t,r)&&this[Zut]()}[OJ](){if(this[cwe]&&typeof this[Og]=="number"){let e=this[Og];this[Og]=void 0,ON.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}[elt](e){this[yhe]=!0,this[OJ](),this.emit("error",e)}[X8o](e,t){let r=!1;return this[z9t]-=e,e>0&&(r=super.write(e<t.length?t.subarray(0,e):t)),(e===0||this[z9t]<=0)&&(r=!1,this[OJ](),super.end()),r}emit(e,...t){switch(e){case"prefinish":case"finish":return!1;case"drain":return typeof this[Og]=="number"&&this[Zut](),!1;case"error":return this[mVe]?!1:(this[mVe]=!0,super.emit(e,...t));default:return super.emit(e,...t)}}},IRm=class extends EGo{[uwe](){let e=!0;try{this[rlt](null,ON.default.openSync(this[TJ],"r")),e=!1}finally{e&&this[OJ]()}}[Zut](){let e=!0;try{if(!this[yhe]){this[yhe]=!0;do{let t=this[Z8o](),r=t.length===0?0:ON.default.readSync(this[Og],t,0,t.length,null);if(!this[X8o](r,t))break}while(!0);this[yhe]=!1}e=!1}finally{e&&this[OJ]()}}[OJ](){if(this[cwe]&&typeof this[Og]=="number"){let e=this[Og];this[Og]=void 0,ON.default.closeSync(e),this.emit("close")}}},MJr=class extends n5u.default{readable=!1;writable=!0;[mVe]=!1;[oVe]=!1;[j9t]=!1;[Xre]=[];[dJr]=!1;[TJ];[H9t];[cwe];[Og];[xJr];[bhe];[B8o]=!1;[rwe];constructor(e,t){t=t||{},super(t),this[TJ]=e,this[Og]=typeof t.fd=="number"?t.fd:void 0,this[H9t]=t.mode===void 0?438:t.mode,this[rwe]=typeof t.start=="number"?t.start:void 0,this[cwe]=typeof t.autoClose=="boolean"?t.autoClose:!0;let r=this[rwe]!==void 0?"r+":"w";this[xJr]=t.flags===void 0,this[bhe]=t.flags===void 0?r:t.flags,this[Og]===void 0&&this[uwe]()}emit(e,...t){if(e==="error"){if(this[mVe])return!1;this[mVe]=!0}return super.emit(e,...t)}get fd(){return this[Og]}get path(){return this[TJ]}[elt](e){this[OJ](),this[oVe]=!0,this.emit("error",e)}[uwe](){ON.default.open(this[TJ],this[bhe],this[H9t],(e,t)=>this[rlt](e,t))}[rlt](e,t){this[xJr]&&this[bhe]==="r+"&&e&&e.code==="ENOENT"?(this[bhe]="w",this[uwe]()):e?this[elt](e):(this[Og]=t,this.emit("open",t),this[oVe]||this[R8o]())}end(e,t){return e&&this.write(e,t),this[j9t]=!0,!this[oVe]&&!this[Xre].length&&typeof this[Og]=="number"&&this[Xut](null,0),this}write(e,t){return typeof e=="string"&&(e=Buffer.from(e,t)),this[j9t]?(this.emit("error",new Error("write() after end()")),!1):this[Og]===void 0||this[oVe]||this[Xre].length?(this[Xre].push(e),this[dJr]=!0,!1):(this[oVe]=!0,this[CJr](e),!0)}[CJr](e){ON.default.write(this[Og],e,0,e.length,this[rwe],(t,r)=>this[Xut](t,r))}[Xut](e,t){e?this[elt](e):(this[rwe]!==void 0&&typeof t=="number"&&(this[rwe]+=t),this[Xre].length?this[R8o]():(this[oVe]=!1,this[j9t]&&!this[B8o]?(this[B8o]=!0,this[OJ](),this.emit("finish")):this[dJr]&&(this[dJr]=!1,this.emit("drain"))))}[R8o](){if(this[Xre].length===0)this[j9t]&&this[Xut](null,0);else if(this[Xre].length===1)this[CJr](this[Xre].pop());else{let e=this[Xre];this[Xre]=[],ERm(this[Og],e,this[rwe],(t,r)=>this[Xut](t,r))}}[OJ](){if(this[cwe]&&typeof this[Og]=="number"){let e=this[Og];this[Og]=void 0,ON.default.close(e,t=>t?this.emit("error",t):this.emit("close"))}}},s5u=class extends MJr{[uwe](){let e;if(this[xJr]&&this[bhe]==="r+")try{e=ON.default.openSync(this[TJ],this[bhe],this[H9t])}catch(t){if(t?.code==="ENOENT")return this[bhe]="w",this[uwe]();throw t}else e=ON.default.openSync(this[TJ],this[bhe],this[H9t]);this[rlt](null,e)}[OJ](){if(this[cwe]&&typeof this[Og]=="number"){let e=this[Og];this[Og]=void 0,ON.default.closeSync(e),this.emit("close")}}[CJr](e){let t=!0;try{this[Xut](null,ON.default.writeSync(this[Og],e,0,e.length,this[rwe])),t=!1}finally{if(t)try{this[OJ]()}catch{}}}},vRm=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),CRm=e=>!!e.sync&&!!e.file,xRm=e=>!e.sync&&!!e.file,SRm=e=>!!e.sync&&!e.file,wRm=e=>!e.sync&&!e.file,TRm=e=>!!e.file,ORm=e=>vRm.get(e)||e,vGo=(e={})=>{if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let i=ORm(r);t[i]=n}return t.chmod===void 0&&t.noChmod===!1&&(t.chmod=!0),delete t.noChmod,t},nWt=(e,t,r,n,i)=>Object.assign((o=[],s,a)=>{Array.isArray(o)&&(s=o,o={}),typeof s=="function"&&(a=s,s=void 0),s=s?Array.from(s):[];let c=vGo(o);if(i?.(c,s),CRm(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return e(c,s)}else if(xRm(c)){let u=t(c,s);return a?u.then(()=>a(),a):u}else if(SRm(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return r(c,s)}else if(wRm(c)){if(typeof a=="function")throw new TypeError("callback only supported with file option");return n(c,s)}throw new Error("impossible options??")},{syncFile:e,asyncFile:t,syncNoFile:r,asyncNoFile:n,validate:i}),PRm=c5u.default.constants||{ZLIB_VERNUM:4736},ene=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},PRm)),BRm=swe.Buffer.concat,BVu=Object.getOwnPropertyDescriptor(swe.Buffer,"concat"),RRm=e=>e,N8o=BVu?.writable===!0||BVu?.set!==void 0?e=>{swe.Buffer.concat=e?RRm:BRm}:e=>{},hVe=Symbol("_superWrite"),mJr=class extends Error{code;errno;constructor(e,t){super("zlib: "+e.message,{cause:e}),this.code=e.code,this.errno=e.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+e.message,Error.captureStackTrace(this,t??this.constructor)}get name(){return"ZlibError"}},j8o=Symbol("flushFlag"),CGo=class extends AVe{#e=!1;#t=!1;#r;#n;#i;#o;#s;get sawError(){return this.#e}get handle(){return this.#o}get flushFlag(){return this.#r}constructor(e,t){if(!e||typeof e!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(e),this.#r=e.flush??0,this.#n=e.finishFlush??0,this.#i=e.fullFlushFlag??0,typeof PVu[t]!="function")throw new TypeError("Compression method not supported: "+t);try{this.#o=new PVu[t](e)}catch(r){throw new mJr(r,this.constructor)}this.#s=r=>{this.#e||(this.#e=!0,this.close(),this.emit("error",r))},this.#o?.on("error",r=>this.#s(new mJr(r))),this.once("end",()=>this.close)}close(){this.#o&&(this.#o.close(),this.#o=void 0,this.emit("close"))}reset(){if(!this.#e)return(0,FJr.default)(this.#o,"zlib binding closed"),this.#o.reset?.()}flush(e){this.ended||(typeof e!="number"&&(e=this.#i),this.write(Object.assign(swe.Buffer.alloc(0),{[j8o]:e})))}end(e,t,r){return typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),e&&(t?this.write(e,t):this.write(e)),this.flush(this.#n),this.#t=!0,super.end(r)}get ended(){return this.#t}[hVe](e){return super.write(e)}write(e,t,r){if(typeof t=="function"&&(r=t,t="utf8"),typeof e=="string"&&(e=swe.Buffer.from(e,t)),this.#e)return;(0,FJr.default)(this.#o,"zlib binding closed");let n=this.#o._handle,i=n.close;n.close=()=>{};let o=this.#o.close;this.#o.close=()=>{},N8o(!0);let s;try{let c=typeof e[j8o]=="number"?e[j8o]:this.#r;s=this.#o._processChunk(e,c),N8o(!1)}catch(c){N8o(!1),this.#s(new mJr(c,this.write))}finally{this.#o&&(this.#o._handle=n,n.close=i,this.#o.close=o,this.#o.removeAllListeners("error"))}this.#o&&this.#o.on("error",c=>this.#s(new mJr(c,this.write)));let a;if(s)if(Array.isArray(s)&&s.length>0){let c=s[0];a=this[hVe](swe.Buffer.from(c));for(let u=1;u<s.length;u++)a=this[hVe](s[u])}else a=this[hVe](swe.Buffer.from(s));return r&&r(),a}},u5u=class extends CGo{#e;#t;constructor(e,t){e=e||{},e.flush=e.flush||ene.Z_NO_FLUSH,e.finishFlush=e.finishFlush||ene.Z_FINISH,e.fullFlushFlag=ene.Z_FULL_FLUSH,super(e,t),this.#e=e.level,this.#t=e.strategy}params(e,t){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==e||this.#t!==t){this.flush(ene.Z_SYNC_FLUSH),(0,FJr.default)(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(n,i)=>{typeof n=="function"&&(i=n,n=this.flushFlag),this.flush(n),i?.()};try{this.handle.params(e,t)}finally{this.handle.flush=r}this.handle&&(this.#e=e,this.#t=t)}}}},DRm=class extends u5u{#e;constructor(e){super(e,"Gzip"),this.#e=e&&!!e.portable}[hVe](e){return this.#e?(this.#e=!1,e[9]=255,super[hVe](e)):super[hVe](e)}},kRm=class extends u5u{constructor(e){super(e,"Unzip")}},l5u=class extends CGo{constructor(e,t){e=e||{},e.flush=e.flush||ene.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||ene.BROTLI_OPERATION_FINISH,e.fullFlushFlag=ene.BROTLI_OPERATION_FLUSH,super(e,t)}},FRm=class extends l5u{constructor(e){super(e,"BrotliCompress")}},NRm=class extends l5u{constructor(e){super(e,"BrotliDecompress")}},p5u=class extends CGo{constructor(e,t){e=e||{},e.flush=e.flush||ene.ZSTD_e_continue,e.finishFlush=e.finishFlush||ene.ZSTD_e_end,e.fullFlushFlag=ene.ZSTD_e_flush,super(e,t)}},jRm=class extends p5u{constructor(e){super(e,"ZstdCompress")}},zRm=class extends p5u{constructor(e){super(e,"ZstdDecompress")}},QRm=(e,t)=>{if(Number.isSafeInteger(e))e<0?LRm(e,t):MRm(e,t);else throw Error("cannot encode number outside of javascript safe integer range");return t},MRm=(e,t)=>{t[0]=128;for(var r=t.length;r>1;r--)t[r-1]=e&255,e=Math.floor(e/256)},LRm=(e,t)=>{t[0]=255;var r=!1;e=e*-1;for(var n=t.length;n>1;n--){var i=e&255;e=Math.floor(e/256),r?t[n-1]=f5u(i):i===0?t[n-1]=0:(r=!0,t[n-1]=d5u(i))}},_Rm=e=>{let t=e[0],r=t===128?VRm(e.subarray(1,e.length)):t===255?URm(e):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},URm=e=>{for(var t=e.length,r=0,n=!1,i=t-1;i>-1;i--){var o=Number(e[i]),s;n?s=f5u(o):o===0?s=o:(n=!0,s=d5u(o)),s!==0&&(r-=s*Math.pow(256,t-i-1))}return r},VRm=e=>{for(var t=e.length,r=0,n=t-1;n>-1;n--){var i=Number(e[n]);i!==0&&(r+=i*Math.pow(256,t-n-1))}return r},f5u=e=>(255^e)&255,d5u=e=>(255^e)+1&255,GRm={};uRm(GRm,{code:()=>xGo,isCode:()=>SJr,isName:()=>qRm,name:()=>_Jr,normalFsTypes:()=>m5u});SJr=e=>_Jr.has(e),qRm=e=>xGo.has(e),m5u=new Set(["0","","1","2","3","4","5","6","7","D"]),_Jr=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),xGo=new Map(Array.from(_Jr).map(e=>[e[1],e[0]])),gVe=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(e,t=0,r,n){Buffer.isBuffer(e)?this.decode(e,t||0,r,n):e&&this.#t(e)}decode(e,t,r,n){if(t||(t=0),!e||!(e.length>=t+512))throw new Error("need 512 bytes for header");let i=sVe(e,t+156,1),o=m5u.has(i),s=o?r:void 0,a=o?n:void 0;if(this.path=s?.path??sVe(e,t,100),this.mode=s?.mode??a?.mode??nwe(e,t+100,8),this.uid=s?.uid??a?.uid??nwe(e,t+108,8),this.gid=s?.gid??a?.gid??nwe(e,t+116,8),this.size=s?.size??a?.size??nwe(e,t+124,12),this.mtime=s?.mtime??a?.mtime??z8o(e,t+136,12),this.cksum=nwe(e,t+148,12),a&&this.#t(a,!0),s&&this.#t(s),SJr(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=sVe(e,t+157,100),e.subarray(t+257,t+265).toString()==="ustar\x0000")if(this.uname=s?.uname??a?.uname??sVe(e,t+265,32),this.gname=s?.gname??a?.gname??sVe(e,t+297,32),this.devmaj=s?.devmaj??a?.devmaj??nwe(e,t+329,8)??0,this.devmin=s?.devmin??a?.devmin??nwe(e,t+337,8)??0,e[t+475]!==0){let u=sVe(e,t+345,155);this.path=u+"/"+this.path}else{let u=sVe(e,t+345,130);u&&(this.path=u+"/"+this.path),this.atime=r?.atime??n?.atime??z8o(e,t+476,12),this.ctime=r?.ctime??n?.ctime??z8o(e,t+488,12)}let c=256;for(let u=t;u<t+148;u++)c+=e[u];for(let u=t+156;u<t+512;u++)c+=e[u];this.cksumValid=c===this.cksum,this.cksum===void 0&&c===256&&(this.nullBlock=!0)}#t(e,t=!1){Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t||r==="linkpath"&&t||r==="global"))))}encode(e,t=0){if(e||(e=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(e.length>=t+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,n=WRm(this.path||"",r),i=n[0],o=n[1];this.needPax=!!n[2],this.needPax=aVe(e,t,100,i)||this.needPax,this.needPax=iwe(e,t+100,8,this.mode)||this.needPax,this.needPax=iwe(e,t+108,8,this.uid)||this.needPax,this.needPax=iwe(e,t+116,8,this.gid)||this.needPax,this.needPax=iwe(e,t+124,12,this.size)||this.needPax,this.needPax=Q8o(e,t+136,12,this.mtime)||this.needPax,e[t+156]=Number(this.#e.codePointAt(0)),this.needPax=aVe(e,t+157,100,this.linkpath)||this.needPax,e.write("ustar\x0000",t+257,8),this.needPax=aVe(e,t+265,32,this.uname)||this.needPax,this.needPax=aVe(e,t+297,32,this.gname)||this.needPax,this.needPax=iwe(e,t+329,8,this.devmaj)||this.needPax,this.needPax=iwe(e,t+337,8,this.devmin)||this.needPax,this.needPax=aVe(e,t+345,r,o)||this.needPax,e[t+475]!==0?this.needPax=aVe(e,t+345,155,o)||this.needPax:(this.needPax=aVe(e,t+345,130,o)||this.needPax,this.needPax=Q8o(e,t+476,12,this.atime)||this.needPax,this.needPax=Q8o(e,t+488,12,this.ctime)||this.needPax);let s=256;for(let a=t;a<t+148;a++)s+=e[a];for(let a=t+156;a<t+512;a++)s+=e[a];return this.cksum=s,iwe(e,t+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:_Jr.get(this.#e)}get typeKey(){return this.#e}set type(e){let t=String(xGo.get(e));if(SJr(t)||t==="Unsupported")this.#e=t;else if(SJr(e))this.#e=e;else throw new TypeError("invalid entry type: "+e)}},WRm=(e,t)=>{let r=e,n="",i,o=fVe.posix.parse(e).root||".";if(Buffer.byteLength(r)<100)i=[r,n,!1];else{n=fVe.posix.dirname(r),r=fVe.posix.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(n)<=t?i=[r,n,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(n)<=t?i=[r.slice(0,99),n,!0]:(r=fVe.posix.join(fVe.posix.basename(n),r),n=fVe.posix.dirname(n));while(n!==o&&i===void 0);i||(i=[e.slice(0,99),"",!0])}return i},sVe=(e,t,r)=>e.subarray(t,t+r).toString("utf8").replace(/\0.*/,""),z8o=(e,t,r)=>HRm(nwe(e,t,r)),HRm=e=>e===void 0?void 0:new Date(e*1e3),nwe=(e,t,r)=>Number(e[t])&128?_Rm(e.subarray(t,t+r)):JRm(e,t,r),KRm=e=>isNaN(e)?void 0:e,JRm=(e,t,r)=>KRm(parseInt(e.subarray(t,t+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),YRm={12:8589934591,8:2097151},iwe=(e,t,r,n)=>n===void 0?!1:n>YRm[r]||n<0?(QRm(n,e.subarray(t,t+r)),!0):(XRm(e,t,r,n),!1),XRm=(e,t,r,n)=>e.write(ZRm(n,r),t,r,"ascii"),ZRm=(e,t)=>$Rm(Math.floor(e).toString(8),t),$Rm=(e,t)=>(e.length===t-1?e:new Array(t-e.length-1).join("0")+e+" ")+"\0",Q8o=(e,t,r,n)=>n===void 0?!1:iwe(e,t,r,n.getTime()/1e3),eDm=new Array(156).join("\0"),aVe=(e,t,r,n)=>n===void 0?!1:(e.write(n+eDm,t,r,"utf8"),n.length!==Buffer.byteLength(n)||n.length>r),NJr=class g5u{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(t,r=!1){this.atime=t.atime,this.charset=t.charset,this.comment=t.comment,this.ctime=t.ctime,this.dev=t.dev,this.gid=t.gid,this.global=r,this.gname=t.gname,this.ino=t.ino,this.linkpath=t.linkpath,this.mtime=t.mtime,this.nlink=t.nlink,this.path=t.path,this.size=t.size,this.uid=t.uid,this.uname=t.uname}encode(){let t=this.encodeBody();if(t==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(t),n=512*Math.ceil(1+r/512),i=Buffer.allocUnsafe(n);for(let o=0;o<512;o++)i[o]=0;new gVe({path:("PaxHeader/"+(0,h5u.basename)(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(i),i.write(t,512,r,"utf8");for(let o=r+512;o<i.length;o++)i[o]=0;return i}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(t){if(this[t]===void 0)return"";let r=this[t],n=r instanceof Date?r.getTime()/1e3:r,i=" "+(t==="dev"||t==="ino"||t==="nlink"?"SCHILY.":"")+t+"="+n+`
|
|
538
538
|
`,o=Buffer.byteLength(i),s=Math.floor(Math.log(o)/Math.log(10))+1;return o+s>=Math.pow(10,s)&&(s+=1),s+o+i}static parse(t,r,n=!1){return new g5u(tDm(rDm(t),r),n)}},tDm=(e,t)=>t?Object.assign({},t,e):e,rDm=e=>e.replace(/\n$/,"").split(`
|
|
539
|
-
`).reduce(nDm,Object.create(null)),nDm=(e,t)=>{let r=parseInt(t,10);if(r!==Buffer.byteLength(t)+1)return e;t=t.slice((r+" ").length);let n=t.split("="),i=n.shift();if(!i)return e;let o=i.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),s=n.join("=");return e[o]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(o)?new Date(Number(s)*1e3):/^[0-9]+$/.test(s)?+s:s,e},iDm=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Pf=iDm!=="win32"?e=>e:e=>e&&e.replaceAll(/\\/g,"/"),oDm=class extends AVe{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(e,t,r){switch(super({}),this.pause(),this.extended=t,this.globalExtended=r,this.header=e,this.remain=e.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=e.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!e.path)throw new Error("no path provided for tar.ReadEntry");this.path=Pf(e.path),this.mode=e.mode,this.mode&&(this.mode=this.mode&4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=this.remain,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=e.linkpath?Pf(e.linkpath):void 0,this.uname=e.uname,this.gname=e.gname,t&&this.#e(t),r&&this.#e(r,!0)}write(e){let t=e.length;if(t>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,n=this.blockRemain;return this.remain=Math.max(0,r-t),this.blockRemain=Math.max(0,n-t),this.ignore?!0:r>=t?super.write(e):super.write(e.subarray(0,r))}#e(e,t=!1){e.path&&(e.path=Pf(e.path)),e.linkpath&&(e.linkpath=Pf(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t))))}},UJr=(e,t,r,n={})=>{e.file&&(n.file=e.file),e.cwd&&(n.cwd=e.cwd),n.code=r instanceof Error&&r.code||t,n.tarCode=t,!e.strict&&n.recoverable!==!1?(r instanceof Error&&(n=Object.assign(r,n),r=r.message),e.emit("warn",t,r,n)):r instanceof Error?e.emit("error",Object.assign(r,n)):e.emit("error",Object.assign(new Error(`${t}: ${r}`),n))},sDm=1024*1024,$8o=Buffer.from([31,139]),eGo=Buffer.from([40,181,47,253]),aDm=Math.max($8o.length,eGo.length),D8=Symbol("state"),cVe=Symbol("writeEntry"),ghe=Symbol("readEntry"),M8o=Symbol("nextEntry"),RVu=Symbol("processEntry"),Zre=Symbol("extendedHeader"),Q9t=Symbol("globalExtendedHeader"),ZSe=Symbol("meta"),DVu=Symbol("emitMeta"),x0=Symbol("buffer"),Ahe=Symbol("queue"),$Se=Symbol("ended"),L8o=Symbol("emittedEnd"),uVe=Symbol("emit"),yS=Symbol("unzip"),hJr=Symbol("consumeChunk"),gJr=Symbol("consumeChunkSub"),_8o=Symbol("consumeBody"),kVu=Symbol("consumeMeta"),FVu=Symbol("consumeHeader"),M9t=Symbol("consuming"),U8o=Symbol("bufferConcat"),AJr=Symbol("maybeEnd"),Hut=Symbol("writing"),ewe=Symbol("aborted"),yJr=Symbol("onDone"),lVe=Symbol("sawValidEntry"),bJr=Symbol("sawNullBlock"),EJr=Symbol("sawEOF"),NVu=Symbol("closeStream"),cDm=()=>!0,eWt=class extends a5u.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Ahe]=[];[x0];[ghe];[cVe];[D8]="begin";[ZSe]="";[Zre];[Q9t];[$Se]=!1;[yS];[ewe]=!1;[lVe];[bJr]=!1;[EJr]=!1;[Hut]=!1;[M9t]=!1;[L8o]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(yJr,()=>{(this[D8]==="begin"||this[lVe]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(yJr,e.ondone):this.on(yJr,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||sDm,this.filter=typeof e.filter=="function"?e.filter:cDm;let t=e.file&&(e.file.endsWith(".tar.br")||e.file.endsWith(".tbr"));this.brotli=!(e.gzip||e.zstd)&&e.brotli!==void 0?e.brotli:t?void 0:!1;let r=e.file&&(e.file.endsWith(".tar.zst")||e.file.endsWith(".tzst"));this.zstd=!(e.gzip||e.brotli)&&e.zstd!==void 0?e.zstd:r?!0:void 0,this.on("end",()=>this[NVu]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,r={}){UJr(this,e,t,r)}[FVu](e,t){this[lVe]===void 0&&(this[lVe]=!1);let r;try{r=new gVe(e,t,this[Zre],this[Q9t])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[bJr]?(this[EJr]=!0,this[D8]==="begin"&&(this[D8]="header"),this[uVe]("eof")):(this[bJr]=!0,this[uVe]("nullBlock"));else if(this[bJr]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let n=r.type;if(/^(Symbolic)?Link$/.test(n)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(n)&&!/^(Global)?ExtendedHeader$/.test(n)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let i=this[cVe]=new oDm(r,this[Zre],this[Q9t]);if(!this[lVe])if(i.remain){let o=()=>{i.invalid||(this[lVe]=!0)};i.on("end",o)}else this[lVe]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[uVe]("ignoredEntry",i),this[D8]="ignore",i.resume()):i.size>0&&(this[ZSe]="",i.on("data",o=>this[ZSe]+=o),this[D8]="meta"):(this[Zre]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[uVe]("ignoredEntry",i),this[D8]=i.remain?"ignore":"header",i.resume()):(i.remain?this[D8]="body":(this[D8]="header",i.end()),this[ghe]?this[Ahe].push(i):(this[Ahe].push(i),this[M8o]())))}}}[NVu](){queueMicrotask(()=>this.emit("close"))}[RVu](e){let t=!0;if(!e)this[ghe]=void 0,t=!1;else if(Array.isArray(e)){let[r,...n]=e;this.emit(r,...n)}else this[ghe]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[M8o]()),t=!1);return t}[M8o](){do;while(this[RVu](this[Ahe].shift()));if(this[Ahe].length===0){let e=this[ghe];!e||e.flowing||e.size===e.remain?this[Hut]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[_8o](e,t){let r=this[cVe];if(!r)throw new Error("attempt to consume body without entry??");let n=r.blockRemain??0,i=n>=e.length&&t===0?e:e.subarray(t,t+n);return r.write(i),r.blockRemain||(this[D8]="header",this[cVe]=void 0,r.end()),i.length}[kVu](e,t){let r=this[cVe],n=this[_8o](e,t);return!this[cVe]&&r&&this[DVu](r),n}[uVe](e,t,r){this[Ahe].length===0&&!this[ghe]?this.emit(e,t,r):this[Ahe].push([e,t,r])}[DVu](e){switch(this[uVe]("meta",this[ZSe]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[Zre]=NJr.parse(this[ZSe],this[Zre],!1);break;case"GlobalExtendedHeader":this[Q9t]=NJr.parse(this[ZSe],this[Q9t],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[Zre]??Object.create(null);this[Zre]=t,t.path=this[ZSe].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[Zre]||Object.create(null);this[Zre]=t,t.linkpath=this[ZSe].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[ewe]=!0,this.emit("abort",e),this.warn("TAR_ABORT",e,{recoverable:!1})}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this[ewe])return r?.(),!1;if((this[yS]===void 0||this.brotli===void 0&&this[yS]===!1)&&e){if(this[x0]&&(e=Buffer.concat([this[x0],e]),this[x0]=void 0),e.length<aDm)return this[x0]=e,r?.(),!0;for(let s=0;this[yS]===void 0&&s<$8o.length;s++)e[s]!==$8o[s]&&(this[yS]=!1);let i=!1;if(this[yS]===!1&&this.zstd!==!1){i=!0;for(let s=0;s<eGo.length;s++)if(e[s]!==eGo[s]){i=!1;break}}let o=this.brotli===void 0&&!i;if(this[yS]===!1&&o)if(e.length<512)if(this[$Se])this.brotli=!0;else return this[x0]=e,r?.(),!0;else try{new gVe(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[yS]===void 0||this[yS]===!1&&(this.brotli||i)){let s=this[$Se];this[$Se]=!1,this[yS]=this[yS]===void 0?new kRm({}):i?new zRm({}):new NRm({}),this[yS].on("data",c=>this[hJr](c)),this[yS].on("error",c=>this.abort(c)),this[yS].on("end",()=>{this[$Se]=!0,this[hJr]()}),this[Hut]=!0;let a=!!this[yS][s?"end":"write"](e);return this[Hut]=!1,r?.(),a}}this[Hut]=!0,this[yS]?this[yS].write(e):this[hJr](e),this[Hut]=!1;let n=this[Ahe].length>0?!1:this[ghe]?this[ghe].flowing:!0;return!n&&this[Ahe].length===0&&this[ghe]?.once("drain",()=>this.emit("drain")),r?.(),n}[U8o](e){e&&!this[ewe]&&(this[x0]=this[x0]?Buffer.concat([this[x0],e]):e)}[AJr](){if(this[$Se]&&!this[L8o]&&!this[ewe]&&!this[M9t]){this[L8o]=!0;let e=this[cVe];if(e&&e.blockRemain){let t=this[x0]?this[x0].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[x0]&&e.write(this[x0]),e.end()}this[uVe](yJr)}}[hJr](e){if(this[M9t]&&e)this[U8o](e);else if(!e&&!this[x0])this[AJr]();else if(e){if(this[M9t]=!0,this[x0]){this[U8o](e);let t=this[x0];this[x0]=void 0,this[gJr](t)}else this[gJr](e);for(;this[x0]&&this[x0]?.length>=512&&!this[ewe]&&!this[EJr];){let t=this[x0];this[x0]=void 0,this[gJr](t)}this[M9t]=!1}(!this[x0]||this[$Se])&&this[AJr]()}[gJr](e){let t=0,r=e.length;for(;t+512<=r&&!this[ewe]&&!this[EJr];)switch(this[D8]){case"begin":case"header":this[FVu](e,t),t+=512;break;case"ignore":case"body":t+=this[_8o](e,t);break;case"meta":t+=this[kVu](e,t);break;default:throw new Error("invalid state: "+this[D8])}t<r&&(this[x0]=this[x0]?Buffer.concat([e.subarray(t),this[x0]]):e.subarray(t))}end(e,t,r){return typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t)),r&&this.once("finish",r),this[ewe]||(this[yS]?(e&&this[yS].write(e),this[yS].end()):(this[$Se]=!0,(this.brotli===void 0||this.zstd===void 0)&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[AJr]())),this}},K9t=e=>{let t=e.length-1,r=-1;for(;t>-1&&e.charAt(t)==="/";)r=t,t--;return r===-1?e:e.slice(0,r)},uDm=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},A5u=(e,t)=>{let r=new Map(t.map(o=>[K9t(o),!0])),n=e.filter,i=(o,s="")=>{let a=s||(0,LJr.parse)(o).root||".",c;if(o===a)c=!1;else{let u=r.get(o);c=u!==void 0?u:i((0,LJr.dirname)(o),a)}return r.set(o,c),c};e.filter=n?(o,s)=>n(o,s)&&i(K9t(o)):o=>i(K9t(o))},lDm=e=>{let t=new eWt(e),r=e.file,n;try{n=dVe.default.openSync(r,"r");let i=dVe.default.fstatSync(n),o=e.maxReadSize||16*1024*1024;if(i.size<o){let s=Buffer.allocUnsafe(i.size),a=dVe.default.readSync(n,s,0,i.size,0);t.end(a===s.byteLength?s:s.subarray(0,a))}else{let s=0,a=Buffer.allocUnsafe(o);for(;s<i.size;){let c=dVe.default.readSync(n,a,0,o,s);if(c===0)break;s+=c,t.write(a.subarray(0,c))}t.end()}}finally{if(typeof n=="number")try{dVe.default.closeSync(n)}catch{}}},pDm=(e,t)=>{let r=new eWt(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("end",o),dVe.default.stat(i,(a,c)=>{if(a)s(a);else{let u=new EGo(i,{readSize:n,size:c.size});u.on("error",s),u.pipe(r)}})})},VJr=nWt(lDm,pDm,e=>new eWt(e),e=>new eWt(e),(e,t)=>{t?.length&&A5u(e,t),e.noResume||uDm(e)}),y5u=(e,t,r)=>(e&=4095,r&&(e=(e|384)&-19),t&&(e&256&&(e|=64),e&32&&(e|=8),e&4&&(e|=1)),e),{isAbsolute:fDm,parse:jVu}=b5u.win32,SGo=e=>{let t="",r=jVu(e);for(;fDm(e)||r.root;){let n=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(n.length),t+=n,r=jVu(e)}return[t,e]},GJr=["|","<",">","?",":"],wGo=GJr.map(e=>String.fromCodePoint(61440+Number(e.codePointAt(0)))),dDm=new Map(GJr.map((e,t)=>[e,wGo[t]])),mDm=new Map(wGo.map((e,t)=>[e,GJr[t]])),zVu=e=>GJr.reduce((t,r)=>t.split(r).join(dDm.get(r)),e),hDm=e=>wGo.reduce((t,r)=>t.split(r).join(mDm.get(r)),e),E5u=(e,t)=>t?(e=Pf(e).replace(/^\.(\/|$)/,""),K9t(t)+"/"+e):Pf(e),gDm=16*1024*1024,QVu=Symbol("process"),MVu=Symbol("file"),LVu=Symbol("directory"),rGo=Symbol("symlink"),_Vu=Symbol("hardlink"),L9t=Symbol("header"),wJr=Symbol("read"),nGo=Symbol("lstat"),TJr=Symbol("onlstat"),iGo=Symbol("onread"),oGo=Symbol("onreadlink"),sGo=Symbol("openfile"),aGo=Symbol("onopenfile"),owe=Symbol("close"),jJr=Symbol("mode"),cGo=Symbol("awaitDrain"),V8o=Symbol("ondrain"),$re=Symbol("prefix"),I5u=class extends AVe{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(e,t={}){let r=vGo(t);super(),this.path=Pf(e),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||gDm,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Pf(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Pf(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let n=!1;if(!this.preservePaths){let[o,s]=SGo(this.path);o&&typeof s=="string"&&(this.path=s,n=o)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=hDm(this.path.replaceAll(/\\/g,"/")),e=e.replaceAll(/\\/g,"/")),this.absolute=Pf(r.absolute||tGo.default.resolve(this.cwd,e)),this.path===""&&(this.path="./"),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path});let i=this.statCache.get(this.absolute);i?this[TJr](i):this[nGo]()}warn(e,t,r={}){return UJr(this,e,t,r)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[nGo](){wJ.default.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[TJr](t)})}[TJr](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=bDm(e),this.emit("stat",e),this[QVu]()}[QVu](){switch(this.type){case"File":return this[MVu]();case"Directory":return this[LVu]();case"SymbolicLink":return this[rGo]();default:return this.end()}}[jJr](e){return y5u(e,this.type==="Directory",this.portable)}[$re](e){return E5u(e,this.prefix)}[L9t](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new gVe({path:this[$re](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[$re](this.linkpath):this.linkpath,mode:this[jJr](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new NJr({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[$re](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[$re](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let e=this.header?.block;if(!e)throw new Error("failed to encode header");super.write(e)}[LVu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[L9t](),this.end()}[rGo](){wJ.default.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[oGo](t)})}[oGo](e){this.linkpath=Pf(e),this[L9t](),this.end()}[_Vu](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Pf(tGo.default.relative(this.cwd,e)),this.stat.size=0,this[L9t](),this.end()}[MVu](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let e=`${this.stat.dev}:${this.stat.ino}`,t=this.linkCache.get(e);if(t?.indexOf(this.cwd)===0)return this[_Vu](t);this.linkCache.set(e,this.absolute)}if(this[L9t](),this.stat.size===0)return this.end();this[sGo]()}[sGo](){wJ.default.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[aGo](t)})}[aGo](e){if(this.fd=e,this.#e)return this[owe]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let t=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(t),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[wJr]()}[wJr](){let{fd:e,buf:t,offset:r,length:n,pos:i}=this;if(e===void 0||t===void 0)throw new Error("cannot read file without first opening");wJ.default.read(e,t,r,n,i,(o,s)=>{if(o)return this[owe](()=>this.emit("error",o));this[iGo](s)})}[owe](e=()=>{}){this.fd!==void 0&&wJ.default.close(this.fd,e)}[iGo](e){if(e<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[owe](()=>this.emit("error",r))}if(e>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[owe](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(e===this.remain)for(let r=e;r<this.length&&e<this.blockRemain;r++)this.buf[r+this.offset]=0,e++,this.remain++;let t=this.offset===0&&e===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+e);this.write(t)?this[V8o]():this[cGo](()=>this[V8o]())}[cGo](e){this.once("drain",e)}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this.blockRemain<e.length){let n=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",n)}return this.remain-=e.length,this.blockRemain-=e.length,this.pos+=e.length,this.offset+=e.length,super.write(e,null,r)}[V8o](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[owe](e=>e?this.emit("error",e):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[wJr]()}},ADm=class extends I5u{sync=!0;[nGo](){this[TJr](wJ.default.lstatSync(this.absolute))}[rGo](){this[oGo](wJ.default.readlinkSync(this.absolute))}[sGo](){this[aGo](wJ.default.openSync(this.absolute,"r"))}[wJr](){let e=!0;try{let{fd:t,buf:r,offset:n,length:i,pos:o}=this;if(t===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let s=wJ.default.readSync(t,r,n,i,o);this[iGo](s),e=!1}finally{if(e)try{this[owe](()=>{})}catch{}}}[cGo](e){e()}[owe](e=()=>{}){this.fd!==void 0&&wJ.default.closeSync(this.fd),e()}},yDm=class extends AVe{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(e,t,r={}){return UJr(this,e,t,r)}constructor(e,t={}){let r=vGo(t);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=e;let{type:n}=e;if(n==="Unsupported")throw new Error("writing entry that should be ignored");this.type=n,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=Pf(e.path),this.mode=e.mode!==void 0?this[jJr](e.mode):void 0,this.uid=this.portable?void 0:e.uid,this.gid=this.portable?void 0:e.gid,this.uname=this.portable?void 0:e.uname,this.gname=this.portable?void 0:e.gname,this.size=e.size,this.mtime=this.noMtime?void 0:r.mtime||e.mtime,this.atime=this.portable?void 0:e.atime,this.ctime=this.portable?void 0:e.ctime,this.linkpath=e.linkpath!==void 0?Pf(e.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[s,a]=SGo(this.path);s&&typeof a=="string"&&(this.path=a,i=s)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.onWriteEntry?.(this),this.header=new gVe({path:this[$re](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[$re](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.header.encode()&&!this.noPax&&super.write(new NJr({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[$re](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[$re](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),e.pipe(this)}[$re](e){return E5u(e,this.prefix)}[jJr](e){return y5u(e,this.type==="Directory",this.portable)}write(e,t,r){typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8"));let n=e.length;if(n>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=n,super.write(e,r)}end(e,t,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t??"utf8")),r&&this.once("finish",r),e?super.end(e,r):super.end(r),this}},bDm=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported",EDm=class $ut{tail;head;length=0;static create(t=[]){return new $ut(t)}constructor(t=[]){for(let r of t)this.push(r)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw new Error("removing node which does not belong to this list");let r=t.next,n=t.prev;return r&&(r.prev=n),n&&(n.next=r),t===this.head&&(this.head=r),t===this.tail&&(this.tail=n),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,r}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let r=this.head;t.list=this,t.next=r,r&&(r.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let r=this.tail;t.list=this,t.prev=r,r&&(r.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let r=0,n=t.length;r<n;r++)vDm(this,t[r]);return this.length}unshift(...t){for(var r=0,n=t.length;r<n;r++)CDm(this,t[r]);return this.length}pop(){if(!this.tail)return;let t=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,t}shift(){if(!this.head)return;let t=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,t}forEach(t,r){r=r||this;for(let n=this.head,i=0;n;i++)t.call(r,n.value,i,this),n=n.next}forEachReverse(t,r){r=r||this;for(let n=this.tail,i=this.length-1;n;i--)t.call(r,n.value,i,this),n=n.prev}get(t){let r=0,n=this.head;for(;n&&r<t;r++)n=n.next;if(r===t&&n)return n.value}getReverse(t){let r=0,n=this.tail;for(;n&&r<t;r++)n=n.prev;if(r===t&&n)return n.value}map(t,r){r=r||this;let n=new $ut;for(let i=this.head;i;)n.push(t.call(r,i.value,this)),i=i.next;return n}mapReverse(t,r){r=r||this;var n=new $ut;for(let i=this.tail;i;)n.push(t.call(r,i.value,this)),i=i.prev;return n}reduce(t,r){let n,i=this.head;if(arguments.length>1)n=r;else if(this.head)i=this.head.next,n=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var o=0;i;o++)n=t(n,i.value,o),i=i.next;return n}reduceReverse(t,r){let n,i=this.tail;if(arguments.length>1)n=r;else if(this.tail)i=this.tail.prev,n=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let o=this.length-1;i;o--)n=t(n,i.value,o),i=i.prev;return n}toArray(){let t=new Array(this.length);for(let r=0,n=this.head;n;r++)t[r]=n.value,n=n.next;return t}toArrayReverse(){let t=new Array(this.length);for(let r=0,n=this.tail;n;r++)t[r]=n.value,n=n.prev;return t}slice(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let n=new $ut;if(r<t||r<0)return n;t<0&&(t=0),r>this.length&&(r=this.length);let i=this.head,o=0;for(o=0;i&&o<t;o++)i=i.next;for(;i&&o<r;o++,i=i.next)n.push(i.value);return n}sliceReverse(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let n=new $ut;if(r<t||r<0)return n;t<0&&(t=0),r>this.length&&(r=this.length);let i=this.length,o=this.tail;for(;o&&i>r;i--)o=o.prev;for(;o&&i>t;i--,o=o.prev)n.push(o.value);return n}splice(t,r=0,...n){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let i=this.head;for(let s=0;i&&s<t;s++)i=i.next;let o=[];for(let s=0;i&&s<r;s++)o.push(i.value),i=this.removeNode(i);i?i!==this.tail&&(i=i.prev):i=this.tail;for(let s of n)i=IDm(this,i,s);return o}reverse(){let t=this.head,r=this.tail;for(let n=t;n;n=n.prev){let i=n.prev;n.prev=n.next,n.next=i}return this.head=r,this.tail=t,this}};TGo=class{list;next;prev;value;constructor(e,t,r,n){this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},UVu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(e,t){this.path=e||"./",this.absolute=t}},VVu=Buffer.alloc(1024),OJr=Symbol("onStat"),_9t=Symbol("ended"),xJ=Symbol("queue"),U9t=Symbol("pendingLinks"),twe=Symbol("current"),pVe=Symbol("process"),V9t=Symbol("processing"),IJr=Symbol("processJob"),SJ=Symbol("jobs"),G8o=Symbol("jobDone"),PJr=Symbol("addFSEntry"),GVu=Symbol("addTarEntry"),lGo=Symbol("stat"),pGo=Symbol("readdir"),BJr=Symbol("onreaddir"),RJr=Symbol("pipe"),qVu=Symbol("entry"),q8o=Symbol("entryOpt"),DJr=Symbol("writeEntryClass"),v5u=Symbol("write"),W8o=Symbol("ondrain"),qJr=class extends AVe{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[DJr];onWriteEntry;[xJ];[U9t]=new Map;[SJ]=0;[V9t]=!1;[_9t]=!1;constructor(e={}){if(super(),this.opt=e,this.file=e.file||"",this.cwd=e.cwd||process.cwd(),this.maxReadSize=e.maxReadSize,this.preservePaths=!!e.preservePaths,this.strict=!!e.strict,this.noPax=!!e.noPax,this.prefix=Pf(e.prefix||""),this.linkCache=e.linkCache||new Map,this.statCache=e.statCache||new Map,this.readdirCache=e.readdirCache||new Map,this.onWriteEntry=e.onWriteEntry,this[DJr]=I5u,typeof e.onwarn=="function"&&this.on("warn",e.onwarn),this.portable=!!e.portable,e.gzip||e.brotli||e.zstd){if((e.gzip?1:0)+(e.brotli?1:0)+(e.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(e.gzip&&(typeof e.gzip!="object"&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new DRm(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new FRm(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new jRm(e.zstd)),!this.zip)throw new Error("impossible");let t=this.zip;t.on("data",r=>super.write(r)),t.on("end",()=>super.end()),t.on("drain",()=>this[W8o]()),this.on("resume",()=>t.resume())}else this.on("drain",this[W8o]);this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,e.mtime&&(this.mtime=e.mtime),this.filter=typeof e.filter=="function"?e.filter:()=>!0,this[xJ]=new EDm,this[SJ]=0,this.jobs=Number(e.jobs)||4,this[V9t]=!1,this[_9t]=!1}[v5u](e){return super.write(e)}add(e){return this.write(e),this}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t=void 0),e&&this.add(e),this[_9t]=!0,this[pVe](),r&&r(),this}write(e){if(this[_9t])throw new Error("write after end");return typeof e=="string"?this[PJr](e):this[GVu](e),this.flowing}[GVu](e){let t=Pf(uGo.default.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new UVu(e.path,t);r.entry=new yDm(e,this[q8o](r)),r.entry.on("end",()=>this[G8o](r)),this[SJ]+=1,this[xJ].push(r)}this[pVe]()}[PJr](e){let t=Pf(uGo.default.resolve(this.cwd,e));this[xJ].push(new UVu(e,t)),this[pVe]()}[lGo](e){e.pending=!0,this[SJ]+=1;let t=this.follow?"stat":"lstat";tWt.default[t](e.absolute,(r,n)=>{e.pending=!1,this[SJ]-=1,r?this.emit("error",r):this[OJr](e,n)})}[OJr](e,t){if(this.statCache.set(e.absolute,t),e.stat=t,!this.filter(e.path,t))e.ignore=!0;else if(t.isFile()&&t.nlink>1&&!this.linkCache.get(`${t.dev}:${t.ino}`)&&!this.sync)if(e===this[twe])this[IJr](e);else{let r=`${t.dev}:${t.ino}`,n=this[U9t].get(r);n?n.push(e):this[U9t].set(r,[e]),e.pendingLink=!0,e.pending=!0}this[pVe]()}[pGo](e){e.pending=!0,this[SJ]+=1,tWt.default.readdir(e.absolute,(t,r)=>{if(e.pending=!1,this[SJ]-=1,t)return this.emit("error",t);this[BJr](e,r)})}[BJr](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[pVe]()}[pVe](){if(!this[V9t]){this[V9t]=!0;for(let e=this[xJ].head;e&&this[SJ]<this.jobs;e=e.next)if(this[IJr](e.value),e.value.ignore){let t=e.next;this[xJ].removeNode(e),e.next=t}this[V9t]=!1,this[_9t]&&this[xJ].length===0&&this[SJ]===0&&(this.zip?this.zip.end(VVu):(super.write(VVu),super.end()))}}get[twe](){return this[xJ]&&this[xJ].head&&this[xJ].head.value}[G8o](e){this[xJ].shift(),this[SJ]-=1;let{stat:t}=e;if(t&&t.isFile()&&t.nlink>1){let r=`${t.dev}:${t.ino}`,n=this[U9t].get(r);if(n){this[U9t].delete(r);for(let i of n)i.pending=!1,this[IJr](i)}}this[pVe]()}[IJr](e){if(e.pending&&e.pendingLink&&e===this[twe]&&(e.pending=!1,e.pendingLink=!1),!e.pending){if(e.entry){e===this[twe]&&!e.piped&&this[RJr](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[OJr](e,t):this[lGo](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[BJr](e,t):this[pGo](e),!e.readdir)return}if(e.entry=this[qVu](e),!e.entry){e.ignore=!0;return}e===this[twe]&&!e.piped&&this[RJr](e)}}}[q8o](e){return{onwarn:(t,r,n)=>this.warn(t,r,n),noPax:this.noPax,cwd:this.cwd,absolute:e.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[qVu](e){this[SJ]+=1;try{return new this[DJr](e.path,this[q8o](e)).on("end",()=>this[G8o](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[W8o](){this[twe]&&this[twe].entry&&this[twe].entry.resume()}[RJr](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[PJr](o+n)});let t=e.entry,r=this.zip;if(!t)throw new Error("cannot pipe without source");r?t.on("data",n=>{r.write(n)||t.pause()}):t.on("data",n=>{super.write(n)||t.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(e,t,r={}){UJr(this,e,t,r)}},OGo=class extends qJr{sync=!0;constructor(e){super(e),this[DJr]=ADm}pause(){}resume(){}[lGo](e){let t=this.follow?"statSync":"lstatSync";this[OJr](e,tWt.default[t](e.absolute))}[pGo](e){this[BJr](e,tWt.default.readdirSync(e.absolute))}[RJr](e){let t=e.entry,r=this.zip;if(e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[PJr](o+n)}),!t)throw new Error("Cannot pipe without source");r?t.on("data",n=>{r.write(n)}):t.on("data",n=>{super[v5u](n)})}},xDm=(e,t)=>{let r=new OGo(e),n=new s5u(e.file,{mode:e.mode||438});r.pipe(n),C5u(r,t)},SDm=(e,t)=>{let r=new qJr(e),n=new MJr(e.file,{mode:e.mode||438});r.pipe(n);let i=new Promise((o,s)=>{n.on("error",s),n.on("close",o),r.on("error",s)});return x5u(r,t).catch(o=>r.emit("error",o)),i},C5u=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?VJr({file:IGo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},x5u=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await VJr({file:IGo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>{e.add(n)}}):e.add(r);e.end()},wDm=(e,t)=>{let r=new OGo(e);return C5u(r,t),r},TDm=(e,t)=>{let r=new qJr(e);return x5u(r,t).catch(n=>r.emit("error",n)),r},WJr=nWt(xDm,SDm,wDm,TDm,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")}),ODm=process.env.__FAKE_PLATFORM__||process.platform,w5u=ODm==="win32",{O_CREAT:T5u,O_NOFOLLOW:WVu,O_TRUNC:O5u,O_WRONLY:P5u}=RGo.default.constants,B5u=Number(process.env.__FAKE_FS_O_FILENAME__)||RGo.default.constants.UV_FS_O_FILEMAP||0,PDm=w5u&&!!B5u,BDm=512*1024,RDm=B5u|O5u|T5u|P5u,HVu=!w5u&&typeof WVu=="number"?WVu|O5u|T5u|P5u:null,R5u=HVu!==null?()=>HVu:PDm?e=>e<BDm?RDm:"w":()=>"w",fGo=(e,t,r)=>{try{return iWt.default.lchownSync(e,t,r)}catch(n){if(n?.code!=="ENOENT")throw n}},zJr=(e,t,r,n)=>{iWt.default.lchown(e,t,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},DDm=(e,t,r,n,i)=>{if(t.isDirectory())D5u(tlt.default.resolve(e,t.name),r,n,o=>{if(o)return i(o);let s=tlt.default.resolve(e,t.name);zJr(s,r,n,i)});else{let o=tlt.default.resolve(e,t.name);zJr(o,r,n,i)}},D5u=(e,t,r,n)=>{iWt.default.readdir(e,{withFileTypes:!0},(i,o)=>{if(i){if(i.code==="ENOENT")return n();if(i.code!=="ENOTDIR"&&i.code!=="ENOTSUP")return n(i)}if(i||!o.length)return zJr(e,t,r,n);let s=o.length,a=null,c=u=>{if(!a){if(u)return n(a=u);if(--s===0)return zJr(e,t,r,n)}};for(let u of o)DDm(e,u,t,r,c)})},kDm=(e,t,r,n)=>{t.isDirectory()&&k5u(tlt.default.resolve(e,t.name),r,n),fGo(tlt.default.resolve(e,t.name),r,n)},k5u=(e,t,r)=>{let n;try{n=iWt.default.readdirSync(e,{withFileTypes:!0})}catch(i){let o=i;if(o?.code==="ENOENT")return;if(o?.code==="ENOTDIR"||o?.code==="ENOTSUP")return fGo(e,t,r);throw o}for(let i of n)kDm(e,i,t,r);return fGo(e,t,r)},N5u=class extends Error{path;code;syscall="chdir";constructor(e,t){super(`${t}: Cannot cd into '${e}'`),this.path=e,this.code=t}get name(){return"CwdError"}},HJr=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(e,t){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=e,this.path=t}get name(){return"SymlinkError"}},FDm=(e,t)=>{EM.default.stat(e,(r,n)=>{(r||!n.isDirectory())&&(r=new N5u(e,r?.code||"ENOTDIR")),t(r)})},NDm=(e,t,r)=>{e=Pf(e);let n=t.umask??18,i=t.mode|448,o=(i&n)!==0,s=t.uid,a=t.gid,c=typeof s=="number"&&typeof a=="number"&&(s!==t.processUid||a!==t.processGid),u=t.preserve,l=t.unlink,p=Pf(t.cwd),d=(m,g)=>{m?r(m):g&&c?D5u(g,s,a,A=>d(A)):o?EM.default.chmod(e,i,r):r()};if(e===p)return FDm(e,d);if(u)return F5u.default.mkdir(e,{mode:i,recursive:!0}).then(m=>d(null,m??void 0),d);let f=Pf(rWt.default.relative(p,e)).split("/");dGo(p,f,i,l,p,void 0,d)},dGo=(e,t,r,n,i,o,s)=>{if(t.length===0)return s(null,o);let a=t.shift(),c=Pf(rWt.default.resolve(e+"/"+a));EM.default.mkdir(c,r,j5u(c,t,r,n,i,o,s))},j5u=(e,t,r,n,i,o,s)=>a=>{a?EM.default.lstat(e,(c,u)=>{if(c)c.path=c.path&&Pf(c.path),s(c);else if(u.isDirectory())dGo(e,t,r,n,i,o,s);else if(n)EM.default.unlink(e,l=>{if(l)return s(l);EM.default.mkdir(e,r,j5u(e,t,r,n,i,o,s))});else{if(u.isSymbolicLink())return s(new HJr(e,e+"/"+t.join("/")));s(a)}}):(o=o||e,dGo(e,t,r,n,i,o,s))},jDm=e=>{let t=!1,r;try{t=EM.default.statSync(e).isDirectory()}catch(n){r=n?.code}finally{if(!t)throw new N5u(e,r??"ENOTDIR")}},zDm=(e,t)=>{e=Pf(e);let r=t.umask??18,n=t.mode|448,i=(n&r)!==0,o=t.uid,s=t.gid,a=typeof o=="number"&&typeof s=="number"&&(o!==t.processUid||s!==t.processGid),c=t.preserve,u=t.unlink,l=Pf(t.cwd),p=m=>{m&&a&&k5u(m,o,s),i&&EM.default.chmodSync(e,n)};if(e===l)return jDm(l),p();if(c)return p(EM.default.mkdirSync(e,{mode:n,recursive:!0})??void 0);let d=Pf(rWt.default.relative(l,e)).split("/"),f;for(let m=d.shift(),g=l;m&&(g+="/"+m);m=d.shift()){g=Pf(rWt.default.resolve(g));try{EM.default.mkdirSync(g,n),f=f||g}catch{let A=EM.default.lstatSync(g);if(A.isDirectory())continue;if(u){EM.default.unlinkSync(g),EM.default.mkdirSync(g,n),f=f||g;continue}else if(A.isSymbolicLink())return new HJr(g,g+"/"+d.join("/"))}}return p(f)},H8o=Object.create(null),KVu=1e4,Kut=new Set,QDm=e=>{Kut.has(e)?Kut.delete(e):H8o[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Kut.add(e);let t=H8o[e],r=Kut.size-KVu;if(r>KVu/10){for(let n of Kut)if(Kut.delete(n),delete H8o[n],--r<=0)break}return t},MDm=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,LDm=MDm==="win32",_Dm=e=>e.split("/").slice(0,-1).reduce((t,r)=>{let n=t.at(-1);return n!==void 0&&(r=(0,DGo.join)(n,r)),t.push(r||"/"),t},[]),UDm=class{#e=new Map;#t=new Map;#r=new Set;reserve(e,t){e=LDm?["win32 parallelization disabled"]:e.map(n=>K9t((0,DGo.join)(QDm(n))));let r=new Set(e.map(n=>_Dm(n)).reduce((n,i)=>n.concat(i)));this.#t.set(t,{dirs:r,paths:e});for(let n of e){let i=this.#e.get(n);i?i.push(t):this.#e.set(n,[t])}for(let n of r){let i=this.#e.get(n);if(!i)this.#e.set(n,[new Set([t])]);else{let o=i.at(-1);o instanceof Set?o.add(t):i.push(new Set([t]))}}return this.#i(t)}#n(e){let t=this.#t.get(e);if(!t)throw new Error("function does not have any path reservations");return{paths:t.paths.map(r=>this.#e.get(r)),dirs:[...t.dirs].map(r=>this.#e.get(r))}}check(e){let{paths:t,dirs:r}=this.#n(e);return t.every(n=>n&&n[0]===e)&&r.every(n=>n&&n[0]instanceof Set&&n[0].has(e))}#i(e){return this.#r.has(e)||!this.check(e)?!1:(this.#r.add(e),e(()=>this.#o(e)),!0)}#o(e){if(!this.#r.has(e))return!1;let t=this.#t.get(e);if(!t)throw new Error("invalid reservation");let{paths:r,dirs:n}=t,i=new Set;for(let o of r){let s=this.#e.get(o);if(!s||s?.[0]!==e)continue;let a=s[1];if(!a){this.#e.delete(o);continue}if(s.shift(),typeof a=="function")i.add(a);else for(let c of a)i.add(c)}for(let o of n){let s=this.#e.get(o),a=s?.[0];if(!(!s||!(a instanceof Set)))if(a.size===1&&s.length===1){this.#e.delete(o);continue}else if(a.size===1){s.shift();let c=s[0];typeof c=="function"&&i.add(c)}else a.delete(e)}return this.#r.delete(e),i.forEach(o=>this.#i(o)),!0}},VDm=()=>process.umask(),JVu=Symbol("onEntry"),mGo=Symbol("checkFs"),YVu=Symbol("checkFs2"),hGo=Symbol("isReusable"),k8=Symbol("makeFs"),gGo=Symbol("file"),AGo=Symbol("directory"),kJr=Symbol("link"),XVu=Symbol("symlink"),ZVu=Symbol("hardlink"),W9t=Symbol("ensureNoSymlink"),$Vu=Symbol("unsupported"),e5u=Symbol("checkPath"),K8o=Symbol("stripAbsolutePath"),awe=Symbol("mkdir"),tO=Symbol("onError"),vJr=Symbol("pending"),t5u=Symbol("pend"),Jut=Symbol("unpend"),J8o=Symbol("ended"),Y8o=Symbol("maybeClose"),yGo=Symbol("skip"),J9t=Symbol("doChown"),Y9t=Symbol("uid"),X9t=Symbol("gid"),Z9t=Symbol("checkedCwd"),GDm=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,$9t=GDm==="win32",qDm=1024,WDm=(e,t)=>{if(!$9t)return Md.default.unlink(e,t);let r=e+".DELETE."+(0,BGo.randomBytes)(16).toString("hex");Md.default.rename(e,r,n=>{if(n)return t(n);Md.default.unlink(r,t)})},HDm=e=>{if(!$9t)return Md.default.unlinkSync(e);let t=e+".DELETE."+(0,BGo.randomBytes)(16).toString("hex");Md.default.renameSync(e,t),Md.default.unlinkSync(t)},r5u=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,kGo=class extends eWt{[J8o]=!1;[Z9t]=!1;[vJr]=0;reservations=new UDm;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(e={}){if(e.ondone=()=>{this[J8o]=!0,this[Y8o]()},super(e),this.transform=e.transform,this.chmod=!!e.chmod,typeof e.uid=="number"||typeof e.gid=="number"){if(typeof e.uid!="number"||typeof e.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(e.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=e.preserveOwner===void 0&&typeof e.uid!="number"?!!(process.getuid&&process.getuid()===0):!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:qDm,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||$9t,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=Pf(bS.default.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:VDm():0,this.umask=typeof e.umask=="number"?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on("entry",t=>this[JVu](t))}warn(e,t,r={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(r.recoverable=!1),super.warn(e,t,r)}[Y8o](){this[J8o]&&this[vJr]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[K8o](e,t){let r=e[t],{type:n}=e;if(!r||this.preservePaths)return!0;let[i,o]=SGo(r),s=o.replaceAll(/\\/g,"/").split("/");if(s.includes("..")||$9t&&/^[a-z]:\.\.$/i.test(s[0]??"")){if(t==="path"||n==="Link")return this.warn("TAR_ENTRY_ERROR",`${t} contains '..'`,{entry:e,[t]:r}),!1;let a=bS.default.posix.dirname(e.path),c=bS.default.posix.normalize(bS.default.posix.join(a,s.join("/")));if(c.startsWith("../")||c==="..")return this.warn("TAR_ENTRY_ERROR",`${t} escapes extraction directory`,{entry:e,[t]:r}),!1}return i&&(e[t]=String(o),this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute ${t}`,{entry:e,[t]:r})),!0}[e5u](e){let t=Pf(e.path),r=t.split("/");if(this.strip){if(r.length<this.strip)return!1;if(e.type==="Link"){let n=Pf(String(e.linkpath)).split("/");if(n.length>=this.strip)e.linkpath=n.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),e.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:e,path:t,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[K8o](e,"path")||!this[K8o](e,"linkpath"))return!1;if(e.absolute=bS.default.isAbsolute(e.path)?Pf(bS.default.resolve(e.path)):Pf(bS.default.resolve(this.cwd,e.path)),!this.preservePaths&&typeof e.absolute=="string"&&e.absolute.indexOf(this.cwd+"/")!==0&&e.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:e,path:Pf(e.path),resolvedPath:e.absolute,cwd:this.cwd}),!1;if(e.absolute===this.cwd&&e.type!=="Directory"&&e.type!=="GNUDumpDir")return!1;if(this.win32){let{root:n}=bS.default.win32.parse(String(e.absolute));e.absolute=n+zVu(String(e.absolute).slice(n.length));let{root:i}=bS.default.win32.parse(e.path);e.path=i+zVu(e.path.slice(i.length))}return!0}[JVu](e){if(!this[e5u](e))return e.resume();switch(S5u.default.equal(typeof e.absolute,"string"),e.type){case"Directory":case"GNUDumpDir":e.mode&&(e.mode=e.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[mGo](e);default:return this[$Vu](e)}}[tO](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[Jut](),t.resume())}[awe](e,t,r){NDm(Pf(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t},r)}[J9t](e){return this.forceChown||this.preserveOwner&&(typeof e.uid=="number"&&e.uid!==this.processUid||typeof e.gid=="number"&&e.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Y9t](e){return r5u(this.uid,e.uid,this.processUid)}[X9t](e){return r5u(this.gid,e.gid,this.processGid)}[gGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=new MJr(String(e.absolute),{flags:R5u(e.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&Md.default.close(n.fd,()=>{}),n.write=()=>!0,this[tO](a,e),t()});let i=1,o=a=>{if(a){n.fd&&Md.default.close(n.fd,()=>{}),this[tO](a,e),t();return}--i===0&&n.fd!==void 0&&Md.default.close(n.fd,c=>{c?this[tO](c,e):this[Jut](),t()})};n.on("finish",()=>{let a=String(e.absolute),c=n.fd;if(typeof c=="number"&&e.mtime&&!this.noMtime){i++;let u=e.atime||new Date,l=e.mtime;Md.default.futimes(c,u,l,p=>p?Md.default.utimes(a,u,l,d=>o(d&&p)):o())}if(typeof c=="number"&&this[J9t](e)){i++;let u=this[Y9t](e),l=this[X9t](e);typeof u=="number"&&typeof l=="number"&&Md.default.fchown(c,u,l,p=>p?Md.default.chown(a,u,l,d=>o(d&&p)):o())}o()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",a=>{this[tO](a,e),t()}),e.pipe(s)),s.pipe(n)}[AGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode;this[awe](String(e.absolute),r,n=>{if(n){this[tO](n,e),t();return}let i=1,o=()=>{--i===0&&(t(),this[Jut](),e.resume())};e.mtime&&!this.noMtime&&(i++,Md.default.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[J9t](e)&&(i++,Md.default.chown(String(e.absolute),Number(this[Y9t](e)),Number(this[X9t](e)),o)),o()})}[$Vu](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[XVu](e,t){let r=Pf(bS.default.relative(this.cwd,bS.default.resolve(bS.default.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[W9t](e,this.cwd,r,()=>this[kJr](e,String(e.linkpath),"symlink",t),n=>{this[tO](n,e),t()})}[ZVu](e,t){let r=Pf(bS.default.resolve(this.cwd,String(e.linkpath))),n=Pf(String(e.linkpath)).split("/");this[W9t](e,this.cwd,n,()=>this[kJr](e,r,"link",t),i=>{this[tO](i,e),t()})}[W9t](e,t,r,n,i){let o=r.shift();if(this.preservePaths||o===void 0)return n();let s=bS.default.resolve(t,o);Md.default.lstat(s,(a,c)=>{if(a)return n();if(c?.isSymbolicLink())return i(new HJr(s,bS.default.resolve(s,r.join("/"))));this[W9t](e,s,r,n,i)})}[t5u](){this[vJr]++}[Jut](){this[vJr]--,this[Y8o]()}[yGo](e){this[Jut](),e.resume()}[hGo](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!$9t}[mGo](e){this[t5u]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,r=>this[YVu](e,r))}[YVu](e,t){let r=s=>{t(s)},n=()=>{this[awe](this.cwd,this.dmode,s=>{if(s){this[tO](s,e),r();return}this[Z9t]=!0,i()})},i=()=>{if(e.absolute!==this.cwd){let s=Pf(bS.default.dirname(String(e.absolute)));if(s!==this.cwd)return this[awe](s,this.dmode,a=>{if(a){this[tO](a,e),r();return}o()})}o()},o=()=>{Md.default.lstat(String(e.absolute),(s,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[yGo](e),r();return}if(s||this[hGo](e,a))return this[k8](null,e,r);if(a.isDirectory()){if(e.type==="Directory"){let c=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,u=l=>this[k8](l??null,e,r);return c?Md.default.chmod(String(e.absolute),Number(e.mode),u):u()}if(e.absolute!==this.cwd)return Md.default.rmdir(String(e.absolute),c=>this[k8](c??null,e,r))}if(e.absolute===this.cwd)return this[k8](null,e,r);WDm(String(e.absolute),c=>this[k8](c??null,e,r))})};this[Z9t]?i():n()}[k8](e,t,r){if(e){this[tO](e,t),r();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[gGo](t,r);case"Link":return this[ZVu](t,r);case"SymbolicLink":return this[XVu](t,r);case"Directory":case"GNUDumpDir":return this[AGo](t,r)}}[kJr](e,t,r,n){Md.default[r](t,String(e.absolute),i=>{i?this[tO](i,e):(this[Jut](),e.resume()),n()})}},G9t=e=>{try{return[null,e()]}catch(t){return[t,null]}},z5u=class extends kGo{sync=!0;[k8](e,t){return super[k8](e,t,()=>{})}[mGo](e){if(!this[Z9t]){let i=this[awe](this.cwd,this.dmode);if(i)return this[tO](i,e);this[Z9t]=!0}if(e.absolute!==this.cwd){let i=Pf(bS.default.dirname(String(e.absolute)));if(i!==this.cwd){let o=this[awe](i,this.dmode);if(o)return this[tO](o,e)}}let[t,r]=G9t(()=>Md.default.lstatSync(String(e.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(e.mtime??r.mtime)))return this[yGo](e);if(t||this[hGo](e,r))return this[k8](null,e);if(r.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(r.mode&4095)!==e.mode,[s]=o?G9t(()=>{Md.default.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[k8](s,e)}let[i]=G9t(()=>Md.default.rmdirSync(String(e.absolute)));this[k8](i,e)}let[n]=e.absolute===this.cwd?[]:G9t(()=>HDm(String(e.absolute)));this[k8](n,e)}[gGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=s=>{let a;try{Md.default.closeSync(i)}catch(c){a=c}(s||a)&&this[tO](s||a,e),t()},i;try{i=Md.default.openSync(String(e.absolute),R5u(e.size),r)}catch(s){return n(s)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",s=>this[tO](s,e)),e.pipe(o)),o.on("data",s=>{try{Md.default.writeSync(i,s,0,s.length)}catch(a){n(a)}}),o.on("end",()=>{let s=null;if(e.mtime&&!this.noMtime){let a=e.atime||new Date,c=e.mtime;try{Md.default.futimesSync(i,a,c)}catch(u){try{Md.default.utimesSync(String(e.absolute),a,c)}catch{s=u}}}if(this[J9t](e)){let a=this[Y9t](e),c=this[X9t](e);try{Md.default.fchownSync(i,Number(a),Number(c))}catch(u){try{Md.default.chownSync(String(e.absolute),Number(a),Number(c))}catch{s=s||u}}}n(s)})}[AGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode,n=this[awe](String(e.absolute),r);if(n){this[tO](n,e),t();return}if(e.mtime&&!this.noMtime)try{Md.default.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[J9t](e))try{Md.default.chownSync(String(e.absolute),Number(this[Y9t](e)),Number(this[X9t](e)))}catch{}t(),e.resume()}[awe](e,t){try{return zDm(Pf(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t})}catch(r){return r}}[W9t](e,t,r,n,i){if(this.preservePaths||r.length===0)return n();let o=t;for(let s of r){o=bS.default.resolve(o,s);let[a,c]=G9t(()=>Md.default.lstatSync(o));if(a)return n();if(c.isSymbolicLink())return i(new HJr(o,bS.default.resolve(t,r.join("/"))))}n()}[kJr](e,t,r,n){let i=`${r}Sync`;try{Md.default[i](t,String(e.absolute)),n(),e.resume()}catch(o){return this[tO](o,e)}}},KDm=e=>{let t=new z5u(e),r=e.file,n=PGo.default.statSync(r),i=e.maxReadSize||16*1024*1024;new IRm(r,{readSize:i,size:n.size}).pipe(t)},JDm=(e,t)=>{let r=new kGo(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("close",o),PGo.default.stat(i,(a,c)=>{if(a)s(a);else{let u=new EGo(i,{readSize:n,size:c.size});u.on("error",s),u.pipe(r)}})})},Q5u=nWt(KDm,JDm,e=>new z5u(e),e=>new kGo(e),(e,t)=>{t?.length&&A5u(e,t)}),YDm=(e,t)=>{let r=new OGo(e),n=!0,i,o;try{try{i=bM.default.openSync(e.file,"r+")}catch(c){if(c?.code==="ENOENT")i=bM.default.openSync(e.file,"w+");else throw c}let s=bM.default.fstatSync(i),a=Buffer.alloc(512);e:for(o=0;o<s.size;o+=512){for(let l=0,p=0;l<512;l+=p){if(p=bM.default.readSync(i,a,l,a.length-l,o+l),o===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let c=new gVe(a);if(!c.cksumValid)break;let u=512*Math.ceil((c.size||0)/512);if(o+u+512>s.size)break;o+=u,e.mtimeCache&&c.mtime&&e.mtimeCache.set(String(c.path),c.mtime)}n=!1,XDm(e,r,o,i,t)}finally{if(n)try{bM.default.closeSync(i)}catch{}}},XDm=(e,t,r,n,i)=>{let o=new s5u(e.file,{fd:n,start:r});t.pipe(o),$Dm(t,i)},ZDm=(e,t)=>{t=Array.from(t);let r=new qJr(e),n=(i,o,s)=>{let a=(d,f)=>{d?bM.default.close(i,m=>s(d)):s(null,f)},c=0;if(o===0)return a(null,0);let u=0,l=Buffer.alloc(512),p=(d,f)=>{if(d||f===void 0)return a(d);if(u+=f,u<512&&f)return bM.default.read(i,l,u,l.length-u,c+u,p);if(c===0&&l[0]===31&&l[1]===139)return a(new Error("cannot append to compressed archives"));if(u<512)return a(null,c);let m=new gVe(l);if(!m.cksumValid)return a(null,c);let g=512*Math.ceil((m.size??0)/512);if(c+g+512>o||(c+=g+512,c>=o))return a(null,c);e.mtimeCache&&m.mtime&&e.mtimeCache.set(String(m.path),m.mtime),u=0,bM.default.read(i,l,0,512,c,p)};bM.default.read(i,l,0,512,c,p)};return new Promise((i,o)=>{r.on("error",o);let s="r+",a=(c,u)=>{if(c&&c.code==="ENOENT"&&s==="r+")return s="w+",bM.default.open(e.file,s,a);if(c||!u)return o(c);bM.default.fstat(u,(l,p)=>{if(l)return bM.default.close(u,()=>o(l));n(u,p.size,(d,f)=>{if(d)return o(d);let m=new MJr(e.file,{fd:u,start:f});r.pipe(m),m.on("error",o),m.on("close",i),ekm(r,t)})})};bM.default.open(e.file,s,a)})},$Dm=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?VJr({file:FGo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},ekm=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await VJr({file:FGo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r);e.end()},q9t=nWt(YDm,ZDm,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!TRm(e))throw new TypeError("file is required");if(e.gzip||e.brotli||e.zstd||e.file.endsWith(".br")||e.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!t?.length)throw new TypeError("no paths specified to add/replace")}),Yxv=nWt(q9t.syncFile,q9t.asyncFile,q9t.syncNoFile,q9t.asyncNoFile,(e,t=[])=>{q9t.validate?.(e,t),tkm(e)}),tkm=e=>{let t=e.filter;e.mtimeCache||(e.mtimeCache=new Map),e.filter=t?(r,n)=>t(r,n)&&!((e.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0)):(r,n)=>!((e.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0))}});var co,JJr=h(()=>{"use strict";Wn();co=class e{breadcrumbs=[];context;static STRING=Zt.TypeReference.primitive({v1:"STRING",v2:Zt.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Zt.TypeReference.container(Zt.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}}});var NGo,M5u,L5u=h(()=>{"use strict";NGo=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:n,position:i,lineStart:o}=t;this._map[r]={line:n,position:i,lineStart:o}}t.children&&t.children.length>0&&t.children.forEach(n=>{this.resolveNode(n,(r==="."?"":r)+"."+n.path)})}iterFragments(t,r){for(let n=this._fragments.length-1;n>=0;n--){if(!this._fragments[n].path.startsWith(t)||this._fragments[n].path===t)continue;let i=this._fragments.pop();r(i)}}handleState(t,r){if(t==="close"){let n=r.result,i=r.kind,o=this._path.join(".");if(i==="scalar"){this._path.pop(),this._lastScalar=`${n}`;let{line:s,position:a,lineStart:c}=r;this._path.length===0?this._map["."+n]={line:s,position:a,lineStart:c}:this._fragments.push({path:this._path.join(".")+"."+n,line:s,position:a,lineStart:c})}else if(i==="mapping"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=0;this.iterFragments(o,c=>{a++,!((!c.children||c.children.length===0)&&a%2===1)&&(this._path.length===1?this.resolveNode(c,c.path):(s.children.push({...c,path:c.path.slice(o.length+1)}),s.line=c.line,s.position=c.position,s.lineStart=c.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else if(i==="sequence"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=new Set,c=n.length;this.iterFragments(o,u=>{a.has(u.position)||(c--,a.add(u.position),this._path.length===1?this.resolveNode(u,`${o}.${c}`):(s.children.push({...u,path:c.toString()}),s.line=u.line,s.position=u.position,s.lineStart=u.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:n,position:i,lineStart:o}=r;this._map["."]={line:n,position:i,lineStart:o}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(i=>`${i}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let n=this._map[r];if(n)return{line:n.line+1,column:n.position-n.lineStart+1,position:n.position}}},M5u=NGo});var _5u,CE,tne,jGo,oWt=h(()=>{"use strict";tr();Ky();_5u=require("fs/promises");cs();L5u();(function(e){e.WARNING="warning",e.ERROR="error"})(CE||(CE={}));tne=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new jGo({logger:t,relativePathToFile:Ae.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,n=0;for(let i of this.errors){let o=i.path?i.path.join("->"):"",s=`${i.message}|${i.level||CE.WARNING}|${o}`;r.has(s)?n++:(r.add(s),t.push(i))}return this.errors=t,n}getErrorStats(){this.dedupe();let t=0,r=0;for(let n of this.errors)n.level===CE.ERROR?t++:(n.level===CE.WARNING||n.level===void 0)&&r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors){let n=r.level??CE.WARNING;if(!(n===CE.WARNING&&!t))switch(n){case CE.ERROR:if(this.logger.log(Zn.Debug,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),o=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Zn.Debug,` - at location (${o})`)}break;case CE.WARNING:if(this.logger.log(Zn.Warn,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),o=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Zn.Warn,` - at location (${o})`)}r.resolution&&this.logger.log(Zn.Warn,` - resolution: ${r.resolution}`);break}}}},jGo=class{logger;relativePathToFile;map=new M5u;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,_5u.readFile)(this.relativePathToFile,"utf-8");Cr.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Zn.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}}});function nkm(e){return"deprecated"in e&&e.deprecated===!0}async function ikm(e){let t=await fetch(e);if(t.ok)try{let r=await t.text();try{return JSON.parse(r)}catch{return Cr.load(r)}}catch{return}}var S0,U5u=h(()=>{"use strict";b8();ct();Wn();cs();qi();oWt();rs();S0=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;externalDocuments=new Map;discriminatedVariantsInProgress=new Set;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=Ww({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples,this.documentBaseDir=t.documentBaseDir}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=e.getPropertyNameIndices(t),n=t.filter((o,s)=>r.has(s)?!0:!(/^\d+$/.test(o)||e.BREADCRUMBS_TO_IGNORE.includes(o)||s===0&&o==="components"||s===1&&o==="schemas"||t[0]==="paths"&&(s===0||s===1&&["get","post","put","delete","patch"].includes(o)||s===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&o==="parameters"))),i=ti(n.join("_"));return BH(i)}static getPropertyNameIndices(t){let r=new Set;for(let[n,i]of t.entries())i==="properties"&&!r.has(n)&&n+1<t.length&&r.add(n+1);return r}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],n=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:n?[...r,n]:r,packagePath:r,file:n}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n}){let i=this.spec,o=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of o){if(typeof i!="object"||i==null)return n||this.errorCollector.collect({level:CE.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[s]}return i==null?(n||this.errorCollector.collect({level:CE.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:i}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,n,i=!1,o=null,s;if(this.isExternalReference(t.$ref)){i=!0;let u=t.$ref.split("#"),l=u[0];if(n=u[1],!l)return{resolved:!1};if(s=l,o=await this.loadExternalDocument(l),r=o,r==null)return{resolved:!1};if(!n)return{resolved:!0,value:r}}let a=n??t.$ref;if(a==null||typeof a!="string")return{resolved:!1};let c=a.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of c){if(typeof r!="object"||r==null)return{resolved:!1};r=r[u]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let u=new Set;u.add(t.$ref),r=await this.resolveNestedExternalReferences(r,o,u,s)}return{resolved:!0,value:r}}async loadExternalDocument(t){let r=this.externalDocuments.get(t);r==null&&(r=ikm(t),this.externalDocuments.set(t,r));try{let n=await r;return n==null&&this.forgetExternalDocument(t,r),structuredClone(n)}catch(n){throw this.forgetExternalDocument(t,r),n}}forgetExternalDocument(t,r){this.externalDocuments.get(t)===r&&this.externalDocuments.delete(t)}async resolveNestedExternalReferences(t,r,n,i){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let s=[];for(let a of t)s.push(await this.resolveNestedExternalReferences(a,r,n,i));return s}if(this.isReferenceObject(t)){let s=t.$ref;if(this.isExternalReference(s)){if(n.has(s))return t;n.add(s);let a=await this.resolveMaybeExternalReference({$ref:s});if(n.delete(s),a.resolved)return a.value}else{let a=`${i}${s}`;if(n.has(a))return t;n.add(a);let c=r,u=s.substring(2).split("/").map(fI);for(let l of u){if(typeof c!="object"||c===null)return t;c=c[l]}if(c!=null){let l=await this.resolveNestedExternalReferences(c,r,n,i);return n.delete(s),l}n.delete(s)}return t}let o={};for(let[s,a]of Object.entries(t))typeof a=="object"&&a!==null?o[s]=await this.resolveNestedExternalReferences(a,r,n,i):o[s]=a;return o}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let n=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?n.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),n}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:n}){if(t==null)return[];let i=[];if(t.example!=null){let o=this.generateUniqueName({prefix:n??`${r.join("_")}_example`,existingNames:[]});i.push([o,{value:t.example}])}return t.examples!=null&&i.push(...Object.entries(t.examples)),i}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:n}){if(this.isReferenceObject(t)){let i=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n});return i.resolved?i.value:void 0}return t}resolveExampleRecursively({example:t,breadcrumbs:r,maxDepth:n=10}){let i=t,o=0;for(;this.isReferenceObject(i);){if(o>=n){this.errorCollector.collect({message:`Maximum reference depth (${n}) exceeded while resolving example reference`,path:r});return}let s=this.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!s.resolved)return;i=s.value,o++}return i}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let o=this.resolveReference({reference:r});if(!o.resolved)return;r=o.value}let{readOnly:n,writeOnly:i}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(n&&i)){if(n)return Zt.ObjectPropertyAccess.ReadOnly;if(i)return Zt.ObjectPropertyAccess.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,n=!0;for(let i of t.allOf){let o=i;if(this.isReferenceObject(i)){let a=this.resolveReference({reference:i});if(!a.resolved)continue;o=a.value}let s=this.getReadOnlyWriteOnlyFromSchema(o);r=r&&s.readOnly,n=n&&s.writeOnly}return{readOnly:r,writeOnly:n}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let i=new qC.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(i!=null)return i.audiences}getAvailability({node:t,breadcrumbs:r}){let n=new Set;for(;this.isReferenceObject(t);){let i=this.getDeclaredAvailability({node:t,breadcrumbs:r});if(i!=null)return i;if(n.has(t.$ref))return;n.add(t.$ref);let o=this.resolveReference({reference:t});if(!o.resolved)return;t=o.value}return this.getDeclaredAvailability({node:t,breadcrumbs:r})}getDeclaredAvailability({node:t,breadcrumbs:r}){let i=new qC.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(nkm(t))return{status:yh.Deprecated,message:void 0}}getNamespacedSchemaId(t){if(this.namespace==null)return t;let r=`${this.namespace}:`;return t.startsWith(r)?t:`${r}${t}`}getRawSchemaId(t){if(this.namespace==null)return t;let r=`${this.namespace}:`;return t.startsWith(r)?t.slice(r.length):t}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return this.getNamespacedSchemaId(r[1])}getRawSchemaNameFromReference(t){let r=t.$ref.match(/\/schemas\/([^/]+)/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return en.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:this.getNamespacedSchemaId(t),displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type==="named")return{typeId:t.typeId,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:t.name,displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){let n=this.getNamespacedSchemaId(t);return Object.fromEntries(Object.entries(r).filter(([i])=>i!==n))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let n=0;for(;r.includes(`${t}_${n}`);)n++;return`${t}_${n}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&vg(t)}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t||"summary"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t&&typeof t.summary=="string"&&t.summary.length>0}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(Fr(t))return t}getGroup({groupParts:t,namespace:r}){let n=[];return r!=null&&n.push(r),n.push(...t??[]),n}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}}});var os,tk=h(()=>{"use strict";os=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let n=t[this.key];if(n!=null)return n;if(r!=null)return t[r]}}});var nlt,zGo=h(()=>{"use strict";tk();nlt=class extends os{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}}});var YJr,V5u=h(()=>{"use strict";Wn();tk();YJr=class extends os{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return yh.InDevelopment;case"PRE_RELEASE":return yh.PreRelease;case"GENERAL_AVAILABILITY":case"GENERALLY_AVAILABLE":case"GA":case"STABLE":return yh.GeneralAvailability;case"DEPRECATED":return yh.Deprecated;case"ALPHA":return yh.Alpha;case"BETA":return yh.Beta;case"PREVIEW":return yh.Preview;case"LEGACY":return yh.Legacy;default:return}}}});var ilt,QGo=h(()=>{"use strict";tk();ilt=class extends os{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}}});var olt,MGo=h(()=>{"use strict";tk();olt=class extends os{node;key="x-fern-discriminator-context";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==="data"||t==="protocol")return t}}});var okm,skm,G5u,q5u=h(()=>{"use strict";cn();okm=De.object({snake:De.string().optional(),camel:De.string().optional(),screamingSnake:De.string().optional(),pascal:De.string().optional()}),skm=De.object({description:De.string().optional(),name:De.string().optional(),casing:okm.optional()}),G5u=De.record(skm)});var slt,LGo=h(()=>{"use strict";tk();q5u();slt=class extends os{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=G5u.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}}});var yVe,W5u=h(()=>{"use strict";tk();yVe=class extends os{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}}});var XJr,H5u=h(()=>{"use strict";tk();XJr=class extends os{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:n}){super({breadcrumbs:t,context:n}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}}});var ZJr,K5u=h(()=>{"use strict";tk();ZJr=class extends os{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}}});var $Jr,J5u=h(()=>{"use strict";tk();$Jr=class extends os{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}}});var eYr,Y5u=h(()=>{"use strict";tk();eYr=class extends os{operation;key="x-fern-server-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation,"x-name");if(!(t==null||typeof t!="string"))return t}}});var tYr,X5u=h(()=>{"use strict";tk();tYr=class extends os{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}}});var rYr,Z5u=h(()=>{"use strict";tk();rYr=class extends os{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}}});function akm({isText:e,isAttribute:t}){return e?lQ.Text:t?lQ.Attribute:lQ.Element}function t8u(e){return typeof e=="object"&&e!=null}function nYr(e,t){if(!(typeof e!="object"||e==null))return e[t]}function _Go(...e){return e.find(t=>t!=null)}var $5u,e8u,alt,clt,iYr=h(()=>{"use strict";Wn();tk();$5u="x-fern-xml-text",e8u="x-fern-xml-list-separator",alt=class extends os{schema;fallbackName;key="xml";constructor({breadcrumbs:t,schema:r,fallbackName:n,context:i}){super({breadcrumbs:t,context:i}),this.schema=r,this.fallbackName=n}convert(){let t=this.getExtensionValue(this.schema);if(t8u(t))return{name:typeof t.name=="string"?t.name:this.fallbackName,namespace:typeof t.namespace=="string"?t.namespace:void 0,prefix:typeof t.prefix=="string"?t.prefix:void 0}}},clt=class extends os{propertySchema;resolvedPropertySchema;key="xml";constructor({breadcrumbs:t,propertySchema:r,resolvedPropertySchema:n,context:i}){super({breadcrumbs:t,context:i}),this.propertySchema=r,this.resolvedPropertySchema=n}convert(){let t=this.propertySchema,r=this.resolvedPropertySchema,n=_Go(this.getExtensionValue(t),this.getExtensionValue(r)),i=_Go(nYr(t,$5u),nYr(r,$5u)),o=_Go(nYr(t,e8u),nYr(r,e8u)),s=t8u(n)?n:{};return{kind:akm({isText:i===!0,isAttribute:s.attribute===!0}),name:typeof s.name=="string"?s.name:void 0,wrapped:typeof s.wrapped=="boolean"?s.wrapped:void 0,listSeparator:typeof o=="string"?o:void 0}}}});var qC={};$(qC,{AudienceExtension:()=>nlt,FernAvailabilityExtension:()=>YJr,FernDiscriminatedExtension:()=>ilt,FernDiscriminatorContextExtension:()=>olt,FernEnumExtension:()=>slt,FernIgnoreExtension:()=>yVe,FernOptionalExtension:()=>XJr,FernTypeExtension:()=>tYr,FernTypeNameExtension:()=>rYr,SdkGroupNameExtension:()=>ZJr,SdkMethodNameExtension:()=>$Jr,ServerFromOperationNameExtension:()=>eYr,XmlPropertyExtension:()=>clt,XmlSchemaExtension:()=>alt});var UGo=h(()=>{"use strict";zGo();V5u();QGo();MGo();LGo();W5u();H5u();K5u();J5u();Y5u();X5u();Z5u();iYr()});function n8u(e){let t=new Map,r=(i,o)=>{if(t.has(i))return t.get(i);let s=e[i];if(s==null||o.has(i))return;o.add(i);let a=n(s,o);return o.delete(i),t.set(i,a),a},n=(i,o)=>{let s=a=>Tw.named({name:i.name,shape:a});switch(i.shape.type){case"object":return s(yD.Object);case"enum":return s(yD.Enum);case"union":return s(yD.Union);case"undiscriminatedUnion":return s(yD.UndiscriminatedUnion);case"alias":{let{resolvedType:a}=i.shape,c=r8u(a);return c!=null?r(c,o):a}default:return}};for(let[i,o]of Object.entries(e)){if(o.shape.type!=="alias"||r8u(o.shape.resolvedType)==null)continue;let s=r(i,new Set);s!=null&&(e[i]={...o,shape:mc.alias({aliasOf:o.shape.aliasOf,resolvedType:s})})}}function r8u(e){if(e.type!=="named")return;let t=e;return e.shape==null&&typeof t.typeId=="string"?t.typeId:void 0}var i8u=h(()=>{"use strict";Wn()});var PJ,o8u=h(()=>{"use strict";Wn();hc();qi();JJr();UGo();i8u();PJ=class extends co{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new CUe(n),this.ir={auth:{docs:void 0,requirement:Zt.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Zt.ErrorDiscriminationStrategy.statusCode(),variables:[],globalParameters:void 0,serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,idempotencyKeyGeneration:void 0,webhookSignatureVerification:void 0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0,casingsConfig:void 0,specVersion:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new yVe({breadcrumbs:[...r,String(i)],operation:n,context:this.context}).convert()).map((n,i)=>this.removeXFernIgnores({document:n,breadcrumbs:[...r,String(i)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([n,i])=>!new yVe({breadcrumbs:[...r,n],operation:i,context:this.context}).convert()).map(([n,i])=>[n,this.removeXFernIgnores({document:i,breadcrumbs:[...r,n]})])):t}finalizeIr(){let t=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.response?.body?.type==="streaming")),r=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.pagination!=null)),n=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.response?.body?.type==="fileDownload"));this.ir.sdkConfig={...this.ir.sdkConfig,hasStreamingEndpoints:t,hasPaginatedEndpoints:r,hasFileDownloadEndpoints:n},iqt(this.ir,{onWarning:a=>this.context.logger.warn(a)}),n8u(this.ir.types);let i={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(i=this.filterIrForAudiences(i)),$Gt({ir:i});let o=this.context.exampleGenerationArgs,s=MLo({ir:i,exampleGeneration:o,logger:this.context.logger});if(this.context.generateV1Examples){let a=tqt({ir:i,exampleGeneration:o});return{...i,...a,...s}}return{...i,...s}}filterIrForAudiences(t){return{...nqt(t,this.irGraph.build()),sdkConfig:t.sdkConfig,subpackages:t.subpackages,rootPackage:t.rootPackage}}async resolveAllExternalRefs({spec:t}){let r=[t];for(let n=0;n<r.length;n++){let i=r[n];i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let n=0;n<t.length;n++)t[n]=await this.resolveReferenceChain(t[n],r)}async resolveExternalRefsInObject(t,r){for(let[n,i]of Object.entries(t))t[n]=await this.resolveReferenceChain(i,r)}async resolveReferenceChain(t,r){let n=t;if(!this.context.isReferenceObject(n))return r.push(n),t;for(;this.context.isReferenceObject(n);){let i=this.context.isExternalReference(n.$ref),o=await this.context.resolveMaybeExternalReference(n);if(o.resolved){if(n=o.value,i)return n}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:n="openapi"}){return n==="openapi"?!r.some(i=>i.url===t.url&&"x-fern-server-name"in i&&"x-fern-server-name"in t&&i["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(i=>i.url===t.url&&"name"in i&&"name"in t&&i.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:n,endpointGroupDisplayName:i,endpointGroupDescription:o,serviceName:s,inlinedRequestPropertiesByAudience:a,queryParametersByAudience:c}){let u=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),l=this.getOrCreatePackage({group:n});l!==this.ir.rootPackage&&l.docs==null&&o!=null&&(l.docs=o);let p=[...u].map(m=>this.context.casingsGenerator.generateName(m)),d=p[p.length-1];l.service==null&&(l.service=s??`service_${u.map(m=>ti(m)).join("/")}`),this.ir.services[l.service]==null&&(this.ir.services[l.service]=this.createNewService({allParts:p,finalpart:d,endpointGroupDisplayName:i})),this.ir.services[l.service]?.endpoints.push(t);let f=this.ir.services[l.service];f!=null&&(this.irGraph.addEndpoint(f,t),this.irGraph.markEndpointForAudience(f.name,[t],r),a!=null&&Object.keys(a).length>0&&this.irGraph.markInlinedRequestPropertiesForAudiences(t.id,a),c!=null&&Object.keys(c).length>0&&this.irGraph.markQueryParametersForAudiences(t.id,c))}addWebhookToIr({webhook:t,operationId:r,audiences:n,group:i,inlinedPayloadPropertiesByAudience:o}){let s=i?.join(".")??r,a=this.getOrCreatePackage({group:i});this.ir.webhookGroups[s]==null&&(this.ir.webhookGroups[s]=[]),this.ir.webhookGroups[s].push(t),a.webhooks=s;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),n!=null&&this.irGraph.markWebhookForAudiences(c,t,n),t.id!=null&&o!=null&&Object.keys(o).length>0&&this.irGraph.markInlinedWebhookPayloadPropertiesForAudiences(t.id,o)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:n,websocketGroup:i}){let o=ti(i?.join(".")),s=ti(r),a=this.context.namespace?`${ti(this.context.namespace)}/`:"",c=o?`channel_${a}${o}`:`channel_${a}${s}`,u=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[s]});this.ir.websocketChannels={...this.ir.websocketChannels,[c]:t},c!==""?u.websocket==null&&(u.websocket=c):this.ir.rootPackage.websocket="";let l=this.context.createFernFilepath();this.irGraph.addChannel(l,c,t),n!=null&&this.irGraph.markChannelForAudiences(l,c,n)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,t==null)return;let n=t.environments.environments,i=r==null||n.every(o=>o.audiences==null);for(let o of n)this.irGraph.markEnvironmentForAudiences(o,r?.[o.id]??[],i)}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:n,inlinedTypes:i}=r,o=this.context.getNamespacedSchemaId(t),a=Object.keys(i).some(c=>c===o)?`${o}Wrapper`:o;this.addTypeToPackage(a),this.addTypesToIr({...i,[a]:n})}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let n of r.endpoints)n.baseUrl==null&&(n.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:n}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:n,basePath:sb(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,hasWebSocketInTree:void 0,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(i=>ti(i))),r.length==0)return this.ir.rootPackage;let n=this.ir.rootPackage;for(let i=0;i<r.length;i++){let o=r[i]??"",a=`subpackage_${r.slice(0,i+1).join("/")}`;this.ir.subpackages[a]==null&&(this.ir.subpackages[a]={name:this.context.casingsGenerator.generateName(o),displayName:void 0,...this.createPackage({name:o})});let c=this.ir.subpackages[a];n.subpackages.includes(a)||n.subpackages.push(a),n=c}return n}}});function bVe(e){return typeof e=="object"&&e!==null&&!("$ref"in e)}function lkm(e){if(!bVe(e))return!1;if("nullable"in e&&e.nullable===!0)return!0;let t=r=>Array.isArray(r)&&r.some(n=>bVe(n)&&n.type==="null");return t(e.anyOf)||t(e.oneOf)}function pkm(e){return e.type==="array"||e.properties||e.oneOf||e.anyOf||e.allOf||e.additionalProperties?!1:!!(e.type==="string"||e.type==="number"||e.type==="integer"||e.type==="boolean"||e.const!==void 0||Array.isArray(e.enum)&&e.enum.length>0)}function a8u(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var ckm,s8u,ukm,Yw,lwe=h(()=>{"use strict";ct();rs();ckm=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/,s8u=new WeakMap,ukm=new Set(["type","properties","required","allOf","description","title","deprecated","readOnly","writeOnly","xml","externalDocs","discriminator"]);Yw=class e extends co{MAX_DEPTH=12;EXAMPLE_STRING=Jo.STRING;EXAMPLE_NUMBER=Jo.DOUBLE;EXAMPLE_BOOLEAN=Jo.BOOLEAN;EXAMPLE_INTEGER=Jo.INT;EXAMPLE_DATE=Jo.DATE;EXAMPLE_DATE_TIME=Jo.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;sharedState;constructor({breadcrumbs:t,context:r,schema:n,example:i,depth:o=0,exampleGenerationStrategy:s,generateOptionalProperties:a=!1,seenRefs:c=new Set}){super({breadcrumbs:t,context:r}),this.example=i,this.schema=n,this.depth=o,this.exampleGenerationStrategy=s,this.generateOptionalProperties=a,this.seenRefs=c;let u=s8u.get(r);u!=null?this.sharedState=u:(this.sharedState={mergedAllOfProperties:new WeakMap,mergeOnlyAllOfSchemas:new WeakMap},s8u.set(r,this.sharedState))}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let n=this.schema.$ref;if(this.seenRefs.has(n))return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(t!=null&&this.context.isReferenceObject(t))return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(t==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]};if(typeof t!="object")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]};if("nullable"in t&&t.nullable===!0&&this.example===null)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.maybeConvertLiteralFernType(t);return r??(Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]})}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof n=="boolean"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n??r,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return n!==void 0&&t.enum?.includes(n)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:r,coerced:!1,usedProvidedExample:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.default;return typeof n=="number"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:n,maximum:i,exclusiveMinimum:o,exclusiveMaximum:s}=r,a;o!=null?typeof o=="boolean"?a=n!=null?n+Math.max(Number.EPSILON,Math.abs(n)*1e-10):void 0:a=o+Math.max(Number.EPSILON,Math.abs(o)*1e-10):n!=null&&(a=n);let c;return s!=null?typeof s=="boolean"?c=i!=null?i-Math.max(Number.EPSILON,Math.abs(i)*Number.EPSILON):void 0:c=s-Math.max(Number.EPSILON,Math.abs(s)*Number.EPSILON):i!=null&&(c=i),a!==void 0&&c!==void 0?(t<a||t>c)&&(t=a+(c-a)/2):a!==void 0&&t<a?t=a+Math.abs(a*.1):c!==void 0&&t>c&&(t=c-Math.abs(c*.1)),Number(Number(t).toPrecision(3))}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??n,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,n=this.example??t.example,o=(Array.isArray(n)?n:[n]).map(c=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:c,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),s=o.every(c=>c?.isValid??!1)&&!r,a=!r&&o.some(c=>c.usedProvidedExample);return{isValid:s,coerced:!1,usedProvidedExample:a,validExample:o.map(c=>c.validExample),errors:s?[]:o.flatMap(c=>c.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,n=this.example===void 0&&this.canGenerateFromMergedAllOf(t),{mergedProperties:i,mergedRequired:o}=this.mergeAllOfProperties(t,new Set,0,n),s=Object.entries(i).map(([y,I])=>{if(typeof I!="object")return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(I)&&!this.isRequiredProperty({key:y,resolvedSchema:t}))return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&"writeOnly"in I&&I.writeOnly===!0)return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in I&&I.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let x=lkm(I),v=!(y in r)||!x&&r[y]==null||x&&r[y]===void 0,S=!o.includes(y);if(v&&S){if(this.example===void 0&&this.generateOptionalProperties){let B=this.maybeResolveSchemaExample(I),R=new e({breadcrumbs:[...this.breadcrumbs,y],context:this.context,schema:I,example:B,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:y,result:R.convert()}}return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let B=r[y],R=B!==void 0?B:this.maybeResolveSchemaExample(I),O=new e({breadcrumbs:[...this.breadcrumbs,y],context:this.context,schema:I,example:R,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:y,result:O}}}),a=n?[]:(t.allOf??[]).map((y,I)=>{let x=this.context.resolveMaybeReference({schemaOrReference:y,breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],skipErrorCollector:!0});return x&&this.isConstraintOnlySchema(x)?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:new e({breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],context:this.context,schema:{...t,...y,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()}),c=this.example!==void 0&&(s.some(({result:y})=>y.usedProvidedExample)||a.some(y=>y.usedProvidedExample)),u=Object.fromEntries(s.map(({key:y,result:I})=>[y,I.validExample]).filter(([y,I])=>I!==void 0));for(let y of a)if(typeof y.validExample=="object"&&y.validExample!==null){let I=y.validExample,x=Object.fromEntries(Object.entries(I).filter(([v,S])=>S!==void 0));for(let[v,S]of Object.entries(x))(!(v in u)||u[v]==null)&&(u[v]=S)}let l=[],p=this.collectAllPropertyKeys(t),d=Object.keys(r).filter(y=>!p.has(y)),f=this.schemaHasPatternProperties(t),m=f?d:[],g=f?[]:d;if(m.forEach(y=>{l.push({key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[y],errors:[]}})}),g.length>0)if(t.additionalProperties===!1)g.forEach(y=>{let I=[...this.breadcrumbs,y].join("."),x={message:`Found unexpected property '${y}' in example. This property does not exist in the schema${I?` at path: ${I}`:""}`,path:[...this.breadcrumbs,y]};l.push({key:y,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[x]}})});else if(t.additionalProperties===!0||t.additionalProperties===void 0)g.forEach(y=>{l.push({key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[y],errors:[]}})});else{let y=t.additionalProperties;g.forEach(I=>{let v=new e({breadcrumbs:[...this.breadcrumbs,I],context:this.context,schema:y,example:r[I],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();l.push({key:I,result:v})})}for(let{key:y,result:I}of l)I.validExample!==void 0&&u[y]===void 0&&(u[y]=I.validExample);let A=s.every(y=>y.result.isValid)&&a.every(y=>y.isValid)&&l.every(({result:y})=>y.isValid);if(Object.keys(u).length===0){let y=a.find(I=>I.validExample!==void 0&&(typeof I.validExample!="object"||I.validExample===null));y&&(u=y.validExample)}return{isValid:A,coerced:!1,usedProvidedExample:c,validExample:u,errors:[...s.flatMap(({result:y})=>y.errors),...a.flatMap(y=>y.errors),...l.flatMap(({result:y})=>y.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((a,c)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${c}]`],context:this.context,schema:{...t,type:a},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),n=r.some(a=>a?.isValid??!1),o=r.find(a=>a.isValid)?.validExample??r[0]?.validExample??null,s=r.some(a=>a.usedProvidedExample);return{isValid:n,coerced:!1,usedProvidedExample:s,validExample:o,errors:n?[]:r.flatMap(a=>a?.errors??[])}}convertUnion({resolvedSchema:t,unionType:r}){let n=r==="oneOf"?t.oneOf:t.anyOf;if(!(r in t)||n==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};let i=this.example!==void 0?this.example:this.maybeResolveSchemaExample(t);if(this.example===void 0){let d=[];for(let m of n){if(!m)continue;let g=this.context.resolveMaybeReference({schemaOrReference:m,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});g&&d.push(g)}if(d.length>0&&d.every(m=>pkm(m))){let m=d.findIndex(g=>a8u(g)!==void 0);if(m!==-1){let g=n[m],A=d[m];if(g&&A){let y=a8u(A),x=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${m}]`],context:this.context,schema:r==="oneOf"?{...t,...g,oneOf:void 0}:g,example:y,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(x.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:x.validExample,errors:[]}}}}}let o=[],s=null,a=null;for(let d=0;d<n.length;d++){let f=n[d];if(!f)continue;let m=r==="oneOf"?{...t,...f,oneOf:void 0}:f,g=i!==void 0?i:this.maybeResolveSchemaExample(m),y=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${d}]`],context:this.context,schema:m,example:g,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(y.isValid&&!y.coerced&&y.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:y.validExample,errors:[]};if(y.isValid&&!y.coerced&&this.example===void 0)return{isValid:!0,coerced:!1,usedProvidedExample:y.usedProvidedExample,validExample:y.validExample,errors:[]};o.push(y),y.isValid&&y.usedProvidedExample&&a===null&&(a=y),y.isValid&&s===null&&(s=y)}let c=a??s,u=c!==null,l=c?.validExample??o[0]?.validExample,p=c?.usedProvidedExample??!1;return{isValid:u,coerced:!1,usedProvidedExample:p,validExample:l,errors:u?[]:o.flatMap(d=>d.errors)}}convertOneOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"oneOf"})}convertAnyOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"anyOf"})}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){if("example"in t)return t.example;if("examples"in t){let n=t.examples;if(Array.isArray(n)&&n.length>0)return n[0];if(n!=null&&typeof n=="object")return Object.values(n)[0]}let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r){let n=r.examples;return Array.isArray(n)&&n.length>0?n[0]:Object.values(n??{})[0]}}}maybeConvertLiteralFernType(t){let r=t["x-fern-type"];if(typeof r!="string")return;let n=r.match(ckm);if(n!=null){if(n[1]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[1],errors:[]};if(n[2]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[2]==="true",errors:[]}}}mergeAllOfProperties(t,r=new Set,n=0,i=!1){if(i){let p=this.sharedState.mergedAllOfProperties.get(t)?.get(n);if(p!=null)return p}let o=t.properties??{},s=t.required??[];if(n>this.MAX_DEPTH||t.allOf==null||t.allOf.length===0){let p={mergedProperties:o,mergedRequired:s};return i&&this.cacheMergedAllOfProperties(t,n,p),p}let a={},c=new Set(s);for(let p of t.allOf){let d=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(d==null)continue;let f=this.context.isReferenceObject(p)?p.$ref:void 0;if(!(f!=null&&r.has(f))){if(d.allOf!=null&&d.allOf.length>0){let m=new Set(r);f!=null&&m.add(f);let g=this.mergeAllOfProperties(d,m,n+1,i);for(let A of g.mergedRequired)c.add(A);for(let[A,y]of Object.entries(g.mergedProperties))if(typeof y=="object"&&y!==null){let I=a[A];I!=null&&bVe(I)&&bVe(y)?a[A]={...I,...y}:a[A]=y}continue}if(d.required!=null)for(let m of d.required)c.add(m);if(d.properties!=null){for(let[m,g]of Object.entries(d.properties))if(typeof g=="object"&&g!==null){let A=a[m];A!=null&&bVe(A)&&bVe(g)?a[m]={...A,...g}:a[m]=g}}}}let u={...o};for(let[p,d]of Object.entries(u)){let f=a[p];if(f==null||!bVe(d))continue;let m="$ref"in f?this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):f;m!=null&&(u[p]={...m,...d})}for(let[p,d]of Object.entries(a))p in u||(u[p]=d);let l={mergedProperties:u,mergedRequired:[...c]};return i&&this.cacheMergedAllOfProperties(t,n,l),l}cacheMergedAllOfProperties(t,r,n){let i=this.sharedState.mergedAllOfProperties.get(t);i!=null?i.set(r,n):this.sharedState.mergedAllOfProperties.set(t,new Map([[r,n]]))}canGenerateFromMergedAllOf(t,r=new WeakSet){if(t.allOf==null||t.allOf.length===0||!this.isMergeOnlyObjectSchema(t))return!1;let n=this.sharedState.mergeOnlyAllOfSchemas.get(t);if(n!=null)return n;if(r.has(t))return!1;r.add(t);let i=t.allOf.every(o=>{let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return s==null||!this.isMergeOnlyObjectSchema(s)?!1:s.allOf==null||s.allOf.length===0?!0:this.canGenerateFromMergedAllOf(s,r)});return r.delete(t),this.sharedState.mergeOnlyAllOfSchemas.set(t,i),i}isMergeOnlyObjectSchema(t){return t.type!=null&&t.type!=="object"||t.type==null&&t.properties==null&&t.allOf==null?!1:Object.keys(t).every(r=>ukm.has(r))}isConstraintOnlySchema(t){if(typeof t!="object"||t===null||t.type!==void 0||t.properties!==void 0||t.allOf!==void 0||t.oneOf!==void 0||t.anyOf!==void 0||"items"in t||t.additionalProperties!==void 0||t.enum!==void 0||t.const!==void 0)return!1;let r=new Set(["required","description","title","deprecated","readOnly","writeOnly","nullable","example","examples","default","minLength","maxLength","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minItems","maxItems","uniqueItems","pattern","format"]),n=Object.keys(t);return n.length>0&&n.every(i=>r.has(i))}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}for(let i of[...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}return n}schemaHasPatternProperties(t,r=new Set){let n=t.patternProperties;if(n&&typeof n=="object"&&Object.keys(n).length>0)return!0;for(let i of[...t.allOf??[],...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)&&(r.add(s),this.schemaHasPatternProperties(o,r)))return!0}}return!1}}});function c8u(e){return SC({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return en.primitive({v1:"BASE_64",v2:xi.base64({})});case"BOOLEAN":return en.primitive({v1:"BOOLEAN",v2:xi.boolean({default:void 0})});case"DATE":return en.primitive({v1:"DATE",v2:xi.date({})});case"DATE_TIME":return en.primitive({v1:"DATE_TIME",v2:xi.dateTime({})});case"DATE_TIME_RFC_2822":return en.primitive({v1:"DATE_TIME_RFC_2822",v2:xi.dateTimeRfc2822({})});case"FLOAT":return en.primitive({v1:"FLOAT",v2:xi.float({default:void 0,validation:void 0})});case"DOUBLE":return en.primitive({v1:"DOUBLE",v2:xi.double({default:void 0,validation:void 0})});case"UINT":return en.primitive({v1:"UINT",v2:xi.uint({default:void 0,validation:void 0})});case"UINT_64":return en.primitive({v1:"UINT_64",v2:xi.uint64({default:void 0,validation:void 0})});case"INTEGER":return en.primitive({v1:"INTEGER",v2:xi.integer({default:void 0,validation:void 0})});case"LONG":return en.primitive({v1:"LONG",v2:xi.long({default:void 0,validation:void 0})});case"STRING":return en.primitive({v1:"STRING",v2:xi.string({default:void 0,validation:void 0})});case"UUID":return en.primitive({v1:"UUID",v2:xi.uuid({})});case"BIG_INTEGER":return en.primitive({v1:"BIG_INTEGER",v2:xi.bigInteger({default:void 0})});default:return}},unknown:()=>en.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return en.container(Ts.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return en.container(Ts.list(t))},optional:t=>{if(t!=null)return en.container(Ts.optional(t))},nullable:t=>{if(t!=null)return en.container(Ts.nullable(t))},set:t=>{if(t!=null)return en.container(Ts.set(t))},literal:t=>en.container(Ts.literal(t._visit({string:r=>cE.string(r),boolean:r=>cE.boolean(r),_other:()=>{throw new T({message:"Unexpected literal type",code:T.Code.InternalError})}}))),named:()=>{}}})}var u8u=h(()=>{"use strict";Io();Wn();Dt()});var pwe,oYr=h(()=>{"use strict";Wn();hc();rs();pwe=class extends co{schema;maybeFernEnum;forwardCompatible;constructor({context:t,breadcrumbs:r,schema:n,maybeFernEnum:i,forwardCompatible:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.maybeFernEnum=i,this.forwardCompatible=o??!1}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(i=>typeof i=="string"||typeof i=="number").map(i=>{let o=i.toString(),s=this.maybeFernEnum?.[o],a=s?.name??o;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:a,wireValue:o}),docs:s?.description,availability:void 0,casing:s?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let n=this.context.getAsString(this.schema.default);return{type:mc.enum({default:n!=null?r.find(i=>ur(i.name)===n):void 0,values:r,forwardCompatible:this.forwardCompatible||void 0})}}}});var sYr,l8u=h(()=>{"use strict";Wn();rs();ult();EVe();sYr=class extends co{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:n}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=n}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=en.container(Ts.map({keyType:co.STRING,valueType:en.unknown()}));return{type:mc.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new rO({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=en.container(Ts.map({keyType:co.STRING,valueType:r.type})),i=new Set;for(let o of r.schema?.typeDeclaration.referencedTypes??[])i.add(o);for(let o of Object.keys(r.inlinedTypes))i.add(o);return F4(r.type,i),{type:mc.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}}});function d8u(e,t,r){let n=m8u(t,r),i={};for(let o of n)i=VGo(i,o);return Akm(i,e),i}function m8u(e,t,r){let n=r??new Set,i=[];for(let o of e)if(Array.isArray(o.allOf)&&o.allOf.length>0){let{allOf:s,...a}=o,c=[];for(let u of s)if("$ref"in u){if(t==null)continue;let l=u.$ref;if(n.has(l))continue;n.add(l);let p=t(u);p!=null&&c.push(p)}else c.push(u);i.push(...m8u(c,t,n)),Object.keys(a).length>0&&i.push(a)}else i.push(o);return i}function VGo(e,t){let r={...e};for(let[n,i]of Object.entries(t)){if(i===void 0||hkm.includes(n))continue;let o=r[n];if(n==="required"){let s=Array.isArray(o)?o:[],a=Array.isArray(i)?i:[];r[n]=[...new Set([...s,...a])];continue}if(n==="properties"){r[n]=gkm(o??{},i);continue}if(n==="items"){Fr(o)&&Fr(i)?r[n]=VGo(o,i):r[n]=i;continue}if(p8u.includes(n)){Fr(o)&&Fr(i)?r[n]=h8u(o,i):r[n]=i;continue}if(f8u.includes(n)){r[n]=!!o||!!i;continue}if(dkm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.max(o,i):r[n]=i;continue}if(mkm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.min(o,i):r[n]=i;continue}r[n]=i}return r}function gkm(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];Fr(o)&&Fr(i)?r[n]=VGo(o,i):r[n]=i}return r}function h8u(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];Fr(o)&&Fr(i)?r[n]=h8u(o,i):r[n]=i}return r}function Akm(e,t){for(let r of fkm){let n=t[r];n!=null&&(e[r]=n)}for(let r of p8u){let n=t[r];n!=null&&(e[r]=n)}for(let r of f8u)t[r]===!0&&(e[r]=!0)}var fkm,p8u,f8u,dkm,mkm,hkm,g8u=h(()=>{"use strict";ct();fkm=["description","title","format","type","discriminator","xml","externalDocs","extensions"],p8u=["example","default"],f8u=["deprecated","readOnly","writeOnly","uniqueItems","nullable"],dkm=["minimum","exclusiveMinimum","minLength","minItems","minProperties"],mkm=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],hkm=["allOf","oneOf","anyOf"]});var llt,GGo=h(()=>{"use strict";ct();Wn();hc();iYr();rs();ult();llt=class extends co{schema;xmlEncoding;constructor({context:t,breadcrumbs:r,schema:n,id:i}){super({context:t,breadcrumbs:r}),this.schema=n,this.xmlEncoding=new alt({breadcrumbs:this.breadcrumbs,schema:n,fallbackName:i,context:t}).convert()}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:mc.object({properties:[],extends:[],extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set,xmlEncoding:this.xmlEncoding};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:o}=IVe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null}),s=[],a=i,c=this.schema.required!=null&&this.schema.required.length>0,u=n,l=o,p={};for(let d of this.schema.allOf??[])if(this.context.isReferenceObject(d)){let f=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs});if(f?.properties!=null)for(let[m,g]of Object.entries(f.properties))!this.context.isReferenceObject(g)&&p[m]==null&&(p[m]=g)}for(let[d,f]of(this.schema.allOf??[]).entries()){let m=[...this.breadcrumbs,"allOf",d.toString()],g,A=!1;if(this.context.isReferenceObject(f)){let R=this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:m});if(R==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${d}] reference could not be resolved. Skipping: ${JSON.stringify(f)}`);continue}if(g=R,typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0),!c||Object.keys(g.properties??{}).every(D=>!this.schema.required?.includes(D))){this.addTypeReferenceToExtends({reference:f,breadcrumbs:m,extends_:s,referencedTypes:a});continue}}else g=f,A=!0;typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0);let y=g.oneOf??g.anyOf;if(y!=null&&g.type==null&&g.properties==null){let R=new Set(r.map(D=>ur(D.name)));for(let[D,O]of y.entries()){let z=[...m,g.oneOf!=null?"oneOf":"anyOf",D.toString()],Y=this.context.isReferenceObject(O)?this.context.resolveMaybeReference({schemaOrReference:O,breadcrumbs:z}):O;if(Y==null)continue;let te={};for(let[Re,ce]of Object.entries(Y.properties??{}))!this.context.isReferenceObject(ce)&&"not"in ce||(te[Re]=ce);let ee=Object.keys(te).filter(Re=>!R.has(Re));if(ee.length===0)continue;let se={};for(let Re of ee){let ce=te[Re];ce!=null&&(se[Re]=ce,R.add(Re))}let{convertedProperties:le,inlinedTypesFromProperties:oe,referencedTypes:me,propertiesByAudience:Se}=IVe({properties:se,required:[],breadcrumbs:z,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...le),u={...u,...oe},l={...l,...Se},me.forEach(Re=>{a.add(Re)})}continue}let I=g.properties??{};if(A){I={};for(let[R,D]of Object.entries(g.properties??{})){let O=p[R];O!=null&&!this.context.isReferenceObject(D)?I[R]={...O,...D}:I[R]=D}}let{convertedProperties:x,inlinedTypesFromProperties:v,referencedTypes:S,propertiesByAudience:B}=IVe({properties:I,required:[...this.schema.required??[],...g.required??[],...mfe(g)],breadcrumbs:m,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...x),u={...u,...v},l={...l,...B},S.forEach(R=>{a.add(R)})}for(let d of Object.keys(u))a.add(d);return{type:mc.object({properties:r,extends:s.map(d=>this.context.typeReferenceToDeclaredTypeName(d)).filter(ga),extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:l,referencedTypes:a,inlinedTypes:u,xmlEncoding:this.xmlEncoding}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:n,referencedTypes:i}){let o=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});o.ok&&n.push(o.reference);let s=this.context.getTypeIdFromSchemaReference(t);s!=null&&i.add(s)}}});function ykm(e){return e.type==="union"&&e.types.length===0}function bkm({schema:e,discriminantProperty:t}){let r=e.properties?.[t];if(r==null||"$ref"in r)return;let n=r.const;if(typeof n=="string")return n;if(r.enum?.length===1&&typeof r.enum[0]=="string")return r.enum[0]}var vVe,qGo=h(()=>{"use strict";Wn();QGo();MGo();LGo();rs();ult();oYr();aYr();EVe();vVe=class extends co{schema;id;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlinedTypes:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i}convert(){if(this.shouldConvertAsNullableSchemaOrReference())return this.convertAsNullableSchemaOrReference();if(new ilt({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1)return this.convertAsUndiscriminatedUnion();if(this.schema.discriminator!=null){let n=this.convertAsDiscriminatedUnion();return n!=null&&!ykm(n.type)?n:this.convertAsUndiscriminatedUnion()??n}if(this.context.settings.inferForwardCompatible){let n=this.convertAsOpenEndedEnum();if(n!=null)return n}return this.convertAsUndiscriminatedUnion()}convertAsOpenEndedEnum(){let t=this.schema.oneOf??this.schema.anyOf;if(t==null||t.length!==2)return;let r,n=!1;for(let c of t){let u;if(this.context.isReferenceObject(c)){let l=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});l.resolved&&(u=l.value)}else u=c;u!=null&&(u.enum!=null&&u.enum.length>1&&(u.type==="string"||u.type==null)?r=u:u.type==="string"&&u.enum==null&&(n=!0))}if(r==null||!n)return;let o=new slt({breadcrumbs:this.breadcrumbs,schema:r,context:this.context}).convert(),a=new pwe({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,maybeFernEnum:o,forwardCompatible:!0}).convert();if(a!=null)return{...a,referencedTypes:new Set,inlinedTypes:{}}}getEnclosingComponentRef(){let[t,r,n]=this.breadcrumbs;return t==="components"&&r==="schemas"&&n!=null?`#/components/schemas/${n}`:void 0}filterDiscriminantFromSchema(t,r){if(t.properties==null||!(r in t.properties))return t;let{[r]:n,...i}=t.properties,o=t.required?.filter(s=>s!==r);return{...t,properties:i,required:o}}getVariants(t){let r=this.schema.discriminator?.mapping;if(r!=null){let o=[];for(let[s,a]of Object.entries(r)){let c=this.context.getTypeIdFromSchemaReference({$ref:a});c!=null&&o.push({discriminant:s,typeId:c,ref:a,schema:this.resolveVariantSchema({$ref:a}),breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",s]})}return o}let n=this.schema.oneOf??this.schema.anyOf??[],i=[];for(let[o,s]of n.entries()){let a=this.resolveVariantSchema(s),c=a!=null?bkm({schema:a,discriminantProperty:t}):void 0;if(!this.context.isReferenceObject(s)){if(c==null)return[];i.push({discriminant:c,typeId:this.context.convertBreadcrumbsToName([`${this.id}_${o}`]),schema:a,breadcrumbs:[...this.breadcrumbs,`oneOf[${o}]`]});continue}let u=s.$ref,l=u.split("/").pop(),p=this.context.getTypeIdFromSchemaReference(s),d=c??l;if(p==null||d==null)return[];i.push({discriminant:d,typeId:p,ref:u,schema:a,breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]})}return i}resolveVariantSchema(t){if(!this.context.isReferenceObject(t))return t;let r=this.context.resolveReference({reference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return r.resolved?r.value:void 0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=this.schema.discriminator.propertyName,r=[],n=new Set,i={};for(let{discriminant:l,typeId:p,ref:d,schema:f,breadcrumbs:m}of this.getVariants(t)){let g=d!=null?{$ref:d}:f,A=p!=null&&this.context.discriminatedVariantsInProgress.has(p),y=d!=null&&d===this.getEnclosingComponentRef(),I=f?.properties!=null&&t in f.properties&&!((A||y)&&d!=null);if(I&&f!=null&&(g=this.filterDiscriminantFromSchema(f,t)),g==null)continue;let x=new rO({context:this.context,schemaOrReference:g,schemaIdOverride:p??void 0,breadcrumbs:m});p!=null&&n.add(p);let v=I&&p!=null&&!A;v&&this.context.discriminatedVariantsInProgress.add(p);let S;try{S=x.convert()}finally{v&&this.context.discriminatedVariantsInProgress.delete(p)}if(S?.type!=null&&p!=null){for(let Y of Object.keys(S?.inlinedTypes??{}))n.add(Y);for(let Y of S.schema?.typeDeclaration.referencedTypes??[])n.add(Y);let B=this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),R=d?.split("/").pop()??p,D=f?.title,O=f?.description,z=D??l??R;S.schema?.typeDeclaration!=null&&D!=null&&(S.schema.typeDeclaration.name.displayName=D),r.push({docs:O,discriminantValue:B,availability:S.availability,displayName:z,shape:iT.samePropertiesAsObject({typeId:p,name:this.context.casingsGenerator.generateName(R),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:z})}),i={...i,...S.inlinedTypes}}}let{convertedProperties:o,referencedTypes:s,inlinedTypesFromProperties:a}=IVe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});n=new Set([...n,...s]);let c=[];for(let[l,p]of(this.schema.allOf??[]).entries()){let d=[...this.breadcrumbs,"allOf",l.toString()];if(this.context.isReferenceObject(p)){let f=this.context.convertReferenceToTypeReference({reference:p,breadcrumbs:d});if(f.ok){let g=this.context.typeReferenceToDeclaredTypeName(f.reference);g!=null&&c.push(g)}let m=this.context.getTypeIdFromSchemaReference(p);m!=null&&n.add(m);continue}}for(let l of Object.keys({...i,...a}))n.add(l);let u=new olt({context:this.context,breadcrumbs:[...this.breadcrumbs,"discriminator"],node:this.schema.discriminator});return{type:mc.union({baseProperties:o,inheritedBaseProperties:[],discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:r,default:void 0,discriminatorContext:u.convert()}),referencedTypes:n,inlinedTypes:{...i,...a}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,n={};for(let[a,c]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(c)){let g;if(this.context.isReferenceObjectWithIdentifier(c))g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:c.summary??c.title??c.name??c.messageId,displayNameOverrideSource:"reference_identifier"});else{let y=this.getDiscriminatorKeyForRef(c);y!=null?g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:y,displayNameOverrideSource:"discriminator_key"}):g=this.context.convertReferenceToTypeReference({reference:c,breadcrumbs:this.breadcrumbs})}if(g.ok){let y=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs}),I=y.resolved?y.value.description:void 0;t.push({type:g.reference,docs:I})}let A=this.context.getTypeIdFromSchemaReference(c);A!=null&&r.add(A);continue}let l=Object.keys(this.schema.properties??{}).length>0?void 0:this.extendSubSchema(c),p=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),d=c.title,m=new fwe({context:this.context,id:p,nameOverride:d,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:l??c}).convert();if(m!=null){let g=m.convertedSchema.typeDeclaration.shape;if(g.type==="alias"&&this.typeReferenceIsWrappedPrimitive(g.aliasOf))t.push({type:g.aliasOf,docs:c.description});else if(g.type==="object"&&g.properties.length===0&&g.extends.length===0)t.push({type:en.container(Ts.map({keyType:co.STRING,valueType:en.unknown()})),docs:c.description});else{t.push({type:this.context.createNamedTypeReference(p,d),docs:c.description});let A=this.context.getNamespacedSchemaId(p);n={...n,...m.inlinedTypes,[A]:m.convertedSchema},r.add(A);for(let y of Object.keys(m.inlinedTypes))r.add(y)}m.convertedSchema.typeDeclaration.referencedTypes.forEach(A=>{r.add(A)})}}let{convertedProperties:i,referencedTypes:o,inlinedTypesFromProperties:s}=IVe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});for(let a of Object.keys(s))r.add(a);for(let a of o)r.add(a);return{type:mc.undiscriminatedUnion({members:t,baseProperties:i.length>0?i:void 0}),referencedTypes:r,inlinedTypes:{...n,...s}}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let n=t.filter(i=>!(typeof i=="object"&&i!==null&&"type"in i&&i.type==="null"));if(n.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return n.length===1?{...this.schema,[r]:void 0,...n[0]}:{...this.schema,[r]:n}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let n=new rO({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:mc.alias({aliasOf:i,resolvedType:i}),referencedTypes:n.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:n.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return en.container(Ts.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,n])=>n===t.$ref)?.[0]}}});var plt,WGo=h(()=>{"use strict";Wn();rs();plt=class extends co{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return en.container(Ts.literal(cE.string(t)));if(this.schema.format==="date-time-rfc-2822")return en.primitive({v1:As.DateTimeRfc2822,v2:xi.dateTimeRfc2822({})});if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return en.primitive({v1:As.Date,v2:xi.date({})});if(this.schema.format==="date-time")return en.primitive({v1:As.DateTime,v2:xi.dateTime({})})}return en.primitive({v1:"STRING",v2:xi.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return en.primitive({v1:"DOUBLE",v2:xi.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return en.primitive({v1:"FLOAT",v2:xi.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return en.primitive({v1:"INTEGER",v2:xi.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return en.primitive({v1:"LONG",v2:xi.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return en.primitive({v1:"UINT",v2:xi.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return en.primitive({v1:"UINT_64",v2:xi.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return en.primitive({v1:"DOUBLE",v2:xi.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return en.primitive({v1:"DOUBLE",v2:xi.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return en.primitive({v1:"FLOAT",v2:xi.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return en.primitive({v1:"INTEGER",v2:xi.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return en.primitive({v1:"LONG",v2:xi.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return en.primitive({v1:"UINT",v2:xi.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return en.primitive({v1:"UINT_64",v2:xi.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return en.primitive({v1:"INTEGER",v2:xi.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?en.container(Ts.literal(cE.boolean(t))):en.primitive({v1:"BOOLEAN",v2:xi.boolean({default:this.context.getAsBoolean(this.schema.default)})})}default:return}}getNumberValidation(t){let r=t.minimum,n=t.maximum,i,o;return typeof t.exclusiveMinimum=="boolean"?i=t.exclusiveMinimum:typeof t.exclusiveMinimum=="number"&&(r=t.exclusiveMinimum,i=!0),typeof t.exclusiveMaximum=="boolean"?o=t.exclusiveMaximum:typeof t.exclusiveMaximum=="number"&&(n=t.exclusiveMaximum,o=!0),{max:n,min:r,exclusiveMax:o,exclusiveMin:i,multipleOf:t.multipleOf}}getStringValidation(t){let r=t.format??(t.contentMediaType==="application/octet-stream"?"binary":void 0);return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:r}}}});function Ikm(e){let t=mfe(e);return t.length===0?e:{...e,required:[...new Set([...e.required??[],...t])]}}var Ekm,fwe,aYr=h(()=>{"use strict";ct();Wn();rs();ult();u8u();lwe();HGo();oYr();l8u();g8u();GGo();qGo();WGo();Ekm=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],fwe=class e extends co{static MAX_DISTRIBUTED_VARIANTS=64;schema;id;inlined;audiences;nameOverride;visitedRefs;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlined:o=!1,nameOverride:s,visitedRefs:a}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i,this.inlined=o,this.nameOverride=s,this.visitedRefs=a??new Set,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertReferenceSchema();if(r!=null)return r;let n=this.tryConvertEnumSchema();if(n!=null)return n;let i=this.tryDistributeAllOfOverOneOf();if(i!=null)return i;let o=this.tryConvertSingularAllOfSchema();if(o!=null)return o;let s=this.tryConvertPrimitiveSchema();if(s!=null)return s;let a=this.tryConvertArraySchema();if(a!=null)return a;let c=this.tryConvertTypeArraySchema();if(c!=null)return c;let u=this.tryConvertSiblingAnyOfConstraint();if(u!=null)return u;let l=this.tryConvertSiblingOneOfConstraint();if(l!=null)return l;let p=this.tryConvertOneOfAnyOfSchema();if(p!=null)return p;let d=this.tryConvertMapSchema();if(d!=null)return d;let f=this.tryConvertDiscriminatorMappingSchema();if(f!=null)return f;let m=this.tryConvertObjectAllOfSchema();if(m!=null)return m;let g=this.tryConvertUntypedSchema();if(g!=null)return g;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertReferenceSchema(){if(!this.context.isReferenceObject(this.schema))return;let t=this.schema;if(this.visitedRefs.has(t.$ref)||t.$ref===`#/components/schemas/${this.id}`)return;let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(!r.ok)return;let n=new Set;return F4(r.reference,n),{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:mc.alias({aliasOf:r.reference,resolvedType:r.reference}),referencedTypes:n}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes??{}}}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new qC.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new pwe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:i.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.schema.allOf[0];if(this.context.isReferenceObject(r)){let i=r.$ref;if(this.visitedRefs.has(i))return}let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:this.breadcrumbs});if(n!=null){let i=this.context.isReferenceObject(r)?new Set([...this.visitedRefs,r.$ref]):this.visitedRefs,s=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:n,id:this.id,inlined:this.inlined,visitedRefs:i}).convert();if(s?.convertedSchema.typeDeclaration?.shape.type!=="object"){if(s!=null){let a=s.convertedSchema.typeDeclaration;this.schema.description!=null&&a.docs==null&&(a.docs=this.schema.description);let c=this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs});c!=null&&a.availability==null&&(a.availability=c)}return s}}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r=new Set,n=[],i=!1;for(let c of this.schema.allOf??[]){let u;if(this.context.isReferenceObject(c)){let p=c.$ref;if(this.visitedRefs.has(p)){i=!0;break}if(r.has(p))continue;r.add(p);let d=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(d==null)return;u=d}else u=c;let l=u.oneOf??u.anyOf;if(!this.context.isReferenceObject(c)&&l!=null&&u.type==null&&u.properties==null){let p={};for(let d of l){let f=this.context.isReferenceObject(d)?this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs}):d;if(f!=null)for(let[m,g]of Object.entries(f.properties??{}))!this.context.isReferenceObject(g)&&"not"in g||m in p||(p[m]=g)}Object.keys(p).length>0&&n.push({properties:p});continue}n.push(Ikm(u))}if(i)return;let o=d8u(this.schema,n,c=>{let u=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(!(u!=null&&this.context.isReferenceObject(u)))return u}),s=new Set([...this.visitedRefs,...r]);return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:o,id:this.id,inlined:this.inlined,visitedRefs:s}).convert()}}tryDistributeAllOfOverOneOf(){if(!this.context.settings.preserveOneOfInAllOf)return;let t=this.schema.allOf;if(!Array.isArray(t)||t.length===0||this.schema.oneOf!=null||this.schema.anyOf!=null)return;let r=this.getDistributableUnions(t),n=r[0];if(n==null)return;let i=r.reduce((c,u)=>c*u.variants.length,1);if(i>e.MAX_DISTRIBUTED_VARIANTS){this.context.logger.warn(`Not distributing allOf over its ${r.length} unions at ${this.breadcrumbs.join(".")}: it would produce ${i} variants (max ${e.MAX_DISTRIBUTED_VARIANTS}).`);return}let o=t.filter((c,u)=>u!==n.index);(this.schema.properties!=null||this.schema.required!=null)&&o.push({type:"object",properties:this.schema.properties,required:this.schema.required});let s={...this.schema};return delete s.allOf,delete s.properties,delete s.required,new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:{...s,oneOf:n.variants.map(c=>{let u=this.getVariantTitle(c);return{...u!=null?{title:u}:{},allOf:[c,...o]}})},id:this.id,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}getVariantTitle(t){return this.context.isReferenceObject(t)?this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs})?.title??t.$ref.split("/").pop():t.title}getDistributableUnions(t){let r=[];for(let[n,i]of t.entries()){let o=this.context.isReferenceObject(i)?this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs}):i;if(o==null||o.properties!=null||o.type!=null&&o.type!=="object"||o.discriminator!=null)continue;let s=o.oneOf??o.anyOf;s==null||s.length===0||r.push({index:n,variants:s})}return r}tryConvertPrimitiveSchema(){let r=new plt({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:mc.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new flt({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:mc.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertSiblingAnyOfConstraint(){if(!this.context.settings.anyOfSiblingPropertiesAsObject||!$Me(this.schema))return;this.context.logger.debug(`Treating the anyOf at ${this.breadcrumbs.join(".")} as an "at least one of" constraint over its sibling properties rather than a union, and converting the schema as an object.`);let{anyOf:t,...r}=this.schema;return new e({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:r,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}tryConvertSiblingOneOfConstraint(){if(!eLe(this.schema)||new qC.FernDiscriminatedExtension({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!0)return;this.context.logger.debug(`Treating the oneOf at ${this.breadcrumbs.join(".")} as an "exactly one of" constraint over its sibling properties rather than a union, and converting the schema as an object.`);let r=mfe(this.schema),{oneOf:n,...i}=this.schema;return r.length>0&&(i.required=[...new Set([...i.required??[],...r])]),new e({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:i,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new vVe({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new sYr({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertDiscriminatorMappingSchema(){if(this.schema.discriminator?.mapping!=null&&Object.keys(this.schema.discriminator.mapping).length>0&&this.schema.oneOf==null&&this.schema.anyOf==null){let t={...this.schema,oneOf:Object.values(this.schema.discriminator.mapping).map(i=>({$ref:i}))},n=new vVe({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:t,inlinedTypes:{}}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:n.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:n.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new llt({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,id:this.id}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes,encoding:r.xmlEncoding!=null?{json:void 0,proto:void 0,xml:r.xmlEncoding}:void 0}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:mc.alias({aliasOf:en.unknown(),resolvedType:en.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new qC.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=c8u(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:mc.alias({aliasOf:n,resolvedType:n}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:n,encoding:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:i,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:n?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){let t=this.context.getRawSchemaId(this.id);return{typeId:this.context.getNamespacedSchemaId(this.id),fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(t),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...Ekm,...t];return Object.keys(this.schema).every(i=>r.includes(i))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let n=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:n},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[n,i]of t.entries()){let o=this.context.resolveExample(i),s=`${this.id}_example_${n}`,a=this.generateOrValidateExample({example:o,exampleName:s});r[s]=a}return r}generateOrValidateExample({example:t}){let r=new Yw({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n}=r.convert();return n}}});function Ckm(e){return Object.keys(e).every(t=>vkm.has(t))}var rO,vkm,EVe=h(()=>{"use strict";Wn();rs();aYr();rO=class extends co{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:n,schemaIdOverride:i,wrapAsOptional:o=!1,wrapAsNullable:s=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=n,this.schemaIdOverride=i,this.wrapAsOptional=o,this.wrapAsNullable=s}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{},availability:this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs})}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null)return;if(this.schemaOrReference.allOf.length===1){let i=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(i)){let o=this.context.convertReferenceToTypeReference({reference:i,breadcrumbs:this.breadcrumbs});if(o.ok)return{type:this.wrapTypeReference(o.reference),inlinedTypes:o.inlinedTypes??{},availability:this.getAvailabilityOfSelfOrReference(i)}}return}let t=this.schemaOrReference.allOf.filter(i=>this.context.isReferenceObject(i)),r=this.schemaOrReference.allOf.filter(i=>typeof i=="object"&&i!==null&&!this.context.isReferenceObject(i)),n=t.length===1?t[0]:void 0;if(n!=null&&r.every(i=>Ckm(i))){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(i!=null&&i.type!=="object"&&!i.properties&&!i.allOf&&!i.oneOf&&!i.anyOf&&!i.format){let o=this.context.convertReferenceToTypeReference({reference:n,breadcrumbs:this.breadcrumbs});if(o.ok)return{type:this.wrapTypeReference(o.reference),inlinedTypes:o.inlinedTypes??{},availability:this.getAvailabilityOfSelfOrReference(n)}}}}getAvailabilityOfSelfOrReference(t){for(let r of[...this.getSelfAndInlineAllOfElements(),t]){let n=this.context.getAvailability({node:r,breadcrumbs:this.breadcrumbs});if(n!=null)return n}}getSelfAndInlineAllOfElements(){return this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null?[this.schemaOrReference]:[this.schemaOrReference,...this.schemaOrReference.allOf.filter(t=>!this.context.isReferenceObject(t))]}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),n=this.context.getNamespacedSchemaId(r),i=new fwe({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),o=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),s=i.convert();if(s!=null){let a=s.convertedSchema.typeDeclaration.shape;return a.type==="alias"?{type:this.wrapTypeReference(a.aliasOf),schema:s.convertedSchema,inlinedTypes:s.inlinedTypes,availability:o}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:s.convertedSchema,inlinedTypes:{...s.inlinedTypes,[n]:s.convertedSchema},availability:o}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return en.container(Ts.optional(t))}wrapInNullable(t){return en.container(Ts.nullable(t))}},vkm=new Set(["description","title","deprecated","readOnly","writeOnly","xml","externalDocs","x-fern-type-name"])});function IVe({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i,withinXmlElement:o=!1}){let s=[],a={},c={},u=new Set;for(let[l,p]of Object.entries(e??{})){let d=[...r,"properties",l];if(typeof p!="object"){i.collect({message:`Schema property ${l} should be an object`,path:d});continue}let f=Skm(r,p,n)??n.convertBreadcrumbsToName(d),m="nullable"in p?p.nullable:!1,A=new rO({context:n,breadcrumbs:d,schemaOrReference:p,schemaIdOverride:f,wrapAsOptional:!t.includes(l),wrapAsNullable:m}).convert();if(A!=null){let y=n.resolveMaybeReference({schemaOrReference:p,breadcrumbs:d,skipErrorCollector:!0});s.push({name:n.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),valueType:A.type,docs:p.description??A.schema?.typeDeclaration.docs,availability:A.availability,propertyAccess:n.getPropertyAccess(p),defaultValue:y?.default,xml:o?new clt({breadcrumbs:d,propertySchema:p,resolvedPropertySchema:y??void 0,context:n}).convert():void 0,v2Examples:A.schema?.typeDeclaration?.v2Examples??xkm({propertySchema:p,breadcrumbs:d,context:n,propertyId:f})}),a={...a,...A.inlinedTypes},A.schema?.typeDeclaration.referencedTypes!=null&&A.schema.typeDeclaration.referencedTypes.forEach(I=>{u.add(I)}),F4(A.type,u);for(let I of A.schema?.audiences??[])c[I]==null&&(c[I]=new Set),c[I].add(l)}}for(let l of Object.keys(a))u.add(l);return{convertedProperties:s,propertiesByAudience:c,inlinedTypesFromProperties:a,referencedTypes:u}}function xkm({propertySchema:e,breadcrumbs:t,context:r,propertyId:n}){let i=r.resolveMaybeReference({schemaOrReference:e,breadcrumbs:t,skipErrorCollector:!0}),o=r.getExamplesFromSchema({schema:i??void 0,breadcrumbs:t});if(o.length>0){let u={};for(let[l,p]of o.entries()){let d=r.resolveExample(p),f=`${n}_example_${l}`,m=new Yw({breadcrumbs:t,context:r,schema:e,example:d}),{validExample:g}=m.convert();u[f]=g}return{userSpecifiedExamples:u,autogeneratedExamples:{}}}let s=`${n}_example_autogenerated`,a=new Yw({breadcrumbs:t,context:r,schema:e,example:void 0,generateOptionalProperties:!0}),{validExample:c}=a.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{[s]:c}}}function Skm(e,t,r){return r.isReferenceObject(t)?void 0:new qC.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}function F4(e,t){switch(e.type){case"named":t.add(e.typeId);return;case"primitive":case"unknown":return;case"container":wkm(e.container,t);return}}function wkm(e,t){switch(e.type){case"list":F4(e.list,t);return;case"set":F4(e.set,t);return;case"optional":F4(e.optional,t);return;case"nullable":F4(e.nullable,t);return;case"map":F4(e.keyType,t),F4(e.valueType,t);return;case"literal":return}}var ult=h(()=>{"use strict";lwe();EVe();iYr();rs()});var flt,HGo=h(()=>{"use strict";Wn();rs();ult();EVe();flt=class e extends co{static LIST_UNKNOWN=en.container(Ts.list(en.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new rO({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let n=new Set;for(let i of r.schema?.typeDeclaration.referencedTypes??[])n.add(i);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(i=>{i.typeDeclaration.referencedTypes.forEach(o=>{n.add(o)})}),F4(r.type,n),{typeReference:en.container(Ts.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}}});var KGo={};$(KGo,{ArraySchemaConverter:()=>flt,EnumSchemaConverter:()=>pwe,ObjectSchemaConverter:()=>llt,OneOfSchemaConverter:()=>vVe,PrimitiveSchemaConverter:()=>plt,SchemaConverter:()=>fwe,SchemaOrReferenceConverter:()=>rO});var JGo=h(()=>{"use strict";HGo();oYr();GGo();qGo();WGo();aYr();EVe()});var cYr,A8u=h(()=>{"use strict";qi();rs();lwe();JGo();cYr=class extends co{group;method;constructor({context:t,breadcrumbs:r,group:n,method:i}){super({context:t,breadcrumbs:r}),this.group=n,this.method=i}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:n,schemaId:i}){if(t.schema==null)return;if(r){let c=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",n]});if(c==null)return;t.schema=c}let s=new rO({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",n,"schema"],schemaOrReference:t.schema,schemaIdOverride:i}).convert();if(s==null)return;let a=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([c,u])=>{if(this.context.isReferenceObject(u)){let l=this.context.resolveReference({reference:u,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return l.resolved?[c,l.value.value??l.value]:null}return[c,u.value??u]}).filter(c=>c!=null)):void 0;return{...s,examples:a}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new rO({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(i!=null)return{...i,examples:void 0}}getIdForExample({key:t,example:r,usedExampleNames:n}){if(this.context.isExampleWithSummary(r)){let i=r.summary;if(!n.has(i))return i;let o=`${i} (${t})`;return n.has(o)?t:o}return t}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t?.schema,s=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),a=new Set;for(let[c,u]of s){let l=this.context.resolveExampleWithValue(u),p=this.context.resolveExampleRecursively({example:u,breadcrumbs:this.breadcrumbs}),d=this.getIdForExample({key:c,example:p,usedExampleNames:a});a.add(d),l!=null&&(o!=null?i.userSpecifiedExamples[d]=this.generateOrValidateExample({schema:o,example:l,exampleGenerationStrategy:n,exampleName:d}):i.userSpecifiedExamples[d]=l)}if(o!=null&&Object.keys(i.userSpecifiedExamples).length===0){let c=this.getExamplesFromSchemaOrReference(o);c.length>1&&c.forEach((u,l)=>{let p=`Example ${l+1}`;i.userSpecifiedExamples[p]=this.generateOrValidateExample({schema:o,example:u,exampleGenerationStrategy:n,exampleName:p})})}if(Object.keys(i.userSpecifiedExamples).length===0&&o!=null){let c=ti(`${[...this.group,this.method].join("_")}_example`);i.autogeneratedExamples[c]=this.generateOrValidateExample({schema:o,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:n,exampleName:c})}return i}getExamplesFromSchemaOrReference(t){let r=new Set,n=t;for(;this.context.isReferenceObject(n);){if(r.has(n.$ref))return[];r.add(n.$ref);let i=this.context.resolveReference({reference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(!i.resolved)return[];n=i.value}return this.context.getExamplesFromSchema({schema:n,breadcrumbs:this.breadcrumbs})}generateOrValidateExample({schema:t,example:r,generateOptionalProperties:n,exampleGenerationStrategy:i}){let o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o==null)return;let s=this.context.getExamplesFromSchema({schema:o,breadcrumbs:this.breadcrumbs}),a=new Yw({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??s[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:i}),{validExample:c}=a.convert();return c}}});var uYr,y8u=h(()=>{"use strict";rs();lwe();uYr=class extends co{parameter;constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r}),this.parameter=n}convertToOutput({schema:t,typeReference:r,inlinedTypes:n}){let i=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),s=this.getParameterSchemaWithExampleOverride({schema:o}),a=o?.default,c=this.getParameterDescription({schema:t});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:c,valueType:r??co.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,clientDefault:void 0,defaultValue:a,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),availability:i,explode:this.getExplodeForQueryParameter()},inlinedTypes:n};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:c,valueType:r??co.OPTIONAL_STRING,env:void 0,clientDefault:void 0,defaultValue:a,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),availability:i},inlinedTypes:n};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:c,valueType:r??co.STRING,location:"ENDPOINT",variable:void 0,clientDefault:void 0,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),explode:this.getExplodeForPathParameter()},inlinedTypes:n};default:return}}getParameterDescription({schema:t}){if(this.parameter.description!=null)return this.parameter.description;if("description"in t&&typeof t.description=="string")return t.description}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t,originalSchema:r}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,o=this.parameter.examples;for(let[s,a]of Object.entries(o??{})){let c=this.context.resolveExampleWithValue(a);c!=null&&(n.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:t,example:c,exampleName:s}))}if(i!=null){let s=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:t,example:i,exampleName:s})}if(Object.keys(n.userSpecifiedExamples).length===0){let s=this.context.getExamplesFromSchema({schema:this.resolveSchemaChain(r),breadcrumbs:this.breadcrumbs});for(let a of s){let c=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[c]=this.generateOrValidateExample({schema:t,example:this.context.resolveExample(a),exampleName:c})}}if(Object.keys(n.userSpecifiedExamples).length===0){let s=`${this.parameter.name}_example`;n.autogeneratedExamples[s]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0,exampleName:s})}return n}resolveSchemaChain(t){let r=new Set,n=t;for(;this.context.isReferenceObject(n);){if(r.has(n.$ref))return;r.add(n.$ref);let i=this.context.resolveReference({reference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(!i.resolved)return;n=i.value}return n}generateOrValidateExample({schema:t,example:r}){let n=new Yw({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:i}=n.convert();return i}getExplodeForQueryParameter(){let t=this.parameter.style??"form",r=this.parameter.explode;if(r!==void 0)return t==="form"||t==="deepObject"?r===!0?void 0:r:r===!1?void 0:r}getExplodeForPathParameter(){let t=this.parameter.explode;if(t!==void 0)return t===!1?void 0:t}}});var YGo={};$(YGo,{AbstractMediaTypeObjectConverter:()=>cYr,AbstractParameterConverter:()=>uYr});var b8u=h(()=>{"use strict";A8u();y8u()});function dlt({context:e,breadcrumbs:t,headers:r}){let n=[],i={},o=t??[];if(r==null)return{headers:n,inlinedTypes:i};for(let[s,a]of Object.entries(r)){let c=e.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...o,"headers",s]});if(c==null)continue;let u=Tkm({context:e,header:c}),l=u?.schema,p=c.required===!0,d=y=>p?y:en.container(Ts.optional(y)),f=d(co.STRING),m,g=e.getAvailability({node:c,breadcrumbs:[...o,"headers",s]});if(l!=null)if(m=e.resolveMaybeReference({schemaOrReference:l,breadcrumbs:[...o,"headers",s,"schema"]}),m?.type==="number"||m?.type==="integer")f=d(en.primitive({v1:m.type==="integer"?"INTEGER":"DOUBLE",v2:m.type==="integer"?xi.integer({default:void 0,validation:void 0}):xi.double({default:void 0,validation:void 0})}));else if(m?.type==="boolean")f=d(en.primitive({v1:"BOOLEAN",v2:xi.boolean({default:void 0})}));else{let y=new rO({context:e,breadcrumbs:[...o,"headers",s,"schema"],schemaOrReference:l,wrapAsOptional:!p,schemaIdOverride:e.convertBreadcrumbsToName([...o,"headers",s])}).convert();if(y!=null){f=y.type;for(let[I,x]of Object.entries(y.inlinedTypes))i[I]=x}}let A=Okm({context:e,breadcrumbs:o,header:c,headerName:s,schema:l,mediaTypeObject:u?.mediaTypeObject});n.push({name:e.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),docs:c.description,valueType:f,env:void 0,v2Examples:A,availability:g,clientDefault:void 0,defaultValue:m?.default})}return{headers:n,inlinedTypes:i}}function Tkm({context:e,header:t}){if(t.schema!=null)return{schema:t.schema};if(!(!e.settings.respectParameterContent||t.content==null)){for(let[r,n]of Object.entries(t.content))if(n.schema!=null&&of.parse(r)?.isJSON())return{schema:n.schema,mediaTypeObject:n}}}function Okm({context:e,breadcrumbs:t,header:r,headerName:n,schema:i,mediaTypeObject:o}){let s={userSpecifiedExamples:{},autogeneratedExamples:{}},a=r.example,c=r.examples;for(let[u,l]of Object.entries(c??{})){let p=e.resolveExampleWithValue(l);p!=null&&(s.userSpecifiedExamples[u]=sWt({context:e,breadcrumbs:t,schema:i,example:p}))}if(a!=null){let u=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[u]=sWt({context:e,breadcrumbs:t,schema:i,example:a})}if(Object.keys(s.userSpecifiedExamples).length===0&&o!=null)for(let[u,l]of e.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...t,"headers",n,"content"],defaultExampleName:`${n}_example`})){let p=e.resolveExampleWithValue(l);if(p!=null){let d=e.generateUniqueName({prefix:u,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[d]=sWt({context:e,breadcrumbs:t,schema:i,example:p})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let u=e.getExamplesFromSchema({schema:Pkm({context:e,schema:i,breadcrumbs:[...t,"headers",n,"schema"]}),breadcrumbs:[...t,"headers",n,"schema"]});for(let l of u){let p=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[p]=sWt({context:e,breadcrumbs:t,schema:i,example:e.resolveExample(l)})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let u=`${n}_example`;s.autogeneratedExamples[u]=sWt({context:e,breadcrumbs:t,schema:i,example:void 0,ignoreErrors:!0})}return s}function Pkm({context:e,schema:t,breadcrumbs:r}){let n=new Set,i=t;for(;e.isReferenceObject(i);){if(n.has(i.$ref))return;n.add(i.$ref);let o=e.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!o.resolved)return;i=o.value}return i}function sWt({context:e,breadcrumbs:t,schema:r,example:n,ignoreErrors:i}){if(r==null)return n;let o=new Yw({breadcrumbs:t,context:e,schema:r,example:n}),{validExample:s,errors:a}=o.convert();return i||a.forEach(c=>{e.errorCollector.collect({message:c.message,path:c.path})}),s}var E8u=h(()=>{"use strict";ct();Wn();JJr();lwe();EVe()});var lYr,I8u=h(()=>{"use strict";tk();lYr=class extends os{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:n}){super({breadcrumbs:t,context:n}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}}});var v8u,Bkm,N4,C8u=h(()=>{"use strict";ct();Wn();zGo();I8u();rs();v8u="Base",Bkm="x-fern-default-url",N4=class e extends co{servers;endpointLevelServers;baseUrlEnvVar;constructor({breadcrumbs:t,context:r,servers:n,endpointLevelServers:i,baseUrlEnvVar:o}){super({breadcrumbs:t,context:r}),this.servers=n,this.endpointLevelServers=i,this.baseUrlEnvVar=o}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let n=this.getDefaultBaseUrlName(),i={id:n,name:this.context.casingsGenerator.generateName(n)},o=this.endpointLevelServers.map(c=>{let u=e.getServerName({server:c,context:this.context});return{id:u,name:this.context.casingsGenerator.generateName(u)}}).filter((c,u,l)=>l.findIndex(p=>p.id===c.id)===u),s=[i,...o],a=this.servers.map(c=>{let u=e.getServerName({server:c,context:this.context}),l=this.endpointLevelServers?.map(g=>[e.getServerName({server:g,context:this.context}),this.getServerUrl(g)]),p=e.getServerAudiences({server:c,context:this.context}),{defaultUrls:d,urlTemplates:f,urlVariables:m}=this.buildMultiUrlTemplateFields({defaultBaseUrlId:n,topLevelServer:c,endpointServers:this.endpointLevelServers??[]});return{id:u,name:this.context.casingsGenerator.generateName(u),urls:{[n]:this.getServerUrl(c),...Object.fromEntries(l??[])},docs:c.description,audiences:p,defaultUrls:d,urlTemplates:f,urlVariables:m}});return{value:{defaultEnvironment:a[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:sE.multipleBaseUrls({baseUrls:s,environments:a})},defaultUrl:i.id}}let t=this.extractFernDefaultUrl(),r=this.servers.map(n=>{let i=e.getServerName({server:n,context:this.context}),o=e.getServerAudiences({server:n,context:this.context});return n.variables!=null&&Object.keys(n.variables).length>0&&n.variables!=null?{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(n)),audiences:o,defaultUrl:t,urlTemplate:this.maybeRemoveTrailingSlashIfNotEmpty(n.url),urlVariables:this.convertServerVariables(n.variables),docs:n.description}:{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(n)),audiences:o,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0,docs:n.description}}).filter(ga);return{value:{defaultEnvironment:r[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:sE.singleBaseUrl({environments:r})},defaultUrl:r[0]?.id}}convertServerVariables(t){return Object.entries(t).map(([r,n])=>({id:r,name:this.context.casingsGenerator.generateName(r),default:n.default,values:n.enum}))}static getServerExtensionName({server:t,context:r}){return new lYr({breadcrumbs:[],server:t,context:r}).convert()}static getServerAudiences({server:t,context:r}){return new nlt({breadcrumbs:[],operation:t,context:r}).convert()?.audiences}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[n,i]of Object.entries(t.variables))i.default!=null&&(r=r.replace(`{${n}}`,encodeURIComponent(i.default)));return r}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?v8u:e.getServerExtensionName({server:this.servers[0],context:this.context})??v8u}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}buildMultiUrlTemplateFields({defaultBaseUrlId:t,topLevelServer:r,endpointServers:n}){let i={},o={},s={},a=!1;if(r.variables!=null&&Object.keys(r.variables).length>0){a=!0;let c=this.extractFernDefaultUrlFromServer(r);c!=null&&(i[t]=c),o[t]=this.maybeRemoveTrailingSlashIfNotEmpty(r.url),s[t]=this.convertServerVariables(r.variables)}for(let c of n){let u=e.getServerName({server:c,context:this.context});if(c.variables!=null&&Object.keys(c.variables).length>0){a=!0;let l=this.extractFernDefaultUrlFromServer(c);l!=null&&(i[u]=l),o[u]=this.maybeRemoveTrailingSlashIfNotEmpty(c.url),s[u]=this.convertServerVariables(c.variables)}}return a?{defaultUrls:Object.keys(i).length>0?i:void 0,urlTemplates:o,urlVariables:s}:{defaultUrls:void 0,urlTemplates:void 0,urlVariables:void 0}}extractFernDefaultUrlFromServer(t){let r=t[Bkm];if(typeof r=="string")return this.maybeRemoveTrailingSlashIfNotEmpty(r)}extractFernDefaultUrl(){if(this.servers!=null)for(let t of this.servers){let r=this.extractFernDefaultUrlFromServer(t);if(r!=null)return r}}}});var Hm={};$(Hm,{AbstractConverters:()=>YGo,ExampleConverter:()=>Yw,SchemaConverters:()=>KGo,ServersConverter:()=>N4,convertResponseHeaders:()=>dlt});var XGo=h(()=>{"use strict";b8u();lwe();E8u();JGo();C8u()});var aWt,x8u=h(()=>{"use strict";lwe();oWt();aWt=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:n,exampleGenerationStrategy:i}){return new Yw({breadcrumbs:n,context:this.context,schema:r,example:t,depth:0,exampleGenerationStrategy:i,generateOptionalProperties:!1}).convert()}validateEndpointExample({exampleToValidate:t}){let r=[],n=[],i=!0,o=!1,s,a=[t.endpointPath,t.method];if(t.requestExample!==void 0&&t.requestSchema!==void 0){let u=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...a,"request"],exampleGenerationStrategy:"request"});if(!u.isValid){i=!1;let l=t.exampleSource==="human"?CE.WARNING:CE.ERROR;r.push(...u.errors.map(p=>({...p,level:l,message:`Invalid request example: ${p.message}`})))}u.coerced&&(o=!0,n.push({level:CE.WARNING,message:"Request example was coerced to match schema",path:[...a,"request"]})),s={request:u.validExample}}let c=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&c!==void 0){let u=this.validateExample({example:t.responseExample,schema:c,breadcrumbs:[...a,"response"],exampleGenerationStrategy:"response"});if(!u.isValid){i=!1;let l=t.exampleSource==="human"?CE.WARNING:CE.ERROR;r.push(...u.errors.map(p=>({...p,level:l,message:`Invalid response example: ${p.message}`})))}u.coerced&&(o=!0,n.push({level:CE.WARNING,message:"Response example was coerced to match schema",path:[...a,"response"]})),s={...typeof s=="object"&&s!==null?s:{},response:u.validExample}}return{isValid:i,errors:r,warnings:n,endpointPath:t.endpointPath,method:t.method,exampleSource:t.exampleSource,exampleName:t.exampleName,validExample:s,coerced:o}}getResponseSchemaForValidation(t){let{responseStatusCode:r,responseSchemas:n,responseSchema:i}=t;return n&&Object.keys(n).length>0?r&&n[r]?n[r]:n[200]??n[201]:i}validateAiExamples({aiExamples:t,spec:r}){let n=[],i=[];for(let o of t){let{requestSchema:s,responseSchema:a,responseSchemas:c}=this.getSchemasForEndpoint({spec:r,endpointPath:o.endpointPath,method:o.method}),u={endpointPath:o.endpointPath,method:o.method,exampleSource:"ai",requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a,responseSchemas:c},l=this.validateEndpointExample({exampleToValidate:u}),p=this.hasUnexpectedProperties({requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a}),d=l.errors.length>0||l.warnings.length>0;!l.isValid||d||p?i.push({example:o,validationResult:l}):n.push(o)}return{validExamples:n,invalidExamples:i}}hasUnexpectedProperties({requestExample:t,responseExample:r,requestSchema:n,responseSchema:i}){return!!(t&&n&&this.exampleHasUnexpectedProperties(t,n)||r&&i&&this.exampleHasUnexpectedProperties(r,i))}exampleHasUnexpectedProperties(t,r){if(!t||typeof t!="object"||t===null)return!1;let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[],skipErrorCollector:!0});if(!n||!n.properties&&!n.allOf&&!n.oneOf&&!n.anyOf||this.schemaHasPatternProperties(n))return!1;let i=t,o=this.collectAllPropertyKeys(n);return Object.keys(i).some(a=>!o.has(a))}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}for(let i of[...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}return n}schemaHasPatternProperties(t,r=new Set){let n=t.patternProperties;if(n&&typeof n=="object"&&Object.keys(n).length>0)return!0;for(let i of[...t.allOf??[],...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)&&(r.add(s),this.schemaHasPatternProperties(o,r)))return!0}}return!1}validateHumanExamples({spec:t}){let r=[],n=0,i=0,o=0,s=[],a=[];if(!t.paths)return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:!1,hasInvalidAiExamples:!1,invalidHumanExamples:s,invalidAiExamples:a};for(let[c,u]of Object.entries(t.paths)){if(!u)continue;let l=["get","post","put","delete","patch","options","head","trace"];for(let p of l){let d=u[p];if(!d)continue;let f=[],{requestSchema:m,responseSchema:g,responseSchemas:A}=this.getSchemasForOperation({operation:d}),y=this.extractExamplesFromOperation({operation:d,path:c,method:p});for(let I of y){n++;let x={endpointPath:c,method:p,exampleName:I.name,exampleSource:I.source,requestExample:I.request,responseExample:I.response,requestSchema:m,responseSchema:g,responseStatusCode:I.statusCode,responseSchemas:A},v=this.validateEndpointExample({exampleToValidate:x});f.push(v),v.isValid?i++:(o++,I.source==="human"?s.push(v):I.source==="ai"&&a.push(v))}f.length>0&&r.push({endpointPath:c,method:p,results:f,hasInvalidExamples:f.some(I=>!I.isValid),invalidExampleCount:f.filter(I=>!I.isValid).length})}}return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:s.length>0,hasInvalidAiExamples:a.length>0,invalidHumanExamples:s,invalidAiExamples:a}}getSchemasForEndpoint({spec:t,endpointPath:r,method:n}){let i=t.paths?.[r];if(!i)return{responseSchemas:{}};let o=i[n.toLowerCase()];return!o||typeof o!="object"||!("responses"in o)?{responseSchemas:{}}:this.getSchemasForOperation({operation:o})}getSchemasForOperation({operation:t}){let r,n,i={};if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let s=t.requestBody.content?.["application/json"];s?.schema&&(r=s.schema)}if(t.responses){for(let[o,s]of Object.entries(t.responses)){if(!s||this.context.isReferenceObject(s))continue;let c=s.content?.["application/json"];c?.schema&&(i[o]=c.schema)}n=i[200]??i[201]}return{requestSchema:r,responseSchema:n,responseSchemas:i}}extractExamplesFromOperation({operation:t,path:r,method:n}){let i=[];if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let a=t.requestBody.content?.["application/json"];if(a?.example!==void 0&&i.push({name:`${n}_${r}_request_example`,source:"openapi",request:a.example}),a?.examples)for(let[c,u]of Object.entries(a.examples)){let l=this.context.isReferenceObject(u)?this.context.resolveExample(u):u;l&&typeof l=="object"&&"value"in l&&i.push({name:c,source:"human",request:l.value})}}if(t.responses)for(let[s,a]of Object.entries(t.responses)){if(!a||this.context.isReferenceObject(a))continue;let u=a.content?.["application/json"];if(u?.example!==void 0){let l=i.find(p=>p.request!==void 0&&p.response===void 0);l?(l.response=u.example,l.statusCode=s):i.push({name:`${n}_${r}_response_${s}_example`,source:"openapi",response:u.example,statusCode:s})}if(u?.examples)for(let[l,p]of Object.entries(u.examples)){let d=this.context.isReferenceObject(p)?this.context.resolveExample(p):p;if(d&&typeof d=="object"&&"value"in d){let f=i.find(m=>m.name===l);f?(f.response=d.value,f.statusCode=s):i.push({name:l,source:"human",response:d.value,statusCode:s})}}}let o=t["x-fern-examples"];if(Array.isArray(o)){for(let s of o)if(typeof s=="object"&&s!==null){let a=s;i.push({name:a.name,source:"human",request:a.request?.body,response:a.response?.body})}}return i}}});function S8u({tags:e,errorCollector:t}){for(let r of e)if(mlt.test(r.name)){let n=[...r.name].filter(i=>mlt.test(i));t.collect({level:CE.ERROR,message:`Tag name "${r.name}" contains non-ASCII characters: ${n.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR).`,path:["tags",r.name],resolution:`Remove non-ASCII characters from the tag name. For example, rename "${r.name}" to "${r.name.replace(mlt,"").trim()}".`})}}function w8u({description:e,path:t,errorCollector:r}){Rkm.test(e)&&r.collect({level:CE.ERROR,message:'Description contains "---" frontmatter delimiters which will cause YAML parsing failures in the generated docs site. The docs renderer interprets content between "---" delimiters as YAML frontmatter, which will fail if the content is not valid YAML.',path:t,resolution:'Remove the "---" delimiters from the description.'})}function ZGo({spec:e,errorCollector:t}){if(Array.isArray(e.tags)){let n=e.tags.filter(i=>typeof i=="object"&&i!=null&&"name"in i&&typeof i.name=="string");S8u({tags:n,errorCollector:t})}let r=["get","post","put","delete","patch","options","head","trace"];if(e.paths!=null&&typeof e.paths=="object"){let n=new Set;for(let[i,o]of Object.entries(e.paths)){if(o==null||typeof o!="object")continue;let s=o;for(let a of r){let c=s[a];if(c==null||typeof c!="object")continue;let u=c;if(typeof u.description=="string"&&w8u({description:u.description,path:["paths",i,a,"description"],errorCollector:t}),Array.isArray(u.tags)&&!Array.isArray(e.tags)){for(let l of u.tags)if(typeof l=="string"&&!n.has(l)&&mlt.test(l)){n.add(l);let p=[...l].filter(d=>mlt.test(d));t.collect({level:CE.ERROR,message:`Tag name "${l}" contains non-ASCII characters: ${p.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR).`,path:["paths",i,a,"tags"],resolution:`Remove non-ASCII characters from the tag name. For example, rename "${l}" to "${l.replace(mlt,"").trim()}".`})}}}}}}var mlt,Rkm,T8u=h(()=>{"use strict";oWt();mlt=new RegExp("[^\\x00-\\x7F]"),Rkm=/(?:^|\n)\s*---\s*(?:\n|$)/});var pYr,Dkm,O8u=h(()=>{"use strict";pYr={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},Dkm=new Set(Object.values(pYr))});function $Go(e){if(e!=null)return e.map(t=>Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n??[]])))}var P8u=h(()=>{"use strict"});var rs=h(()=>{"use strict";JJr();U5u();tk();o8u();XGo();XGo();oWt();x8u();UGo();T8u();O8u();P8u()});var kkm,Fkm,B8u,R8u=h(()=>{"use strict";cn();kkm=De.object({type:De.string(),channelId:De.string().optional(),messageId:De.string(),value:De.any()}),Fkm=De.object({summary:De.string().optional(),description:De.string().optional(),"query-parameters":De.record(De.string()).optional(),headers:De.record(De.string()).optional(),messages:De.array(kkm)}),B8u=De.array(Fkm)});var fYr,D8u=h(()=>{"use strict";rs();R8u();fYr=class extends os{channel;baseDir;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:n,baseDir:i}){super({breadcrumbs:t??[],context:n}),this.channel=r,this.baseDir=i}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=B8u.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(n=>({summary:n.summary,description:n.description,queryParameters:n["query-parameters"],headers:n.headers,messages:n.messages.map(i=>({type:i.type,channelId:i.channelId,messageId:i.messageId,value:i.value}))}))}}});var hlt,eqo=h(()=>{"use strict";rs();D8u();hlt=class extends co{channel;channelPath;inlinedTypes={};websocketGroup;constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}){super({context:t,breadcrumbs:r}),this.websocketGroup=n,this.channel=i,this.channelPath=o}convertExamples({fullPath:t,baseUrl:r,asyncApiVersion:n}){let o=new fYr({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel,baseDir:this.context.documentBaseDir}).convert();return o==null?{}:Object.fromEntries(o.map((s,a)=>[a.toString(),{channel:{method:"GET",path:t},baseUrl:t,environment:r,auth:void 0,pathParameters:{},queryParameters:s.queryParameters,headers:s.headers,messages:s.messages.map(c=>({type:n==="v2"?c.type:c.messageId,body:c.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}}});var Nkm,BJ,cWt=h(()=>{"use strict";Wn();rs();Nkm="x-fern-server-name",BJ=class e extends co{servers;constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r}),this.servers=n}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[n,i]of Object.entries(this.servers)){let o=e.getServerName(n,i),s=this.buildSingleBaseUrlEnvironment(this.context,o,i);t.push(s),r==null&&(r=s.id)}return{defaultEnvironment:r,baseUrlEnvVar:void 0,environments:sE.singleBaseUrl({environments:t})}}static getServerName(t,r){if(r!=null&&typeof r=="object"){let n=r[Nkm];if(typeof n=="string"&&n.length>0)return n}return t}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}}});var dwe,tqo=h(()=>{"use strict";rs();dwe=class extends Hm.AbstractConverters.AbstractParameterConverter{parameterNamePrefix;constructor({context:t,breadcrumbs:r,parameter:n,parameterNamePrefix:i}){super({context:t,breadcrumbs:r,parameter:n}),this.parameterNamePrefix=i}convert(){let t,r={},i=new qC.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required===!1,o=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example??this.parameter.name,examples:Object.values(this.parameter.examples??{}),deprecated:this.parameter.deprecated,required:void 0},a=new Hm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameterNamePrefix?`${this.parameterNamePrefix}_${this.parameter.name}`:this.parameter.name,schemaOrReference:o,wrapAsOptional:i}).convert();return a!=null&&(t=a.type,r=a.inlinedTypes??{}),this.convertToOutput({schema:o,typeReference:t,inlinedTypes:r})}}});var dYr,k8u=h(()=>{"use strict";rs();dYr=class extends os{channel;key="x-fern-address";constructor({breadcrumbs:t,channel:r,context:n}){super({breadcrumbs:t,context:n}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}}});var mwe,rqo=h(()=>{"use strict";rs();mwe=class extends os{node;key="x-fern-display-name";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(!(t==null||typeof t!="string"))return t}}});var hwe,nqo=h(()=>{"use strict";rs();hwe=class extends os{node;key="x-fern-explorer";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}}});var mYr,F8u=h(()=>{"use strict";rs();mYr=class extends os{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(!(t==null||typeof t!="string"))return t}}});var hYr,N8u=h(()=>{"use strict";Wn();hc();rs();qi();eqo();cWt();tqo();k8u();rqo();nqo();F8u();hYr=class extends hlt{inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}){super({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o})}convert(){let t=[],r=[],n=[],o=new mwe({breadcrumbs:this.breadcrumbs,node:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".");this.channel.parameters&&this.convertPathParameters({context:this.context,pathParameters:t}),this.channel.bindings?.ws!=null&&(this.convertHeaders({context:this.context,headers:n}),this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let s;this.channel.subscribe!=null&&(s=this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let a;this.channel.publish!=null&&(a=this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let c=[];s!=null&&c.push(s),a!=null&&c.push(a);let l=new dYr({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),p=this.transformToValidPath(l??this.channelPath),d=this.resolveServerName(this.channel.servers?.[0])??this.resolveServerName(Object.keys(this.context.spec.servers??{})[0]),f=sb(p),m=ti(this.channelPath),g=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],A=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,y=new hwe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),x=new hwe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??y;return{channel:{name:this.context.casingsGenerator.generateName(m),displayName:o,connectMethodName:void 0,baseUrl:d,path:f,auth:A,headers:n,queryParameters:r,pathParameters:t,messages:c,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:p,baseUrl:d,asyncApiVersion:"v2"})},apiPlayground:x},audiences:g,inlinedTypes:this.inlinedTypes}}hasServerSecurity(){let t=this.context.spec.servers??{};if(this.channel.servers&&this.channel.servers.length>0){for(let r of this.channel.servers){let n=t[r];if(n?.security&&n.security.length>0)return!0}return!1}for(let r of Object.values(t)){let n=r;if(n.security&&n.security.length>0)return!0}return!1}convertMessage({context:t,operation:r,origin:n}){let i,o=n==="server"?"subscribe":"publish",s=[...this.breadcrumbs,o],a=t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:s});a!=null&&(r.message=a);let c=dLe(ti(`${this.channelPath}_${o}`)).replace(/ /g,"");if("oneOf"in r.message){let l=new Hm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:r.message,schemaIdOverride:c}).convert();l!=null&&l.schema!=null&&(i=l.schema,this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let u=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:s});if(u!=null){let p=new Hm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:u,schemaIdOverride:c}).convert();p!=null&&p.schema!=null&&(i=p.schema,this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes})}}if(i!=null){let u=i,l=en.named({fernFilepath:t.createFernFilepath(),name:u.typeDeclaration.name.name,typeId:u.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),p=dB.reference({bodyType:l,docs:r.description}),d=n==="server"?"subscribe":"publish",m=new mwe({breadcrumbs:[...this.breadcrumbs,d],node:r,context:this.context}).convert()??d;return{type:d,displayName:m,origin:n,body:p,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description,methodName:this.getOperationMethodName(r)}}}convertPathParameters({context:t,pathParameters:r}){for(let[n,i]of Object.entries(this.channel.parameters??{})){let o=t.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs});if(o==null)continue;let a=new dwe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:n,in:"path",description:o.description,required:o.required??!0},parameterNamePrefix:this.channelPath}).convert();a!=null&&(this.inlinedTypes={...this.inlinedTypes,...a.inlinedTypes},a.type==="path"&&r.push(a.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let n=this.channel.bindings.ws.headers.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let c=new dwe({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"header",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0},parameterNamePrefix:this.channelPath}).convert();c!=null&&c.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}resolveServerName(t){if(t==null)return;let r=this.context.spec.servers;if(r!=null&&t in r){let n=r[t];return BJ.getServerName(t,n)}return t}getOperationMethodName(t){return new mYr({breadcrumbs:this.breadcrumbs,operation:t,context:this.context}).convert()}convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let n=this.channel.bindings.ws.query.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.query.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let c=new dwe({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"query",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0,deprecated:s.deprecated??!1},parameterNamePrefix:this.channelPath}).convert();c!=null&&c.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}}});var gYr,j8u=h(()=>{"use strict";cWt();gYr=class extends BJ{constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r,servers:n})}buildSingleBaseUrlEnvironment(t,r,n){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(n.protocol,n.url),docs:void 0,audiences:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}}});var iqo,z8u,oqo,AYr,Q8u=h(()=>{"use strict";Wn();hc();Dt();eqo();cWt();tqo();rqo();nqo();iqo="$message.",z8u="#/channels/",oqo="#/servers/",AYr=class extends hlt{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o,operations:s}){super({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}),this.operations=s}convert(){let t=[],r=[],n=[],o=new mwe({breadcrumbs:this.breadcrumbs,node:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".")??this.channelPath;this.channel.parameters&&this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:n,channelPath:this.channelPath});let s=Object.entries(this.operations).reduce((A,[y,I])=>{try{this.getChannelPathFromOperation(I)===this.channelPath&&(A[y]=I)}catch{}return A},{}),a=[];for(let[A,y]of Object.entries(s)){let x=new mwe({breadcrumbs:[...this.breadcrumbs,A],node:y,context:this.context}).convert()??A;for(let v of y.messages){let S=this.context.convertReferenceToTypeReference({reference:v});if(S.ok){let B=this.resolveMessageDocs(v)??y.description,R=dB.reference({bodyType:S.reference,docs:B});a.push({type:A,displayName:x,origin:y.action==="send"?"client":"server",body:R,availability:this.context.getAvailability({node:y,breadcrumbs:this.breadcrumbs}),docs:B,methodName:void 0})}}}let c=this.resolveChannelServersFromReference(this.channel.servers??[])??this.resolveFirstServerName(),u=this.transformToValidPath(this.channel.address??this.channelPath),l=sb(u),p=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],d=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,f=new hwe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),g=new hwe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??f;return{channel:{name:this.context.casingsGenerator.generateName(o),displayName:o,connectMethodName:void 0,baseUrl:c,path:l,auth:d,headers:n,queryParameters:r,pathParameters:t,messages:a,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:u,baseUrl:c,asyncApiVersion:"v3"})},apiPlayground:g},audiences:p,inlinedTypes:this.inlinedTypes}}hasServerSecurity(){let r=this.context.spec.servers??{};if(this.channel.servers&&this.channel.servers.length>0){for(let n of this.channel.servers){let i=n.$ref.replace(oqo,""),o=r[i];if(o?.security&&o.security.length>0)return!0}return!1}for(let n of Object.values(r))if(n.security&&n.security.length>0)return!0;return!1}convertChannelParameters({pathParameters:t,queryParameters:r,headers:n,channelPath:i}){for(let o of Object.values(this.channel.parameters??{})){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(s==null)continue;let a=this.convertChannelParameterLocation(s.location);if(a==null)continue;let{type:c,parameterKey:u}=a,p=new dwe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...s,name:u,in:c},parameterNamePrefix:this.channelPath}).convert();if(p!=null)switch(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},p.type){case"path":t.push(p.parameter);break;case"query":r.push(p.parameter);break;case"header":n.push(p.parameter);break}}}convertChannelParameterLocation(t){try{let[r,n]=t.split("#/");if(r==null||n==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(iqo)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${iqo} prefix`,path:this.breadcrumbs});return}let i=r.substring(iqo.length);if(i!=="header"&&i!=="path"&&i!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${i}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return i==="payload"?{type:"query",parameterKey:n}:{type:i,parameterKey:n}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveMessageDocs(t){let r=t,n=new Set;for(;this.context.isReferenceObject(r);){if(n.has(r.$ref))return;n.add(r.$ref);let i=this.context.resolveReference({reference:r,breadcrumbs:this.breadcrumbs});if(!i.resolved)return;r=i.value}return r.description??r.summary}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(oqo)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let n=r.$ref.substring(oqo.length);if(n==null){this.context.errorCollector.collect({message:`Failed to find server with name ${n}`,path:this.breadcrumbs});return}let i=this.context.spec.servers;if(i!=null&&n in i){let o=i[n];return BJ.getServerName(n,o)}return n}resolveFirstServerName(){let t=this.context.spec.servers;if(t==null)return;let r=Object.keys(t)[0];if(r==null)return;let n=t[r];return BJ.getServerName(r,n)}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(z8u))throw new T({message:`Failed to resolve channel path from operation ${t.channel.$ref}`,code:T.Code.ReferenceError});return t.channel.$ref.substring(z8u.length)}}});var yYr,M8u=h(()=>{"use strict";cWt();yYr=class extends BJ{constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r,servers:n})}buildSingleBaseUrlEnvironment(t,r,n){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(n.protocol,n.host),docs:void 0,audiences:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}}});var uWt,L8u=h(()=>{"use strict";Wn();hc();rs();N8u();j8u();Q8u();M8u();uWt=class extends PJ{constructor({context:t,breadcrumbs:r,audiences:n}){super({context:t,breadcrumbs:r,audiences:n})}async convert(){return this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.isAsyncAPIV3(this.context)?this.convertChannelMessages():this.convertComponentMessages(),this.convertSchemas(),this.convertServers(),this.convertSecuritySchemes(),this.convertChannels(),this.finalizeIr()}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}convertChannelMessages(){let t=this.context.spec;for(let[r,n]of Object.entries(t.channels??{}))for(let[i,o]of Object.entries(n.messages??{})){if(!this.context.isMessageWithPayload(o)&&!this.context.isReferenceObject(o))continue;let s=["channels",r,"messages",i],a=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:s});if(!this.context.isMessageWithPayload(a))continue;let c=this.context.resolveMaybeReference({schemaOrReference:a.payload,breadcrumbs:s});if(c==null)continue;let u=`${r}_${i}`;this.convertSchema({id:u,breadcrumbs:s,schema:c})}}convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let n=["components","messages",t],i=this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:n});i!=null&&this.convertSchema({id:t,breadcrumbs:n,schema:i})}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}convertSchema({id:t,breadcrumbs:r,schema:n}){let o=new Hm.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:n}).convert();o!=null&&this.addSchemaOutputToIr(t,o)}convertServers(){let t;if(this.isAsyncAPIV3(this.context)){let r=this.context.spec.servers;t=new yYr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new gYr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertSecuritySchemes(){if(this.context.authOverrides){let r=JGt({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertAsyncApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertAsyncApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let o=this.convertSecurityScheme({securityScheme:i,schemeId:r});o!=null&&t.push(o)}return t}convertSecurityScheme({securityScheme:t,schemeId:r}){switch(t.type){case"http":{if(t.scheme?.toLowerCase()==="bearer")return Hp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});if(t.scheme?.toLowerCase()==="basic")return Hp.basic({key:r,username:this.context.casingsGenerator.generateName("username"),password:this.context.casingsGenerator.generateName("password"),usernameEnvVar:void 0,passwordEnvVar:void 0,usernameOmit:!1,passwordOmit:!1,usernamePlaceholder:void 0,passwordPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"apiKey":{if(t.in==="header")return Hp.header({key:r,name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:t.name},valueType:co.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,headerPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"oauth2":return Hp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:t.description,playgroundDocs:void 0})}}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let i=new qC.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,o;if(this.isAsyncAPIV3(this.context)){let a=this.context.spec.operations??{};o=new AYr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t,operations:a}).convert()}else o=new hYr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t}).convert();o!=null&&(this.addWebsocketChannelToIr({websocketChannel:o.channel,channelPath:t,audiences:o.audiences,websocketGroup:i}),this.addTypesToIr(o.inlinedTypes))}}}});var lWt,_8u=h(()=>{"use strict";Wn();rs();lWt=class extends S0{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o,s=t.$ref.match(/^.*\/schemas\/(.+)$/),a=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),c=t.$ref.match(/^.*\/messages\/(.+)$/);if(s&&s[1])return o=s[1],this.convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o});if(a&&a[2]){let u=a[1],l=a[2];return o=`${u}_${l}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})}else return c&&c[1]?(o=c[1],this.convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})):{ok:!1}}convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.title;else if(i==="discriminator_key")a=s.value.title??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.title??c}return{ok:!0,reference:en.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.name;else if(i==="discriminator_key")a=s.value.name??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.name??c}return{ok:!0,reference:en.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.messageId??s.value.name;else if(i==="discriminator_key")a=s.value.messageId??s.value.name??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.messageId??s.value.name??c}return{ok:!0,reference:en.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var U8u=h(()=>{"use strict";L8u();_8u()});function zkm(e){let t=new Set,r,n=new RegExp(jkm.source,"g");for(;(r=n.exec(e))!=null;)r[1]!=null&&t.add(r[1]);return t}var jkm,bYr,V8u=h(()=>{"use strict";rs();jkm=/\{([^}]+)\}/g,bYr=class extends os{document;key="x-fern-base-path";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t=="string")return this.parseString(t);if(typeof t=="object"&&!Array.isArray(t))return this.parseStructured(t);this.context.errorCollector.collect({message:"Expected `x-fern-base-path` to be a string or object",path:this.breadcrumbs})}}parseString(t){if(this.validatePath(t))return{path:t,parameters:[],pathsIncludeBasePath:!1}}parseStructured(t){let r=t.path;if(typeof r!="string"){this.context.errorCollector.collect({message:"`x-fern-base-path.path` must be a string",path:this.breadcrumbs});return}if(!this.validatePath(r))return;let n=zkm(r),i=t.parameters;if(i!=null&&(typeof i!="object"||Array.isArray(i))){this.context.errorCollector.collect({message:"`x-fern-base-path.parameters` must be an object map",path:[...this.breadcrumbs,"parameters"]});return}let o=i??{};for(let c of Object.keys(o))if(!n.has(c)){this.context.errorCollector.collect({message:`Parameter '${c}' does not appear in the base path '${r}'`,path:[...this.breadcrumbs,"parameters",c]});return}let s=[];for(let c of n){let u=o[c];if(u==null){s.push({name:c,type:"string",default:void 0,docs:void 0});continue}if(typeof u!="object"||Array.isArray(u)){this.context.errorCollector.collect({message:`Parameter '${c}' must be an object`,path:[...this.breadcrumbs,"parameters",c]});return}let l=u,p=typeof l.type=="string"?l.type:"string",d=typeof l.docs=="string"?l.docs:void 0;s.push({name:c,type:p,default:l.default,docs:d})}let a=t["paths-include-base-path"]===!0;return{path:r,parameters:s,pathsIncludeBasePath:a}}validatePath(t){return t.startsWith("/")?!0:(this.context.errorCollector.collect({message:"`x-fern-base-path` path must start with '/'",path:this.breadcrumbs}),!1)}}});var EYr,G8u=h(()=>{"use strict";rs();EYr=class extends os{document;key="x-fern-base-url-env";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="string"||t.length===0){this.context.errorCollector.collect({message:"Expected a non-empty string value for x-fern-base-url-env",path:this.breadcrumbs});return}return t}}}});var IYr,q8u=h(()=>{"use strict";rs();IYr=class extends os{document;key="x-fern-global-headers";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-headers",path:this.breadcrumbs});return}return t}}}});function Qkm(e){let r=e["x-fern-default"]??e.default;if(typeof r=="string"||typeof r=="boolean"||typeof r=="number")return r}var vYr,W8u=h(()=>{"use strict";rs();vYr=class extends os{document;key="x-fern-global-parameters";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t==null)return;if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-parameters",path:this.breadcrumbs});return}let r=[];for(let[n,i]of t.entries()){if(typeof i!="object"||i==null||Array.isArray(i)){this.context.errorCollector.collect({message:`x-fern-global-parameters[${n}] must be an object`,path:[...this.breadcrumbs,`${n}`]});continue}let o=i;if(typeof o.name!="string"){this.context.errorCollector.collect({message:`x-fern-global-parameters[${n}].name is required and must be a string`,path:[...this.breadcrumbs,`${n}`,"name"]});continue}r.push({name:o.name,"parameter-name":typeof o["parameter-name"]=="string"?o["parameter-name"]:void 0,in:typeof o.in=="string"?o.in:void 0,target:typeof o.target=="string"?o.target:void 0,env:typeof o.env=="string"?o.env:void 0,default:Qkm(o),optional:typeof o.optional=="boolean"?o.optional:void 0,apply:typeof o.apply=="string"?o.apply:void 0,type:typeof o.type=="string"?o.type:void 0,docs:typeof o.docs=="string"?o.docs:void 0})}return r.length>0?r:void 0}}});function Mkm(e){if(e!=null){if(typeof e=="string")return Zt.Literal.string(e);if(typeof e=="boolean")return Zt.Literal.boolean(e)}}function H8u({globalHeaderOverrides:e,context:t}){let r=[];for(let[n,i]of Object.entries(e.headers??{}))if(typeof i=="string")r.push({name:t.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),valueType:co.STRING,env:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:void 0,clientDefault:void 0,defaultValue:void 0});else{let o=i.name??n;r.push({name:t.casingsGenerator.generateNameAndWireValue({name:o,wireValue:n}),valueType:co.STRING,env:i.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:i.docs,clientDefault:Mkm(i.default),defaultValue:i.default})}return r}var K8u=h(()=>{"use strict";Wn();rs()});function Lkm(e){if(e!=null){if(typeof e=="string")return Zt.Literal.string(e);if(typeof e=="boolean")return Zt.Literal.boolean(e)}}function J8u({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?co.OPTIONAL_STRING:co.STRING,env:r.env,v2Examples:r.optional?void 0:_km({header:r,context:t}),availability:void 0,docs:void 0,clientDefault:Lkm(r["x-fern-default"]),defaultValue:void 0}))}function _km({header:e,context:t}){let r=new Yw({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:n}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:n}}}var Y8u=h(()=>{"use strict";Wn();rs()});function Ukm(e,t,r,n){if(e!=null){if(typeof e=="boolean"){if(t!=null&&t!=="boolean"){n.errorCollector.collect({message:`Default value is a boolean but type is '${t}'; expected a ${t} value`,path:[...r,"default"]});return}return Zt.Literal.boolean(e)}if(typeof e=="string"){if(t==="boolean"){n.errorCollector.collect({message:"Default value is a string but type is 'boolean'; expected a boolean value",path:[...r,"default"]});return}if(t==="integer"||t==="double"||t==="number"){n.errorCollector.collect({message:`Default value is a string but type is '${t}'; expected a numeric value`,path:[...r,"default"]});return}return Zt.Literal.string(e)}if(typeof e=="number"){if(t==="boolean"){n.errorCollector.collect({message:"Default value is a number but type is 'boolean'; expected a boolean value",path:[...r,"default"]});return}if(t==="string"){n.errorCollector.collect({message:"Default value is a number but type is 'string'; expected a string value",path:[...r,"default"]});return}if(t==="integer"&&!Number.isInteger(e)){n.errorCollector.collect({message:`Default value ${e} is not an integer`,path:[...r,"default"]});return}return Zt.Literal.string(String(e))}n.errorCollector.collect({message:`Default value has unsupported type '${typeof e}'; expected a string, number, or boolean`,path:[...r,"default"]})}}function Vkm(e,t,r){switch(e){case void 0:case"body":return Zt.GlobalParameterLocation.Body;case"query":return Zt.GlobalParameterLocation.Query;case"header":return Zt.GlobalParameterLocation.Header;case"path":return Zt.GlobalParameterLocation.Path;default:return r.errorCollector.collect({message:`Invalid global parameter location '${e}'; expected one of: body, query, header, path`,path:t}),Zt.GlobalParameterLocation.Body}}function Gkm(e,t,r){switch(e){case void 0:return;case"explicit":return Zt.GlobalParameterApplyMode.Explicit;case"auto":return Zt.GlobalParameterApplyMode.Auto;default:r.errorCollector.collect({message:`Invalid global parameter apply mode '${e}'; expected one of: explicit, auto`,path:t});return}}function qkm(e,t){let r=Wkm(e);return t===!0?Zt.TypeReference.container(Zt.ContainerType.optional(r)):r}function Wkm(e){switch(e){case"boolean":return Zt.TypeReference.primitive({v1:"BOOLEAN",v2:Zt.PrimitiveTypeV2.boolean({default:void 0})});case"integer":return Zt.TypeReference.primitive({v1:"INTEGER",v2:Zt.PrimitiveTypeV2.integer({default:void 0,validation:void 0})});case"double":case"number":return Zt.TypeReference.primitive({v1:"DOUBLE",v2:Zt.PrimitiveTypeV2.double({default:void 0,validation:void 0})});default:return co.STRING}}function Hkm(e){return e.target!=null?e.target:e.name}function X8u({globalParameters:e,context:t}){let r=new Map;for(let[n,i]of e.entries()){let o=r.get(i.name);o!=null?t.errorCollector.collect({message:`Duplicate global parameter name '${i.name}' at index ${n} (first seen at index ${o}). Each global parameter must have a unique name.`,path:["x-fern-global-parameters",`${n}`,"name"]}):r.set(i.name,n)}return e.map((n,i)=>({param:n,index:i})).filter(({param:n,index:i})=>r.get(n.name)===i).map(({param:n,index:i})=>{let o=["x-fern-global-parameters",`${i}`],s=Vkm(n.in,[...o,"in"],t),a=n["parameter-name"]??n.name;return{id:n.name,name:t.casingsGenerator.generateNameAndWireValue({name:a,wireValue:n.name}),location:s,target:Hkm(n),valueType:qkm(n.type,n.optional),env:n.env,clientDefault:Ukm(n.default,n.type,o,t),optional:n.optional,apply:Gkm(n.apply,[...o,"apply"],t),docs:n.docs}})}var Z8u=h(()=>{"use strict";Wn();rs()});var CYr,$8u=h(()=>{"use strict";ct();rs();CYr=class extends Hm.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={},n=this.getSchema();if(n!=null){let i=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),s=new Hm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:n,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:i}).convert();s!=null&&(t=s.type,r=s.inlinedTypes??{})}return this.convertToOutput({schema:n??{type:"string"},typeReference:t,inlinedTypes:r})}getSchema(){if(this.parameter.schema!=null)return this.parameter.schema;if(!(!this.context.settings.respectParameterContent||this.parameter.in!=="header"||this.parameter.content==null)){for(let[t,r]of Object.entries(this.parameter.content))if(r.schema!=null&&of.parse(t)?.isJSON())return r.schema}}}});function Jkm({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return Kkm[e.contentType]}}var xYr,Kkm,eGu=h(()=>{"use strict";ct();Wn();hc();rs();xYr=class extends Hm.AbstractConverters.AbstractMediaTypeObjectConverter{contentType;mediaType;description;required;schemaId;streamingExtension;queryParameters;constructor({context:t,breadcrumbs:r,contentType:n,mediaType:i,description:o,required:s,group:a,method:c,streamingExtension:u,queryParameters:l}){super({context:t,breadcrumbs:r,group:a,method:c}),this.contentType=n,this.mediaType=i,this.description=o,this.required=s,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=u,this.queryParameters=l??[]}get bodyRequired(){return this.required===!1?!1:void 0}convert(){return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleStreamConditionJsonOrFormContent({contentType:this.contentType})}convertNonStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleJsonOrFormContent({contentType:this.contentType});if(of.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=of.parse(this.contentType);return t?t.isJSON()||t.isURLEncoded()||t.isPlainText()||t.isCSV()||t.isHTML()||t.isXML()||t.isDNS()||t.isApplicationText():!1}isBinaryContentType(){let t=of.parse(this.contentType);return t?t.isBinary():!1}handleJsonOrFormContent({contentType:t}){let r=this.mediaType;if(r==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});if(n==null)return this.handleSchemalessJsonContent({contentType:t,mediaTypeObject:r});let i=n.schema?.typeDeclaration.shape;return i?.type==="object"?this.hasBodyQueryParameterOverlap(i.properties)?{requestBody:Od.reference({contentType:t,docs:this.description,requestBodyType:n.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}:{requestBody:Od.inlinedRequestBody({contentType:t,docs:this.description??n.schema?.typeDeclaration.docs,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:i.extendedProperties,extends:i.extends,properties:i.properties,extraProperties:i.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes}),inlinedPropertiesByAudience:n.schema?.propertiesByAudience}:{requestBody:Od.reference({contentType:t,docs:this.description,requestBodyType:n.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}}handleSchemalessJsonContent({contentType:t,mediaTypeObject:r}){if(!(r.example!=null||r.examples!=null&&Object.keys(r.examples).length>0))return;let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:r,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),s=new Set;for(let[a,c]of o){let u=this.context.resolveExampleWithValue(c),l=this.context.resolveExampleRecursively({example:c,breadcrumbs:this.breadcrumbs}),p=a;if(this.context.isExampleWithSummary(l)){let d=l.summary;s.has(d)||(p=d)}s.add(p),u!=null&&(i.userSpecifiedExamples[p]=u)}return{requestBody:Od.reference({contentType:t,docs:this.description,requestBodyType:en.unknown(),required:this.bodyRequired,v2Examples:i}),streamRequestBody:void 0,inlinedTypes:{}}}handleMultipartContent({contentType:t}){let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,resolveSchema:!0,contentType:t});if(n==null)return;let i=n.schema?.typeDeclaration.shape;if(i?.type==="object")return{requestBody:Od.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:i.properties.map(o=>{let s=r.encoding?.[ur(o.name)];return this.convertRequestBodyProperty({property:o,contentType:t,encoding:s})}),v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes}),examples:n.examples}}handleBinaryContent({contentType:t}){let r=this.mediaType;if(r==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});return{requestBody:Od.bytes({contentType:t,isOptional:this.required===!1,docs:this.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n?.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r,encoding:n}){let{isFile:i,isOptional:o,isArray:s}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return i?s?Xx.file(cQ.fileArray({key:t.name,isOptional:o,contentType:r,docs:t.docs})):Xx.file(cQ.file({key:t.name,isOptional:o,contentType:r,docs:t.docs})):Xx.bodyProperty({...t,contentType:n?.contentType??r,style:Jkm({encoding:n}),name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(n==null)return;let i=n.properties?.[this.streamingExtension.streamConditionProperty];if(i!=null&&this.context.isReferenceObject(i)&&(i=void 0),i==null){if(n.oneOf==null&&n.anyOf==null)return;i={type:"boolean"}}let o=this.buildStreamConditionRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!0,contentType:t,mediaTypeObject:r}),s=this.buildStreamConditionRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(o==null||s==null))return{requestBody:s.requestBody,streamRequestBody:o.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...o.inlinedTypes,...s.inlinedTypes}})}}buildStreamConditionRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:n,contentType:i,mediaTypeObject:o}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let s={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{...t,type:"boolean",const:n}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},a={...o,schema:s},c=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:this.schemaId,contentType:i});if(c==null)return;let u=c.schema?.typeDeclaration.shape;return u?.type==="object"?{requestBody:Od.inlinedRequestBody({contentType:i,docs:this.description??c.schema?.typeDeclaration.docs,name:this.context.casingsGenerator.generateName(n?this.streamingExtension?.streamRequestName??`${this.schemaId}_streaming`:this.schemaId),extendedProperties:u.extendedProperties,extends:u.extends,properties:u.properties,extraProperties:u.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes}:{requestBody:Od.reference({contentType:i,docs:this.description,requestBodyType:c.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes??{}}}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:n}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:n}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:n}):{isFile:this.context.isFile(t),isOptional:r??!1,isArray:n??!1}}hasBodyQueryParameterOverlap(t){if(this.queryParameters.length===0)return!1;let r=new Set(this.queryParameters.map(n=>ur(n.name).toLowerCase()));return t.some(n=>r.has(ur(n.name).toLowerCase()))}},Kkm={"application/json":"json"}});function Zkm(e){return e?.header!=null}var Ykm,Xkm,glt,sqo=h(()=>{"use strict";ct();Wn();hc();rs();qi();$8u();eGu();Ykm=/{([^}]+)}/g,Xkm=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),glt=class extends co{operation;method;path;pathItemParameters;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}){super({context:t,breadcrumbs:r}),this.operation=n,this.method=i,this.path=o,this.pathItemParameters=s??[]}convertHttpMethod(){switch(this.method){case"get":return Tm.Get;case"post":return Tm.Post;case"put":return Tm.Put;case"delete":return Tm.Delete;case"patch":return Tm.Patch;case"head":return Tm.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],n=[],i=[],o=this.mergeParameters(this.pathItemParameters,this.operation.parameters??[]);if(o.length===0)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i};for(let s of o){let a=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:t});if(a==null)continue;let u=new CYr({context:this.context,breadcrumbs:t,parameter:a}).convert();if(u!=null)switch(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},u.type){case"path":r.push(u.parameter);break;case"query":n.push(u.parameter);break;case"header":{let l=Vr(u.parameter.name),p=ur(u.parameter.name),d=!1,f=this.context.authOverrides?.["auth-schemes"];if(f!=null){for(let g of Object.values(f))if(Zkm(g)&&g.header.toLowerCase()===p.toLowerCase()){d=!0;break}}let m=this.context.globalHeaderNames;if(m!=null){for(let g of m)if(g.toLowerCase()===p.toLowerCase()){d=!0;break}}!Xkm.has(l.toLowerCase())&&!d&&i.push(u.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i}}mergeParameters(t,r){if(t.length===0)return r;if(r.length===0)return t;let n=new Set;for(let o of r){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs});s!=null&&n.add(`${s.in}:${s.name}`)}return[...t.filter(o=>{let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs});return s==null?!1:!n.has(`${s.in}:${s.name}`)}),...r]}checkMissingPathParameters(t){let n=[...this.path.matchAll(Ykm)].map(i=>i[1]).filter(i=>!t.some(o=>Vr(o.name)===i));for(let i of n){if(i==null)continue;let o=`${i}_example`;t.push({name:this.context.casingsGenerator.generateName(i),valueType:co.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[o]:this.generateStringParameterExample({example:i})}},explode:void 0,clientDefault:void 0})}}convertRequestBody({breadcrumbs:t,group:r,method:n,streamingExtension:i,queryParameters:o}){if(this.operation.requestBody==null)return;let s=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(s==null)return null;let a=[];for(let[c,u]of Object.entries(s.content)){let p=new xYr({context:this.context,breadcrumbs:t,contentType:c,mediaType:u,description:s.description,required:s.required,group:r??[],method:n,streamingExtension:i,queryParameters:o}).convert();p!=null&&(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},a.push({requestBody:p.requestBody,streamRequestBody:p.streamRequestBody,examples:p.examples,inlinedPropertiesByAudience:p.inlinedPropertiesByAudience}))}return a}computeGroupNameAndLocationFromExtensions(){let r=new qC.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,i=new qC.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:i,method:r}}evaluateMethodNameFromOperation(){let t=this.operation.operationId;return t??(this.operation.summary!=null?ti(this.operation.summary):ti(`${this.method}_${this.path.split("/").join("_")}`))}sanitizeMethodName(t){return t.includes(".")?ti(t):t}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:this.sanitizeMethodName(r)};let n=this.context.settings.respectOperationIdWordBoundaries,i=RH(t,n),o=RH(r,n);return rE(i,o)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,methodName:r,methodNameTokens:o})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:n,methodNameTokens:i}){if(r.some((a,c)=>a!==i[c]))return{group:[t],method:this.sanitizeMethodName(n)};let s=i.slice(r.length);return s[0]!=null&&/^\d/.test(s[0])?{group:[t],method:this.sanitizeMethodName(n)}:{group:[t],method:ti(s.join("_"))}}generateStringParameterExample({example:t}){let r=new Hm.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:n}=r.convert();return n}}});var Alt,aqo=h(()=>{"use strict";Wn();sqo();Alt=class extends glt{constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=[...this.breadcrumbs,"Payload"],{headers:o,queryParameters:s}=this.convertParameters({breadcrumbs:i}),a=this.convertRequestBody({breadcrumbs:i,group:r,method:n,streamingExtension:void 0,queryParameters:s});if(a==null)return;let c=a[0]?.requestBody;if(c==null)return;let u=c.type==="inlinedRequestBody"?a[0]?.inlinedPropertiesByAudience:void 0,l,p;if(c.type==="inlinedRequestBody")l=oT.inlinedPayload({name:c.name,extends:c.extends,properties:c.properties});else if(c.type==="reference")l=oT.reference({payloadType:c.requestBodyType,docs:c.docs});else if(c.type==="fileUpload")p={name:c.name,properties:c.properties,docs:c.docs,v2Examples:c.v2Examples,contentType:c.contentType},l=oT.inlinedPayload({name:c.name,extends:[],properties:[]});else return;let d=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,inlinedPayloadPropertiesByAudience:u,webhook:{id:`${r?.join(".")??""}.${n}`,name:this.context.casingsGenerator.generateName(n),displayName:this.operation.summary,method:t,headers:o,payload:l,signatureVerification:void 0,fileUploadPayload:p,responses:d.length>0?d:void 0,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(c.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(c.v2Examples?.userSpecifiedExamples??{})}},inlinedTypes:this.inlinedTypes}}convertWebhookResponses(){let t=[];if(this.operation.responses==null)return t;for(let[r,n]of Object.entries(this.operation.responses)){let i=/^\d[Xx]{2}$/.test(r),o;if(i)o=parseInt(r.charAt(0))*100;else if(o=parseInt(r),isNaN(o))continue;let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"responses",r]})?.description;t.push({statusCode:o,isWildcardStatusCode:i?!0:void 0,body:void 0,docs:a})}return t}getWebhookV2ExamplesFromRequestBodyV2Examples(t){return Object.fromEntries(Object.entries(t).map(([r,n])=>[r,{name:r,payload:n}]))}}});var tGu,rGu=h(()=>{"use strict";tGu=["get","post","put","delete","patch","head"]});var SYr,nGu=h(()=>{"use strict";rs();SYr=class extends os{operation;key="x-fern-global-parameter";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;if(typeof t=="string")return[t];if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected value for x-fern-global-parameter; expected a string or array of strings",path:this.breadcrumbs});return}let r=[];for(let[n,i]of t.entries()){if(typeof i!="string"){this.context.errorCollector.collect({message:`x-fern-global-parameter[${n}] must be a string`,path:[...this.breadcrumbs,`${n}`]});continue}r.push(i)}return r.length>0?r:void 0}}});var wYr,iGu=h(()=>{"use strict";rs();wYr=class extends os{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}}});var $km,eFm,tFm,rFm,cqo,oGu=h(()=>{"use strict";cn();$km=De.object({cursor:De.string(),next_cursor:De.string(),results:De.string()}),eFm=De.object({offset:De.string(),results:De.string(),step:De.string().optional(),"has-next-page":De.string().optional()}),tFm=De.object({next_uri:De.string(),results:De.string()}),rFm=De.object({next_path:De.string(),results:De.string()}),cqo=De.union([De.boolean(),$km,eFm,tFm,rFm])});var uqo,gwe,TYr,sGu=h(()=>{"use strict";rs();oGu();uqo="$request.",gwe="$response.",TYr=class extends os{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:n,context:i}){super({breadcrumbs:t,context:i}),this.operation=r,this.document=n}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=cqo.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let n=this.getExtensionValue(this.document);if(n==null)return;if(typeof n=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let i=cqo.safeParse(n);if(!i.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${i.error.message}`,path:this.breadcrumbs});return}if(typeof i.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:i.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:S0.maybeTrimPrefix(r.cursor,uqo),nextCursor:S0.maybeTrimPrefix(r.next_cursor,gwe),results:S0.maybeTrimPrefix(r.results,gwe)};let n=t;if("next_uri"in n)return{type:"uri",nextUri:S0.maybeTrimPrefix(n.next_uri,gwe),results:S0.maybeTrimPrefix(n.results,gwe)};let i=t;if("next_path"in i)return{type:"path",nextPath:S0.maybeTrimPrefix(i.next_path,gwe),results:S0.maybeTrimPrefix(i.results,gwe)};let o=t;return{type:"offset",offset:S0.maybeTrimPrefix(o.offset,uqo),results:S0.maybeTrimPrefix(o.results,gwe),step:o.step!=null?S0.maybeTrimPrefix(o.step,uqo):void 0,hasNextPage:o["has-next-page"]!=null?S0.maybeTrimPrefix(o["has-next-page"],gwe):void 0}}}});function lqo(e){let t=e["x-fern-streaming"];if(t==null||typeof t=="boolean")return;let r=t.resumable;return typeof r=="boolean"?r:void 0}var nFm,iFm,oFm,OYr,aGu=h(()=>{"use strict";rs();cn();nFm="$request.",iFm=De.object({"stream-condition":De.string().optional(),format:De.enum(["sse","json"]).optional(),"stream-description":De.string().optional(),"stream-request-name":De.string().optional(),"response-stream":De.any(),response:De.any(),terminator:De.string().optional(),resumable:De.boolean().optional()}),oFm=De.union([De.boolean(),iFm]),OYr=class extends os{document;operation;key="x-fern-streaming";constructor({breadcrumbs:t,document:r,operation:n,context:i}){super({breadcrumbs:t,context:i}),this.document=r,this.operation=n}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=oFm.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json",terminator:void 0,resumable:!1}:void 0;let n=r.data.resumable??lqo(this.document)??!1;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format,terminator:r.data.terminator,resumable:n};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",terminator:r.data.terminator,streamDescription:r.data["stream-description"],streamConditionProperty:S0.maybeTrimPrefix(r.data["stream-condition"],nFm),streamRequestName:r.data["stream-request-name"],responseStream:r.data["response-stream"],response:r.data.response,resumable:n}}}});var PYr,cGu=h(()=>{"use strict";rs();PYr=class extends os{operation;key="x-fern-subtitle";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-subtitle",path:this.breadcrumbs});return}return t}}}});var BYr,uGu=h(()=>{"use strict";rs();BYr=class extends os{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}}});function sFm(e){return gi(e)&&typeof e.$ref=="string"}function aFm(e,t){if(e!=null){if(typeof e=="string")return e;if(sFm(e)){let r=(0,lGu.resolve)(t??process.cwd(),e.$ref);if((0,DYr.existsSync)(r))try{return(0,DYr.readFileSync)(r,"utf-8")}catch{return}}}}var DYr,lGu,RYr,pGu=h(()=>{"use strict";ct();rs();DYr=require("fs"),lGu=require("path");RYr=class extends os{operation;baseDir;key="x-codeSamples";constructor({context:t,breadcrumbs:r,operation:n,baseDir:i}){super({breadcrumbs:r,context:t}),this.operation=n,this.baseDir=i}convert(){let t=gi(this.operation)?this.operation:{},r=t["x-codeSamples"],n=t["x-code-samples"],i=Array.isArray(r)?r:[],o=Array.isArray(n)?n:[],s=[...i,...o];if(s.length===0)return;let a=[];for(let c of s){if(!gi(c))continue;let u=c,l=u.lang,p=u.label,d=u.source;if(typeof l!="string")continue;let f=aFm(d,this.baseDir);f!=null&&a.push({name:typeof p=="string"?p:l,language:l,code:f,install:void 0,docs:void 0})}if(a.length!==0)return[{"code-samples":a}]}}});function cFm(e){return gi(e)&&typeof e.$ref=="string"}function uFm(e,t){if(e!=null){if(typeof e=="string")return e;if(cFm(e)){let r=(0,fGu.resolve)(t??process.cwd(),e.$ref);if((0,FYr.existsSync)(r))try{return(0,FYr.readFileSync)(r,"utf-8")}catch{return}}}}function lFm(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!gi(n))continue;let o=uFm(n.code,t);o!=null&&r.push({...n,code:o})}return r}var FYr,fGu,kYr,dGu=h(()=>{"use strict";ct();Io();rs();FYr=require("fs"),fGu=require("path");kYr=class extends os{operation;baseDir;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:n,baseDir:i}){super({breadcrumbs:r,context:t}),this.operation=n,this.baseDir=i}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).map(o=>{if(!gi(o))return o;let a=o["code-samples"];if(a!=null){let c=lFm(a,this.baseDir);return{...o,"code-samples":c}}return o}).filter(o=>{let s=tm.serialization.ExampleEndpointCallSchema.parse(o);return s.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),s.ok})}}});var pWt,mGu=h(()=>{"use strict";rs();pWt=class extends os{document;key="x-fern-explorer";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}}});var fWt,hGu=h(()=>{"use strict";ct();Wn();rs();fWt=class extends Hm.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;convertedResponseHeaders;constructor({context:t,breadcrumbs:r,responseBody:n,group:i,method:o,statusCode:s,streamingExtension:a}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseBody=n,this.statusCode=s,this.streamingExtension=a}convert(){if(parseInt(this.statusCode)===204){this.responseBody.content!=null&&Object.keys(this.responseBody.content).length>0&&this.context.errorCollector.collect({message:"A 204 (No Content) response declares a body, but a 204 response cannot include one. Ignoring the declared body and treating the success response as optional.",path:this.breadcrumbs});return}return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,n=[...this.group,this.method,"Response",this.statusCode].join("_"),i=`${n}_streaming`,o=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:i}),s=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:n});return this.convertStreamConditionResponse({convertedStreamingSchema:o,convertedNonStreamingSchema:s})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}),n=this.streamingExtension.format==="sse"?[...r.filter(i=>i.includes("text/event-stream")),...r.filter(i=>!i.includes("text/event-stream"))]:r;for(let i of n){let o=this.responseBody.content?.[i];if(o==null)continue;let s=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:this.streamingExtension.format});if(s!=null)return this.convertStreamingResponse({mediaTypeObject:o,convertedSchema:s})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(o=>o.includes("json"));for(let o of r){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null&&this.shouldReturnJsonResponse(o))return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}let n=Object.keys(this.responseBody.content??{}).filter(o=>!o.includes("json"));for(let o of n){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null){if(this.isBinarySchema(a))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:s}):this.returnFileDownloadResponse({mediaTypeObject:s});if(this.shouldReturnTextResponse(o))return this.returnTextResponse({mediaTypeObject:s,contentType:o})}}let i=parseInt(this.statusCode);if(!isNaN(i)&&i>=200&&i<300&&i!==204){let o=r.map(c=>this.responseBody.content?.[c]).find(c=>c!=null),s={schema:{type:"object",description:"Empty response body"},...o?.examples!=null&&{examples:o.examples},...o?.example!=null&&{example:o.example}},a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:"application/json",resolveSchema:!0});if(a!=null)return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}}convertStreamConditionResponse({convertedStreamingSchema:t,convertedNonStreamingSchema:r}){if(t==null||r==null)return;let n=this.responseBody.description;return this.streamingExtension?.type==="streamCondition"&&this.streamingExtension.streamDescription!=null&&(n=this.streamingExtension.streamDescription),{responseBody:_u.json(gI.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:_u.streaming(Ev.json({docs:n,payload:t.type,terminator:this.streamingExtension?.terminator,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},headers:this.convertResponseHeaders().headers}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:_u.streaming(Ev.json({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers};case"sse":return{responseBody:_u.streaming(Ev.sse({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,resumable:this.streamingExtension?.resumable,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:_u.json(gI.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:_u.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:_u.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}returnTextResponse({mediaTypeObject:t,contentType:r}){return{responseBody:_u.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"}),contentType:of.parse(r)?.isPlainText()?void 0:r}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return of.parse(t)?.isText()??!1}convertResponseHeaders(){return this.convertedResponseHeaders??=dlt({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseBody.headers}),this.convertedResponseHeaders}}});var NYr,gGu=h(()=>{"use strict";ct();Wn();rs();NYr=class extends Hm.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;convertedResponseHeaders;constructor({context:t,breadcrumbs:r,responseError:n,group:i,method:o,methodName:s,statusCode:a,isWildcardStatusCode:c}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseError=n,this.statusCode=a,this.methodName=s,this.isWildcardStatusCode=c}convert(){if(!this.responseError.content){let n=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(n==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let i=this.getErrorIdFromErrorName(n);return{error:{error:{name:this.context.casingsGenerator.generateName(i),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:i},docs:this.responseError.description},errorType:en.unknown(),displayName:n,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:this.convertResponseHeaders().inlinedTypes,examples:{},headers:this.convertResponseHeaders().headers}}let t=Object.keys(this.responseError.content).filter(n=>n.includes("json")),r=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let n of[...t]){let i=this.responseError.content?.[n];if(i==null)continue;let o=this.parseMediaTypeObject({mediaTypeObject:i,schemaId:BH(`${this.methodName}Request${r}`),contentType:n});if(o==null)continue;let s=this.getErrorIdFromErrorName(r);if(o.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.schema.typeDeclaration.name.fernFilepath,convertedSchema:o,mediaTypeObject:i});if(o.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.type.fernFilepath,convertedSchema:o,mediaTypeObject:i})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:n,convertedSchema:i,mediaTypeObject:o}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:n,errorId:r},docs:this.responseError.description},errorType:i.type,displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:{...i.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:this.convertErrorExamples({mediaTypeObject:o}),headers:this.convertResponseHeaders().headers}}convertErrorExamples({mediaTypeObject:t}){let r=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_error_example`});if(r.length===0)return;let n=new Set,i={};for(let[o,s]of r){let a=this.context.resolveExampleWithValue(s),c=this.context.resolveExampleRecursively({example:s,breadcrumbs:this.breadcrumbs}),u=this.getIdForErrorExample({key:o,example:c,usedExampleNames:n});n.add(u),a!=null&&(i[u]=a)}return Object.keys(i).length>0?i:void 0}getIdForErrorExample({key:t,example:r,usedExampleNames:n}){if(this.context.isExampleWithSummary(r)){let i=r.summary;if(!n.has(i))return i;let o=`${i} (${t})`;return n.has(o)?t:o}return t}getErrorNameForStatusCode(t,r){if(r){if(t===400)return"ClientRequestError";if(t===500)return"ServerError"}return pYr[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?BH(`${this.methodName}Request${t}`):t}convertResponseHeaders(){return this.convertedResponseHeaders??=dlt({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseError.headers}),this.convertedResponseHeaders}}});var jYr,AGu=h(()=>{"use strict";Io();Wn();hc();R5();rs();qi();pGu();dGu();mGu();hGu();gGu();sqo();jYr=class e extends glt{idempotent;subtitle;globalParameterIds;idToAuthScheme;topLevelServers;pathLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s,idempotent:a,subtitle:c,globalParameterIds:u,idToAuthScheme:l,topLevelServers:p,pathLevelServers:d,streamingExtension:f}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}),this.idempotent=a,this.subtitle=c,this.globalParameterIds=u,this.idToAuthScheme=l,this.topLevelServers=p,this.pathLevelServers=d,this.streamingExtension=f}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=this.getGroupDisplayName(r),o=this.getGroupDescription(r),{headers:s,pathParameters:a,queryParameters:c}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),u=this.collectQueryParameterAudiences({breadcrumbs:[...this.breadcrumbs,"parameters"]}),l=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:n,streamingExtension:this.streamingExtension,queryParameters:c}),p=l?.[0]?.requestBody,d=l?.[0]?.streamRequestBody,f=l?.[0]?.inlinedPropertiesByAudience,m={requestBodies:l?.map(ue=>ue.requestBody)},g=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:n,streamingExtension:this.streamingExtension}),A=g?.response,y=g?.streamResponse,I=g!=null?g.errors:[],x={},v=I.map(ue=>ue.error),S=sb(this.path),B=this.context.perSpecBasePath,R=this.getEndpointBaseUrl(),D=this.getEndpointBaseUrls(),O=this.convertExamples({httpPath:S,httpMethod:t,baseUrl:R});if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0){let ue=this.synthesizeEndpointExamplesFromNativeRequestBody({httpPath:S,httpMethod:t,baseUrl:R});if(ue!=null)for(let[Oe,Ie]of Object.entries(ue))O.examples[Oe]=Ie}if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0&&l!=null&&l.length>1){let ue=this.synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:l,httpPath:S,httpMethod:t,baseUrl:R});if(ue!=null)for(let[Oe,Ie]of Object.entries(ue))O.examples[Oe]=Ie}let z=new Set(this.operation.security?.flatMap(ue=>Object.keys(ue))??[]),Y=this.authSchemeToHeaders(Array.from(z));Y.length>0&&s.push(...Y);for(let ue of I){let Oe=ue.error,Ie=ue.errorType,je=Oe.error.errorId,Ge=ue.examples;x[je]={name:Oe.error,displayName:ue.displayName,discriminantValue:{name:Oe.error.name,wireValue:je},type:Ie,statusCode:ue.statusCode,isWildcardStatusCode:ue.isWildcardStatusCode,docs:Oe.docs,examples:[],v2Examples:{userSpecifiedExamples:Ge??{},autogeneratedExamples:{}},headers:ue.headers}}let te=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],se=new pWt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),me=new pWt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??se,Se={displayName:this.operation.summary,subtitle:this.subtitle,method:t,baseUrl:R,v2BaseUrls:D,path:S,pathParameters:a,queryParameters:c,headers:s.filter((ue,Oe,Ie)=>Oe===Ie.findIndex(je=>ur(je.name)===ur(ue.name))),responseHeaders:g?.responseHeaders,sdkRequest:void 0,errors:v,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:B!=null?sb(B):void 0,fullPath:B!=null?sb(`${B}${this.path}`):S,allPathParameters:a,pagination:void 0,transport:void 0,source:AD.openapi(),audiences:te,retries:void 0,globalParameters:this.globalParameterIds,apiPlayground:me},Re=this.context.namespace!=null?[this.context.namespace]:[],ce=r?.map(ue=>ti(ue));return Re.push(...ce??[]),{audiences:te,group:r,groupDisplayName:i,groupDescription:o,errors:x,endpoint:{...Se,id:`endpoint_${Re.join("/")}.${n}`,name:this.context.casingsGenerator.generateName(n),requestBody:p,v2RequestBodies:m,response:A,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:O.examples},v2Responses:{responses:g?.v2Responses}},streamEndpoint:y!=null&&y.body!=null?{...Se,id:`endpoint_${Re.join("/")}.${n}_stream`,name:this.context.casingsGenerator.generateName(`${n}_stream`),requestBody:d,v2RequestBodies:void 0,response:y,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:O.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:y.body,docs:y.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[]),inlinedRequestPropertiesByAudience:f,queryParametersByAudience:u}}collectQueryParameterAudiences({breadcrumbs:t}){let r=this.mergeParameters(this.pathItemParameters,this.operation.parameters??[]);if(r.length===0)return;let n={},i=!1;for(let o of r){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:t,skipErrorCollector:!0});if(s==null||s.in!=="query")continue;let a=this.context.getAudiences({operation:s,breadcrumbs:t})??[];if(a.length!==0){i=!0;for(let c of a)n[c]==null&&(n[c]=new Set),n[c].add(s.name)}}return i?n:void 0}convertResponseBody({breadcrumbs:t,group:r,method:n,streamingExtension:i}){if(this.operation.responses==null)return;let o,s=!1,a=!1;for(let[c,u]of Object.entries(this.operation.responses)){let l=/^[45]XX$/i.test(c),p,d=!1;if(l)p=parseInt(c.charAt(0))*100,d=!0;else{if(p=parseInt(c),isNaN(p)||p<200||p>=300&&p<400)continue;d=p>=400&&p<600}if(o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]}),p>=200&&p<300){let f=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,c]});if(f==null)continue;let g=new fWt({context:this.context,breadcrumbs:[...t,c],responseBody:f,group:r??[],method:n,statusCode:c,streamingExtension:i}).convert();if(g==null){a=!0,o.response==null&&(o.response={statusCode:p,isWildcardStatusCode:l?!0:void 0,body:void 0,docs:f.description});continue}g!=null&&(this.inlinedTypes={...this.inlinedTypes,...g.inlinedTypes},s||(s=!0,o.response={statusCode:p,isWildcardStatusCode:l?!0:void 0,body:g.responseBody,docs:f.description},o.streamResponse={statusCode:p,isWildcardStatusCode:l?!0:void 0,body:g.streamResponseBody,docs:f.description},g.headers!=null&&(o.responseHeaders=g.headers)),o.v2Responses=[...o.v2Responses??[],{statusCode:p,isWildcardStatusCode:l?!0:void 0,body:g.responseBody,docs:f.description}])}if(d){let f=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,c]});if(f==null)continue;let g=new NYr({context:this.context,breadcrumbs:[...t,c],responseError:f,group:r??[],method:n,methodName:this.evaluateMethodNameFromOperation(),statusCode:p,isWildcardStatusCode:l?!0:void 0}).convert();g!=null&&(this.inlinedTypes={...this.inlinedTypes,...g.inlinedTypes},o.errors.push(g))}}if(this.streamingExtension!=null){o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]});let u=new fWt({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:n,statusCode:"stream",streamingExtension:i}).convert();u!=null&&(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},o.response={statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0},o.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:u.streamResponseBody,docs:void 0},o.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0}])}if(a&&s&&o?.response?.body!=null){let c=o.response.body;if(c.type==="json"&&c.value.type==="response"){let u=c.value.responseBodyType;(u.type!=="container"||u.container.type!=="optional")&&(o.response={...o.response,body:_u.json(gI.response({...c.value,responseBodyType:en.container(Ts.optional(u))}))})}}return o}computeEndpointAuth(){return this.operation.security!=null&&this.operation.security.length===0?!1:this.operation.security!=null&&this.operation.security.length>0?!0:this.context.spec.security!=null&&this.context.spec.security.length>0||this.shouldApplyDefaultAuthOverrides()}computeEndpointSecurity(){return this.operation.security!=null&&this.operation.security.length===0?[]:this.context.authOverrides?.auth!=null&&!this.usesEndpointSecurity()?this.getDefaultSecurityFromAuthOverrides():$Go(this.operation.security??this.context.spec.security)}usesEndpointSecurity(){let t=this.context.authOverrides?.auth;return t!=null&&qtt(t)}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth||this.usesEndpointSecurity())return!1;let t=this.context.spec.security!=null&&this.context.spec.security.length>0,r=this.operation.security!=null&&this.operation.security.length>0;return!(t||r)}getDefaultSecurityFromAuthOverrides(){if(!this.context.authOverrides?.auth)return;let t=this.context.authOverrides.auth;if(typeof t=="string"){let r={};return r[t]=[],[r]}if(typeof t=="object"&&"any"in t){let r=t.any;if(Array.isArray(r))return r.map(n=>{let i=typeof n=="string"?n:n.scheme,o={};return o[i]=[],o})}}authSchemeToHeaders(t){let r=[];for(let n of t){let i=this.idToAuthScheme?.[n];if(i==null)continue;let o={valueType:co.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0,clientDefault:void 0,defaultValue:void 0};switch(i.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...o});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...o});break;case"header":r.push({name:i.name,...o});break}}return r}convertExamples({httpPath:t,httpMethod:r,baseUrl:n}){let o=new kYr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],a=new RYr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],u=o.some(l=>Array.isArray(l["code-samples"])&&l["code-samples"].length>0)?o:[...o,...a];return u.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:u}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:u}),streamExamples:{}}}synthesizeEndpointExamplesFromNativeRequestBody({httpPath:t,httpMethod:r,baseUrl:n}){if(this.operation.requestBody==null)return;let i=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:[...this.breadcrumbs,"requestBody"]});if(i==null)return;let o=this.extractNativeResponseExample(),s={};for(let[,a]of Object.entries(i.content)){if(a.schema!=null)continue;let c=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:a,breadcrumbs:[...this.breadcrumbs,"requestBody"],defaultExampleName:"Example"});for(let[u,l]of c){let p=this.context.resolveExampleWithValue(l);p!=null&&(s[u]={displayName:void 0,contentType:void 0,request:{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:p},response:o,codeSamples:void 0})}}return Object.keys(s).length>0?s:void 0}extractNativeResponseExample(){if(this.operation.responses!=null)for(let[t,r]of Object.entries(this.operation.responses)){let n=parseInt(t);if(isNaN(n)||n<200||n>=300)continue;let i=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[...this.breadcrumbs,"responses",t]});if(i?.content!=null)for(let[,o]of Object.entries(i.content)){let s=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...this.breadcrumbs,"responses",t],defaultExampleName:"Example"});for(let[,a]of s){let c=this.context.resolveExampleWithValue(a);if(c!=null)return{docs:void 0,statusCode:n,body:Zt.V2HttpEndpointResponseBody.json(c)}}}}}synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:t,httpPath:r,httpMethod:n,baseUrl:i}){let o={},s=this.extractNativeResponseExamplesByContentType();for(let a of t){let c=a.requestBody,u=c.contentType,l=c.v2Examples;if(l==null)continue;let p=l.userSpecifiedExamples;if(Object.keys(p).length===0)continue;let d=u!=null?s.get(u):void 0;for(let[f,m]of Object.entries(p)){let g=t.length>1&&u!=null?`${f} (${u})`:f;o[g]={displayName:t.length>1?g:void 0,contentType:u??void 0,request:{docs:void 0,endpoint:{method:n,path:this.buildExamplePath(r,{})},baseUrl:void 0,environment:i,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:m},response:d??this.extractNativeResponseExample()??void 0,codeSamples:void 0}}}return Object.keys(o).length>0?o:void 0}extractNativeResponseExamplesByContentType(){let t=new Map;if(this.operation.responses==null)return t;for(let[r,n]of Object.entries(this.operation.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"responses",r]});if(o?.content!=null)for(let[s,a]of Object.entries(o.content)){if(t.has(s))continue;let c=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:a,breadcrumbs:[...this.breadcrumbs,"responses",r],defaultExampleName:"Example"});for(let[,u]of c){let l=this.context.resolveExampleWithValue(u);if(l!=null){t.set(s,{docs:void 0,statusCode:i,body:Zt.V2HttpEndpointResponseBody.json(l)});break}}}}return t}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){let o=i.filter(u=>!(u.response!=null&&"stream"in u.response)),s=i.filter(u=>u.response!=null&&"stream"in u.response),a=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:o}),c=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:s});return{examples:a,streamExamples:c}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){return Object.fromEntries(i.map((o,s)=>[this.getExampleName({example:o,exampleIndex:s}),{displayName:void 0,contentType:void 0,request:o.request!=null||o["path-parameters"]!=null||o["query-parameters"]!=null||o.headers!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,o["path-parameters"]??{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:o["path-parameters"]??{},queryParameters:o["query-parameters"]??{},headers:o.headers??{},requestBody:o.request??void 0}:void 0,response:o.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:o})}:void 0,codeSamples:o["code-samples"]?.map(a=>{let c=("language"in a?a.language:a.sdk)??void 0;return{name:a.name,docs:void 0,language:c,code:a.code}})}]))}getExampleName({example:t,exampleIndex:r}){return t.name??t["code-samples"]?.[0]?.name??`Example_${r}`}getExampleResponseBody({example:t}){if(t.response!=null){if("stream"in t.response)return Zt.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return Zt.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new qC.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert();if(r!=null)return this.context.logger.debug(`[getEndpointBaseUrl] Endpoint ${this.method.toUpperCase()} ${this.path} specifies a server with "${mn.SERVER_NAME_V2}" extension. Returning server type: ${r}`),r;let n=this.operation.servers?.[0]??this.pathLevelServers?.[0];if(n==null)return;let o=this.topLevelServers?.find(s=>s.url===n.url)??n;return N4.getServerName({server:o,context:this.context})}getEndpointBaseUrls(){if(new qC.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()!=null)return;let n=this.operation.servers??this.pathLevelServers;return n?.map(o=>{let a=this.topLevelServers?.find(c=>c.url===o.url)??o;return N4.getServerName({server:a,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(n=>`${r[n.pathParameter]?.toString()??n.pathParameter}${n.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(n=>n.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0],n=t?.[t.length-1];if(r==null||n==null)return;let i=this.context.getDisplayNameForTag(r);if(i.toLowerCase().replaceAll(" ","")===n||this.context.hasExplicitDisplayNameForTag(r)&&ti(r)===ti(n))return i}getGroupDescription(t){let r=this.operation.tags?.[0],n=t?.[t.length-1];if(!(r==null||n==null)&&ti(r)===ti(n))return this.context.getDescriptionForTag(r)}}});var pqo,zYr,yGu=h(()=>{"use strict";rs();pqo=ye(Q4t(),1);rGu();nGu();iGu();sGu();aGu();cGu();uGu();AGu();aqo();zYr=class extends co{pathItem;path;idToAuthScheme;topLevelServers;declaredGlobalParameterIds;constructor({context:t,breadcrumbs:r,pathItem:n,path:i,idToAuthScheme:o,topLevelServers:s,declaredGlobalParameterIds:a}){super({context:t,breadcrumbs:r}),this.pathItem=n,this.path=i,this.idToAuthScheme=o,this.topLevelServers=s,this.declaredGlobalParameterIds=a}convert(){let t=[],r=[],n={};for(let i of tGu){let o=this.pathItem[i];if(o==null)continue;let s=[...this.breadcrumbs,i],a=this.tryParseAsWebhook({operationBreadcrumbs:s,operation:o,method:i,context:this.context});if(a!=null){r.push(a),Object.assign(n,a.inlinedTypes);continue}let u=new OYr({breadcrumbs:s,document:this.context.spec,operation:o,context:this.context}).convert();u==null&&this.operationHasTextEventStreamResponse(o)&&(u={type:"stream",format:"sse",terminator:void 0,resumable:lqo(this.context.spec)??!1});let l=this.tryParseAsHttpEndpoint({operationBreadcrumbs:s,operation:o,method:i,streamingExtension:u});l!=null&&(t.push(l),Object.assign(n,l.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:n}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:n,context:i}){return new BYr({breadcrumbs:n,operation:t,context:i}).convert()?new Alt({context:this.context,breadcrumbs:n,operation:t,method:pqo.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters}).convert():void 0}operationHasTextEventStreamResponse(t){if(t.responses==null)return!1;for(let[r,n]of Object.entries(t.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(o?.content==null)continue;let s=Object.keys(o.content);if(s.length===1&&s[0]?.includes("text/event-stream"))return!0}return!1}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:n,streamingExtension:i}){new TYr({breadcrumbs:n,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let c=new wYr({breadcrumbs:n,operation:t,context:this.context}).convert(),l=new PYr({breadcrumbs:n,operation:t,context:this.context}).convert(),d=new SYr({breadcrumbs:n,operation:t,context:this.context}).convert();if(d!=null&&this.declaredGlobalParameterIds!=null){let m=[];for(let g of d)this.declaredGlobalParameterIds.has(g)?m.push(g):this.context.errorCollector.collect({message:`x-fern-global-parameter references undeclared global parameter '${g}'. Declared parameters: ${[...this.declaredGlobalParameterIds].join(", ")}`,path:[...n,"x-fern-global-parameter"]});d=m.length>0?m:void 0}return new jYr({context:this.context,breadcrumbs:n,operation:t,method:pqo.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters,idempotent:c,subtitle:l,globalParameterIds:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:i}).convert()}}});var QYr,bGu=h(()=>{"use strict";Wn();rs();QYr=class extends co{securityScheme;schemeId;constructor({context:t,breadcrumbs:r,securityScheme:n,schemeId:i}){super({context:t,breadcrumbs:r}),this.securityScheme=n,this.schemeId=i}getExtension(t){return this.securityScheme[t]}convert(){let t=this.getExtension("x-fern-playground-description");switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme?.toLowerCase()==="bearer"){let r=this.getExtension("x-fern-bearer"),n=r?.name??"token",i=r?.env,o=r?.placeholder;return Hp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName(n),tokenEnvVar:i,tokenPlaceholder:o,docs:this.securityScheme.description,playgroundDocs:t})}if(this.securityScheme.scheme?.toLowerCase()==="basic"){let r=this.getExtension("x-fern-basic"),n=r?.username?.name??"username",i=r?.password?.name??"password",o=r?.username?.env,s=r?.password?.env,a=r?.username?.placeholder,c=r?.password?.placeholder;return Hp.basic({key:this.schemeId,username:this.context.casingsGenerator.generateName(n),password:this.context.casingsGenerator.generateName(i),usernameEnvVar:o,passwordEnvVar:s,usernameOmit:!1,passwordOmit:!1,usernamePlaceholder:a,passwordPlaceholder:c,docs:this.securityScheme.description,playgroundDocs:t})}break}case"apiKey":{if(this.securityScheme.in==="header"){let r=this.getExtension("x-fern-header"),n=r?.name??"apiKey",i=r?.env,o=r?.prefix,s=r?.placeholder;return Hp.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(n),wireValue:this.securityScheme.name},valueType:co.OPTIONAL_STRING,prefix:o,headerEnvVar:i,headerPlaceholder:s,docs:this.securityScheme.description,playgroundDocs:t})}break}case"oauth2":return Hp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:this.securityScheme.description,playgroundDocs:t})}}}});function pFm(e){if(e!=null){if(typeof e=="string")return cE.string(e);if(typeof e=="boolean")return cE.boolean(e)}}var EGu,dWt,IGu=h(()=>{"use strict";ct();Io();Wn();hc();R5();rs();EGu=ye(Q4t(),1);V8u();G8u();q8u();W8u();K8u();Y8u();Z8u();aqo();yGu();bGu();dWt=class extends PJ{constructor({breadcrumbs:t,context:r,audiences:n}){super({breadcrumbs:t,context:r,audiences:n})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.context.spec=M4t({document:this.context.spec,options:this.context.settings,logger:this.context.logger}),ZGo({spec:this.context.spec,errorCollector:this.context.errorCollector}),this.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertGlobalParameters(),this.convertBasePath(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:t,errors:r}=this.convertPaths();this.addErrorsToIr(r);let{defaultUrl:n}=this.convertServers({endpointLevelServers:t});this.updateEndpointsWithDefaultUrl(n);let i=this.context.spec.info?.title?.trim();return i&&i!=='""'&&(this.ir.apiDisplayName=i),this.finalizeIr()}convertGlobalHeaders(){if(this.context.globalHeaderOverrides){let n=H8u({globalHeaderOverrides:this.context.globalHeaderOverrides,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n);return}let r=new IYr({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=J8u({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n)}}convertGlobalParameters(){let r=new vYr({breadcrumbs:["x-fern-global-parameters"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=X8u({globalParameters:r,context:this.context});if(this.ir.globalParameters=n,this.ir.headers.length>0){let i=new Set(this.ir.headers.map(o=>{let s=o.name;return(typeof s=="string"?s:s.wireValue).toLowerCase()}));for(let o of r){let s=(o.target??o.name).toLowerCase();o.in==="header"&&i.has(s)&&this.context.logger.warn(`Global parameter "${o.name}" (in: header, target: "${o.target??o.name}") overlaps with an x-fern-global-headers entry. The x-fern-global-parameters definition takes precedence.`)}}}}convertBasePath(){let r=new bYr({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();if(r!=null){if(this.context.settings.respectPerSpecBasePath&&r.parameters.length===0){r.pathsIncludeBasePath||(this.context.perSpecBasePath=Hy(r.path));return}this.context.settings.respectPerSpecBasePath&&r.parameters.length>0&&this.context.errorCollector.collect({message:"respect-per-spec-base-path only applies to an x-fern-base-path without path parameters; this base path is used as the API-wide base path instead, which only one spec keeps when multiple specs are merged",path:["x-fern-base-path"]}),this.ir.basePath=sb(r.path);for(let n of r.parameters)n.type!=="string"&&this.context.errorCollector.collect({message:`x-fern-base-path parameter '${n.name}' uses type '${n.type}' which is not yet supported; treating as string`,path:["x-fern-base-path","parameters",n.name]}),this.ir.pathParameters.push({name:this.context.casingsGenerator.generateName(n.name),valueType:co.STRING,docs:n.docs,location:Zt.PathParameterLocation.Root,variable:void 0,clientDefault:pFm(n.default),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},explode:void 0});if(r.pathsIncludeBasePath){let n=z4t({openApi:this.context.spec,basePath:r.path,rootPathParameterNames:new Set(r.parameters.map(i=>i.name))});for(let i of n)this.context.errorCollector.collect({message:i,path:["x-fern-base-path","paths-include-base-path"]})}}}convertSecuritySchemes(){let t=this.convertOpenApiSecuritySchemes();if(this.context.authOverrides){let r=new Map(t.map(n=>[n.key,n.docs]));this.convertAuthOverrides(r,this.context.authOverrides);return}t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertAuthOverrides(t,r){let n={...r,"auth-schemes":Object.fromEntries(Object.entries(r["auth-schemes"]??{}).map(([o,s])=>[o,{...s}]))};for(let[o,s]of Object.entries(n["auth-schemes"]))!s.docs&&t.has(o)&&(s.docs=t.get(o));let i=JGt({rawApiFileSchema:n,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:i.requirement,schemes:i.schemes,docs:i.docs})}convertOpenApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let s=new QYr({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:i,schemeId:r}).convert();s!=null&&t.push(s)}return t}convertServers({endpointLevelServers:t}){let n=new EYr({breadcrumbs:["x-fern-base-url-env"],document:this.context.spec,context:this.context}).convert();if(this.context.environmentOverrides){let s=YGt({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return s!=null&&this.addEnvironmentsToIr({environmentConfig:{...s.environmentsConfig,baseUrlEnvVar:s.environmentsConfig.baseUrlEnvVar??n},audiences:s.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let o=new N4({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t,baseUrlEnvVar:n}).convert();return this.addEnvironmentsToIr({environmentConfig:o?.value}),{defaultUrl:o?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Hm.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();i!=null&&this.addSchemaOutputToIr(t,i)}}convertWebhooks(){for(let[t,r]of Object.entries(this.context.spec.webhooks??{})){if(r==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});continue}if(!("post"in r)||r.post==null){this.context.errorCollector.collect({message:"Skipping webhook as it is not a POST method",path:this.breadcrumbs});continue}let n=r.post.operationId??t,i=r.post.operationId!=null?r.post:{...r.post,operationId:n},s=new Alt({context:this.context,breadcrumbs:["webhooks",n],operation:i,method:EGu.OpenAPIV3.HttpMethods.POST,path:n}).convert();s!=null&&(this.addWebhookToIr({webhook:s.webhook,operationId:n,audiences:s.audiences,group:s.group,inlinedPayloadPropertiesByAudience:s.inlinedPayloadPropertiesByAudience}),this.addTypesToIr(s.inlinedTypes))}}convertPaths(){let t=[],r={},n=this.ir.globalParameters!=null?new Set(this.ir.globalParameters.map(i=>i.id)):void 0;for(let[i,o]of Object.entries(this.context.spec.paths??{})){if(o==null)continue;let a=new zYr({context:this.context,breadcrumbs:["paths",i],topLevelServers:this.context.spec.servers,pathItem:o,path:i,declaredGlobalParameterIds:n}).convert();if(a!=null){for(let c of a.endpoints){if(c.streamEndpoint!=null&&this.addEndpointToIr({endpoint:c.streamEndpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName,endpointGroupDescription:c.groupDescription,inlinedRequestPropertiesByAudience:c.inlinedRequestPropertiesByAudience,queryParametersByAudience:c.queryParametersByAudience}),this.addEndpointToIr({endpoint:c.endpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName,endpointGroupDescription:c.groupDescription,inlinedRequestPropertiesByAudience:c.inlinedRequestPropertiesByAudience,queryParametersByAudience:c.queryParametersByAudience}),c.servers)for(let u of c.servers)this.shouldAddServerToCollectedServers({server:u,currentServers:t})&&t.push(u);if(c.errors)for(let[u,l]of Object.entries(c.errors))r[u]=l}for(let c of a.webhooks){let u=this.context.getGroup({groupParts:c.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:c.webhook,operationId:u.join("."),group:u,audiences:c.audiences,inlinedPayloadPropertiesByAudience:c.inlinedPayloadPropertiesByAudience})}this.addTypesToIr(a.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;let t=this.context.authOverrides.auth;if(t!=null&&qtt(t))return;let r={};for(let n of Object.keys(this.context.authOverrides["auth-schemes"]))r[n]=[];this.context.spec.security=[r],this.removeEndpointSpecificAuth()}removeEndpointSpecificAuth(){if(this.context.spec.paths)for(let t of Object.values(this.context.spec.paths)){if(!t)continue;let r=["get","post","put","patch","delete","options","head","trace"];for(let n of r){let i=t[n];i?.security!=null&&i.security.length>0&&delete i.security}}}}});var MYr,vGu=h(()=>{"use strict";rs();MYr=class extends os{tag;key="x-displayName";constructor({breadcrumbs:t,tag:r,context:n}){super({breadcrumbs:t,context:n}),this.tag=r}convert(){if(typeof this.tag!="object"||this.tag==null)return;let t=this.tag[this.key];if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"x-displayName extension must be a string",path:this.breadcrumbs});return}if(t.trim().length!==0)return{displayName:t}}}}});var CVe,CGu=h(()=>{"use strict";Wn();hc();rs();vGu();CVe=class extends S0{perSpecBasePath;globalHeaderNames;tagToDisplayName={};tagsWithExplicitDisplayName=new Set;tagToDescription=new Map;tagDescriptionsIndexed=!1;isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=t.$ref.split("/").pop()??o,a=this.resolveReference({reference:t,breadcrumbs:r});if(!a.resolved)return{ok:!1};let c;i==="reference_identifier"?c=n??a.value.title:i==="discriminator_key"?c=a.value.title??n:c=a.value.title??s;let u;if(o.includes("/")){let p=new Hm.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:a.value,id:o}).convert();p!=null&&(u={[o]:p.convertedSchema})}return{ok:!0,reference:en.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(s),typeId:o,default:void 0,inline:!1,displayName:c}),inlinedTypes:u}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>ur(r.name))}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let i=new MYr({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName;i!=null&&this.tagsWithExplicitDisplayName.add(r.name),this.tagToDisplayName[r.name]=i??r.name}return this.tagToDisplayName[t]??t}hasExplicitDisplayNameForTag(t){return this.getDisplayNameForTag(t),this.tagsWithExplicitDisplayName.has(t)}getDescriptionForTag(t){if(!this.tagDescriptionsIndexed){this.tagDescriptionsIndexed=!0;for(let r of this.spec.tags??[])r.description!=null&&r.description.trim().length>0&&this.tagToDescription.set(r.name,r.description)}return this.tagToDescription.get(t)}}});function dqo({ir:e,authOverrides:t}){if(!t["auth-schemes"]||!e.auth)return e;let r=t["auth-schemes"],n=[];for(let i of e.auth.schemes){if(i.type!=="bearer"){n.push(i);continue}let o=r[i.key];if(o==null){n.push(i);continue}let s=qfe(o,{header:()=>{},basic:()=>{},tokenBearer:()=>{},inferredBearer:()=>{},oauth:a=>dFm({ir:e,key:i.key,oauthScheme:a})});n.push(s??i)}return{...e,auth:{...e.auth,schemes:n}}}function dFm({ir:e,key:t,oauthScheme:r}){if(r.type!=="client-credentials")return;let n=r["get-token"];if(n==null)return;let i=xGu({ir:e,endpointRef:n.endpoint});if(i==null)return;let{endpoint:o,serviceId:s,subpackageId:a}=i,c=n["request-properties"],u=n["response-properties"],l=fqo({ir:e,endpoint:o,wireValue:RJ(c?.["client-id"],"client_id")}),p=fqo({ir:e,endpoint:o,wireValue:RJ(c?.["client-secret"],"client_secret")}),d=ylt({ir:e,endpoint:o,wireValue:RJ(u?.["access-token"],"access_token")});if(!(l==null||p==null||d==null))return Hp.oauth({key:t,docs:r.docs,playgroundDocs:r["playground-docs"],configuration:hD.clientCredentials({clientIdEnvVar:r["client-id-env"],clientSecretEnvVar:r["client-secret-env"],tokenPrefix:r["token-prefix"],tokenHeader:r["token-header"],scopes:r.scopes,tokenEndpoint:{endpointReference:{endpointId:o.id,serviceId:s,subpackageId:a},requestProperties:{clientId:l,clientSecret:p,scopes:void 0,customProperties:gFm({ir:e,endpoint:o,excludeWireValues:[RJ(c?.["client-id"],"client_id"),RJ(c?.["client-secret"],"client_secret")]})},responseProperties:{accessToken:d,expiresIn:ylt({ir:e,endpoint:o,wireValue:RJ(u?.["expires-in"],"expires_in")}),refreshToken:ylt({ir:e,endpoint:o,wireValue:RJ(u?.["refresh-token"],"refresh_token")})}},refreshEndpoint:r["refresh-token"]!=null?mFm({ir:e,refreshTokenConfig:r["refresh-token"]}):void 0})})}function mFm({ir:e,refreshTokenConfig:t}){let r=xGu({ir:e,endpointRef:t.endpoint});if(r==null)return;let{endpoint:n,serviceId:i,subpackageId:o}=r,s=t["request-properties"],a=t["response-properties"],c=fqo({ir:e,endpoint:n,wireValue:RJ(s?.["refresh-token"],"refresh_token")}),u=ylt({ir:e,endpoint:n,wireValue:RJ(a?.["access-token"],"access_token")});if(!(c==null||u==null))return{endpointReference:{endpointId:n.id,serviceId:i,subpackageId:o},requestProperties:{refreshToken:c},responseProperties:{accessToken:u,expiresIn:ylt({ir:e,endpoint:n,wireValue:RJ(a?.["expires-in"],"expires_in")}),refreshToken:ylt({ir:e,endpoint:n,wireValue:RJ(a?.["refresh-token"],"refresh_token")})}}}function xGu({ir:e,endpointRef:t}){let r=t.trim().split(/\s+/);if(r.length!==2)return;let n=fFm[r[0]?.toUpperCase()??""],i=Hy(r[1]);if(!(n==null||i==null))for(let[o,s]of Object.entries(e.services))for(let a of s.endpoints){if(a.method!==n)continue;if(hFm(a.fullPath)===i){let u=Object.entries(e.subpackages).find(([,l])=>l.service===o)?.[0];return{endpoint:a,serviceId:o,subpackageId:u}}}}function hFm(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return Hy(t)}function RJ(e,t){return e==null?t:e.match(/^\$(?:request|response)\.(.+)$/)?.[1]??e}function SGu(e,t){return e.find(r=>ur(r.name)===t)}function mqo(e,t){let r=e.types[t];if(r?.shape.type==="object")return r.shape.properties}function fqo({ir:e,endpoint:t,wireValue:r}){if(t.requestBody==null)return;let n;t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties.map(o=>({...o,xml:void 0})):t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=mqo(e,t.requestBody.requestBodyType.typeId));let i=n!=null?SGu(n,r):void 0;if(i!=null)return{propertyPath:void 0,property:pB.body({...i})}}function gFm({ir:e,endpoint:t,excludeWireValues:r}){if(t.requestBody==null)return;let n;if(t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties.map(s=>({...s,xml:void 0})):t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=mqo(e,t.requestBody.requestBodyType.typeId)),n==null)return;let i=new Set(r),o=n.filter(s=>!i.has(ur(s.name))).map(s=>({propertyPath:void 0,property:pB.body({...s})}));return o.length>0?o:void 0}function ylt({ir:e,endpoint:t,wireValue:r}){if(t.response?.body?.type!=="json")return;let n=t.response.body.value.responseBodyType;if(n.type!=="named")return;let i=mqo(e,n.typeId),o=i!=null?SGu(i,r):void 0;if(o!=null)return{propertyPath:void 0,property:o}}var fFm,wGu=h(()=>{"use strict";ct();Io();Wn();hc();fFm={GET:Tm.Get,POST:Tm.Post,PUT:Tm.Put,PATCH:Tm.Patch,DELETE:Tm.Delete}});var hqo=h(()=>{"use strict";IGu();CGu();wGu()});var AFm,yFm,bFm,LYr,TGu=h(()=>{"use strict";ct();rs();cn();AFm=De.object({description:De.string().optional(),required:De.boolean().optional(),deprecated:De.boolean().optional(),allowEmptyValue:De.boolean().optional(),style:De.string().optional(),explode:De.boolean().optional(),allowReserved:De.boolean().optional(),schema:De.any().optional(),example:De.any().optional(),examples:De.record(De.string(),De.any()).optional(),content:De.record(De.string(),De.any()).optional()}),yFm=AFm.extend({name:De.string(),in:De.string()}),bFm=De.array(yFm),LYr=class extends os{operation;key="x-fern-parameters";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null)try{return bFm.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${In(r)}`,path:this.breadcrumbs});return}}}});var _Yr,OGu=h(()=>{"use strict";Wn();hc();rs();_Yr=class extends co{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:n,pathParameters:i=[],queryParameters:o=[],headers:s=[],topLevelServers:a=[]}){super({context:t,breadcrumbs:r}),this.method=n,this.pathParameters=i,this.queryParameters=o,this.headers=s,this.topLevelServers=a}convert(){let t={},r="";for(let u of this.pathParameters)r+=`/{${Vr(u.name)}}`;let n=sb(r),i=[];for(let[u,l]of this.method.params.entries()){let p;if(this.context.isReferenceObject(l)){let g=this.context.resolveReference({reference:l});if(g.resolved)p=g.value;else continue}else p=l;let d=[this.method.name,"Param",p.name].join("_"),m=new Hm.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",p.name],schemaIdOverride:d,context:this.context,schemaOrReference:p.schema,wrapAsOptional:!p.required}).convert();m!=null&&(i.push({docs:p.description,availability:this.context.getAvailability({node:l,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:p.name,wireValue:p.name}),valueType:m.type,defaultValue:p.schema!=null&&typeof p.schema=="object"?p.schema.default:void 0,v2Examples:m.schema?.typeDeclaration.v2Examples,propertyAccess:void 0}),t={...m.inlinedTypes,...t,...m.schema!=null?{[d]:m.schema}:{}})}let o;if(this.method.result!=null){let u=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(u!=null){let l=new Hm.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:u.schema}),p=[this.method.name,"Result"].join("_"),d=l.convert();d!=null&&(o={docs:u.description,v2Examples:d.schema?.typeDeclaration.v2Examples,responseBodyType:d.type},t={...d.inlinedTypes,...t,...d.schema!=null?{[p]:d.schema}:{}})}}let s=this.getEndpointBaseUrls(),a=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:s,basePath:void 0,auth:!1,security:void 0,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,subtitle:void 0,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:n,fullPath:n,requestBody:i.length>0?Od.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:i,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,v2RequestBodies:void 0,sdkRequest:void 0,response:o!=null?{body:_u.json(gI.response(o)),statusCode:void 0,isWildcardStatusCode:void 0,docs:o.docs}:void 0,v2Responses:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples(r)},transport:void 0,availability:void 0,source:AD.openrpc({paramStructure:this.convertParamStructure()}),audiences:a,retries:void 0,globalParameters:void 0,apiPlayground:void 0,responseHeaders:[]},audiences:a,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}convertParamStructure(){let t=this.method.paramStructure;switch(t){case"by-name":return Zt.OpenRpcParamStructure.ByName;case"by-position":return Zt.OpenRpcParamStructure.ByPosition;case"either":return Zt.OpenRpcParamStructure.Either;case void 0:return;default:return}}convertExampleParams(t){return this.method.paramStructure==="by-name"?Object.fromEntries(t.map(r=>[r.name,r.value])):t.map(r=>r.value)}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(n=>n.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(n=>{if(this.topLevelServers.find(a=>a.name===n.name&&a.url!==n.url)!=null)return n.url;let s=this.topLevelServers.find(a=>a.url===n.url)??n;return N4.getServerName({server:s,context:this.context})})}convertExamples(t){let r={},n={};for(let o of this.pathParameters){let s=Object.values(o.v2Examples?.userSpecifiedExamples??{})[0],a=Object.values(o.v2Examples?.autogeneratedExamples??{})[0],c=s!==void 0?s:a;c!==void 0&&(n[Vr(o.name)]=c)}let i=0;if(this.method.examples&&this.method.examples.length>0){for(let o of this.method.examples??[]){let s;if(this.context.isReferenceObject(o)){let l=this.context.resolveReference({reference:o});if(l.resolved)s=l.value;else continue}else s=o;let a;if(s.result)if(this.context.isReferenceObject(s.result)){let l=this.context.resolveReference({reference:s.result});l.resolved&&(a=l.value)}else a=s.result;let c=s.name??`Example ${i+1}`,u=[];if(s.params&&Array.isArray(s.params)){u=[];for(let l of s.params)if(this.context.isReferenceObject(l)){let p=this.context.resolveReference({reference:l});if(p.resolved)u.push(p.value);else continue}else u.push(l)}r[c]={displayName:void 0,contentType:void 0,request:{docs:void 0,endpoint:{method:"POST",path:t},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:n,queryParameters:{},headers:{},requestBody:this.convertExampleParams(u)},response:{docs:void 0,statusCode:void 0,body:a?.value?Zt.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:s.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++i}return r}}});var UYr,PGu=h(()=>{"use strict";rs();UYr=class extends Hm.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={};if(this.parameter.schema!=null){let i=new Hm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();i!=null&&(t=i.type,r=i.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}}});var mWt,BGu=h(()=>{"use strict";rs();TGu();OGu();PGu();mWt=class extends PJ{constructor({context:t,breadcrumbs:r,audiences:n}){super({context:t,breadcrumbs:r,audiences:n})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.convertSchemas();let{endpointLevelServers:t}=this.convertMethods(),{defaultUrl:r}=this.convertServers({endpointLevelServers:t});return this.updateEndpointsWithDefaultUrl(r),this.finalizeIr()}convertServers({endpointLevelServers:t}){let n=new N4({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:n?.value}),{defaultUrl:n?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Hm.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();i!=null&&this.addSchemaOutputToIr(t,i)}}convertMethods(){let t=[],n=new LYr({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],o=[],s=[];if(n&&n.length>0)for(let[c,u]of n.entries()){let p=new UYr({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${c}]`],parameter:u}).convert();if(p!=null)switch(p.type){case"path":{i.push(p.parameter);break}case"query":{o.push(p.parameter);break}case"header":{s.push(p.parameter);break}}}let a=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let c of this.context.spec.methods??[]){let u=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:["methods"]});if(u==null)continue;let p=new _Yr({context:this.context,breadcrumbs:["methods"],method:u,pathParameters:i,queryParameters:o,headers:s,topLevelServers:this.context.spec.servers}).convert();if(p!=null&&(this.addEndpointToIr({endpoint:p.endpoint,audiences:p.audiences,endpointGroup:a,serviceName:"service_root"}),this.addTypesToIr(p.inlinedTypes),p.servers))for(let d of p.servers)this.shouldAddServerToCollectedServers({server:d,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(d))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(n=>n.name===t.name&&n.url!==t.url)?{...t,name:t.url}:t}}});var hWt,RGu=h(()=>{"use strict";Wn();rs();hWt=class extends S0{isReferenceObject(t){return t!=null&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.title;else if(i==="discriminator_key")a=s.value.title??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.title??c}return{ok:!0,reference:en.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var DGu=h(()=>{"use strict";BGu();RGu()});var kGu,FGu=h(()=>{"use strict";kGu=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function EFm(e){return typeof e=="string"&&kGu.test(e)}var gqo,NGu=h(()=>{"use strict";FGu();gqo=EFm});function jGu(e,t=0){return(XB[e[t+0]]+XB[e[t+1]]+XB[e[t+2]]+XB[e[t+3]]+"-"+XB[e[t+4]]+XB[e[t+5]]+"-"+XB[e[t+6]]+XB[e[t+7]]+"-"+XB[e[t+8]]+XB[e[t+9]]+"-"+XB[e[t+10]]+XB[e[t+11]]+XB[e[t+12]]+XB[e[t+13]]+XB[e[t+14]]+XB[e[t+15]]).toLowerCase()}var XB,zGu=h(()=>{"use strict";XB=[];for(let e=0;e<256;++e)XB.push((e+256).toString(16).slice(1))});function Aqo(){return crypto.getRandomValues(IFm)}var IFm,QGu=h(()=>{"use strict";IFm=new Uint8Array(16)});function vFm(e,t,r){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():CFm(e,t,r)}function CFm(e,t,r){e=e||{};let n=e.random??e.rng?.()??Aqo();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return jGu(n)}var Xw,MGu=h(()=>{"use strict";QGu();zGu();Xw=vFm});var xVe=h(()=>{"use strict";MGu();NGu()});async function blt({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:n}){let i=null;try{let o=(await(0,LGu.readFile)(e,"utf8")).toString();try{i=JSON.parse(o)}catch{i=Cr.load(o,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`,void 0,{code:T.Code.ParseError})}return $Z({data:t,overrides:i,allowNullKeys:n})}var LGu,VYr=h(()=>{"use strict";ct();Dt();LGu=require("fs/promises");cs()});async function yqo({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,_Gu.readFile)(t)).toString(),i;try{i=JSON.parse(n)}catch{i=Cr.load(n)}let o=[];r!=null&&(Array.isArray(r)?o=r:o=[r]);let s=i;for(let a of o)s=await blt({absoluteFilePathToOverrides:a,context:e,data:s});return s}var _Gu,UGu=h(()=>{"use strict";_Gu=require("fs/promises");cs();VYr()});async function bqo({document:e,settings:t}){let r=t?.errorResponses;if(r==null)return{document:e,errorResponses:void 0};let n=typeof r.schema=="string"?await xFm($t.of(r.schema)):r.schema;return{document:pSo({document:e,errorResponses:r,schema:n}),errorResponses:{...r,schema:n}}}async function xFm(e){let t=(await(0,VGu.readFile)(e)).toString(),r=Cr.load(t);if(!Fr(r))throw new T({message:`Expected ${e} to contain an OpenAPI schema object.`,code:T.Code.ConfigError});return r}var VGu,GGu=h(()=>{"use strict";kc();ct();tr();Dt();VGu=require("fs/promises");cs()});var WGu=E((yDv,qGu)=>{"use strict";function SFm(){return typeof process=="object"&&typeof process.nextTick=="function"?process.nextTick:typeof setImmediate=="function"?setImmediate:function(t){setTimeout(t,0)}}qGu.exports=SFm()});var JGu=E((bDv,KGu)=>{"use strict";var HGu=WGu();KGu.exports=function(t,r){if(t){r.then(function(n){HGu(function(){t(null,n)})},function(n){HGu(function(){t(n)})});return}else return r}});var Iqo=E((EDv,XGu)=>{"use strict";var Eqo=class{constructor(t,r){this.cb=t,this.delay=r,this.timers={},this.pausers={}}setDelay(t){t>=0&&(this.delay=t)}pause(t){this.pausers[t]=this.pausers[t]||0,this.pausers[t]++}unpause(t){var r=this.pausers[t]||0;r>0&&r--,this.pausers[t]=r}unpauseAndTime(t){this.unpause(t),this.time(t)}time(t){var r=this,n=this.timers,i=this.timers[t];this.pausers[t]>0||(i&&clearTimeout(i),n[t]=setTimeout(function(){r.cb(t),delete n[t]},r.delay))}},GYr=class extends TypeError{constructor(t,r,n){let i=t.includes(".")?"property":"argument",o=`The "${t}" ${i} ${determiner} ${r}`}};function YGu(e,t,r="Object"){if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e))){let n=new GYr(t,r,e);throw Error.captureStackTrace(n,YGu),n}}XGu.exports={ERR_INVALID_ARG_TYPE:GYr,assertIsObject:YGu,DebounceTimers:Eqo}});var equ=E((IDv,$Gu)=>{"use strict";var{assertIsObject:ZGu}=Iqo();function wFm(e){return ZGu(e,"options"),e=Object.assign({},e),e.allowHalfOpen=!0,e.rejectUnauthorized=!1,ZGu(e.settings,"options.settings"),e.settings=Object.assign({},e.settings),e.Http1IncomingMessage=e.Http1IncomingMessage||this.http.IncomingMessage,e.Http1ServerResponse=e.Http1ServerResponse||this.http.ServerResponse,e.Http2ServerRequest=e.Http2ServerRequest||(this.http2||{}).Http2ServerRequest,e.Http2ServerResponse=e.Http2ServerResponse||(this.http2||{}).Http2ServerResponse,e}function TFm(e,t){e=wFm.call(this,e);var r=e.ALPNProtocols=[];return this.http2Support&&r.push("h2"),(e.allowHTTP1==!0||!this.http2Support)&&r.push("http/1.1"),t!==void 0&&e.servername===void 0&&(e.servername=t),e}$Gu.exports={initializeTLSOptions:TFm}});var KYr=E((CDv,iqu)=>{"use strict";var{URL:qYr}=require("url"),{EventEmitter:rqu}=require("events"),WYr=require("util")._extend,{DebounceTimers:OFm,assertIsObject:tqu,ERR_INVALID_ARG_TYPE:vDv}=Iqo(),{initializeTLSOptions:PFm}=equ(),gWt=require("http"),vqo=require("https"),{Stream:BFm}=require("stream");function HYr(e,t){let r=t.prototype;Object.keys(r).forEach(n=>{e.indexOf(n)==-1&&n.indexOf("_")!=0&&typeof r[n]=="function"&&e.push(n)})}var Ehe=[];HYr(Ehe,gWt.ClientRequest);HYr(Ehe,gWt.OutgoingMessage);HYr(Ehe,rqu);HYr(Ehe,BFm);var RFm=["httpVersionMajor","httpVersionMinor","httpVersion"],DFm=["host","connection"],Awe=Symbol("stubs");function AWt(){this.http2Mimic=!0,this[Awe]=[];for(var e=0;e<Ehe.length;e++){let u=Ehe[e];AWt.prototype[u]||(this[u]=function(){return this.genericStubber(u,arguments)}.bind(this))}var t,r,n,i;let o=arguments[0]instanceof yWt;var s,a;if(o){let u=arguments[0];u.method&&(s=u.method),u.protocol&&(a=u.protocol)}if(o?i=arguments[0].args:i=arguments,i[2]!=null?(n=i[0],t=i[1],r=i[2]):i[1]==null?t=i[0]:(t=i[0],r=i[1]),r=r||function(){},typeof t=="string"){if(t=Cqo(new qYr(t)),!t.hostname)throw new Error("Unable to determine the domain name")}else n?t=WYr(Cqo(new qYr(n)),t):t=WYr({},t);a!=a&&(t.protocol=a),t.protocol=="https:"&&!t.port&&t.port!=0&&(t.port=443),!t.port&&t.port!=0&&(t.port=80),s?t.method=s:t.method||(t.method="GET"),t.method=t.method.toUpperCase(),(t.requestManager||this.getGlobalManager(t)).handleClientRequest(this,t,r)}AWt.prototype={getGlobalManager(e){return e.agent?e.agent.protocol=="https:"?bwe.globalManager:Ewe.globalManager:ywe.globalManager},genericStubber(e,t){return this[Awe]?(this[Awe].push([e,t]),!0):this[e](...arguments)},on(e,t){e=="response"&&(t.http2Safe||(e="http1.response",arguments[0]=e)),this._on?this._on(...arguments):this.genericStubber("on",arguments)},once(e,t){e=="response"&&(t.http2Safe||(e="http1.response")),this._once?this._once(...arguments):this.genericStubber("once",arguments)},emitError(e){if(this[Awe])this[Awe].forEach(([t,r])=>{(t==="on"||t==="once")&&r[0]==="error"&&r[1](e)});else return this.emit("error",e)},take(e){for(var t=0;t<Ehe.length;t++){let n=Ehe[t];e[n]&&(this[n]=e[n].bind(e))}this._on=e.on.bind(e),this._once=e.once.bind(e),this.proxyProps(e);for(let n=0;n<this[Awe].length;n++){var r=this[Awe][n];e[r[0]](...r[1])}this[Awe]=null},proxyProps(e){function t(){return e[this]}function r(c){e[this]=c}let n=["on","_on","_once","once","http2Mimic"].concat(Ehe),i=Object.keys(this),o=[].concat(RFm);i.forEach(function(u){n.indexOf(u)==-1&&o.indexOf(u)==-1&&o.push(u)});let s=Object.getOwnPropertyDescriptors(e);for(var a=0;a<o.length;a++){let c=o[a],u=s[c],l;u||(l=!0),u&&(u.writable||u)&&(l=!0),l&&(e[c]=this[c]),Object.defineProperty(this,c,{get:t.bind(c),set:r.bind(c)})}}};var ywe=class e extends rqu{constructor(t){super(),this.httpsAgent=vqo.globalAgent,this.httpAgent=gWt.globalAgent,this.init(t)}log(){}init(t){t=t||{},this.http2Clients={},this.cachedHTTP1Result={},this.setModules(),this.http2Debouncer=new OFm(function(n){this.log("stopping ",n);var i=this.http2Clients[n];i&&this.removeHttp2Client(n,i)}.bind(this),1e3),this.keepH1IdentificationCacheFor=t.keepH1IdentificationCacheFor||3e4,this.http2Debouncer.setDelay(t.keepH2ConnectionFor),t.useHttp?this.enforceProtocol="http:":t.useHttps&&(this.enforceProtocol="https:")}setModules(){this.http=require("http"),this.https=require("https"),this.tls=require("tls"),this.net=require("net"),this.http2Support=!1;try{this.http2=require("http2"),this.http2Support=!0}catch{}}handleClientRequest(t,r,n){let i=this,o=i.getClientKey(r);if(i.hasCachedConnection(o)){let s=i.getHttp2Client(o),a={createConnection(){return s}};process.nextTick(function(){i.makeRequest(t,o,r,n,a)}.bind(i))}else i.holdConnectionToIdentification(o,r,function(a,c){if(a){t.emitError(a);return}i.makeRequest(t,o,r,n,c)}.bind(i))}getClientKey(t){return`${t.protocol||this.enforceProtocol}${t.servername||t.host||t.hostname}:${t.port}`}getHttp2Client(t){return this.http2Clients[t]}setHttp2Client(t,r){let n=this,i=n.http2Clients[t];i&&n.removeHttp2Client(t,i),n.http2Clients[t]=r;function o(){n.removeHttp2Client(t,r)}r.on("close",o),r.on("goaway",o),r.on("error",o),r.on("frameError",o),r.on("timeout",o)}removeHttp2Client(t,r){try{delete this.http2Clients[t],r.closed||r.close()}catch{}r.removeAllListeners("close"),r.removeAllListeners("error"),r.removeAllListeners("frameError"),r.removeAllListeners("timeout")}request(t,r,n){var i=new yWt(arguments);return this.enforceProtocol&&(i.protocol=this.enforceProtocol),new AWt(i)}get(){var t=new yWt(arguments);t.method="GET";var r=this.request(t);return r.end(),r}hasCachedConnection(t){return this.getHttp2Client(t)?!0:this.cachedHTTP1Result[t]+this.keepH1IdentificationCacheFor<Date.now()}makeRequest(t,r,n,i,o){let s=this.getHttp2Client(r);return s?this.makeHttp2Request(r,t,s,Object.assign(o||{},n),i):(n.agent||(n.protocol=="https:"?n.agent=this.httpsAgent:n.agent=this.httpAgent),this.makeHttpRequest(r,t,n,i,o))}holdConnectionToIdentification(t,r,n){let i=`identify-${t}`;if(this._events[i])this.once(i,n);else{this.once(i,function(){});let o=this.identifyConnection(r,function(a,c){if(a)return n(a);var u={createConnection(){return o}};if(c=="h2"&&this.http2Support){var l=this.http2.connect(r,u);this.setHttp2Client(t,l)}else this.cachedHTTP1Result[t]=Date.now();n(null,u),this.emit(i,u)}.bind(this))}}makeHttpRequest(t,r,n,i,o){n instanceof qYr&&(n=Cqo(n));let s=WYr({},n);o&&(s.createConnection=o.createConnection);let c=(s.protocol=="https:"?this.https:this.http).request(s,i);r.take(c),r._on("response",function(l){this.emit("http1.response",l)})}makeHttp2Request(t,r,n,i,o){var s=this.http2Debouncer;s.pause(t);var a=WYr({},i.headers||{});i.method&&(a[":method"]=i.method),i.path&&(a[":path"]=i.path),Object.keys(a).forEach(d=>{DFm.indexOf((d+"").toLowerCase())!=-1&&delete a[d]}),i.headers=a;var c=n.request(a);r.emit("socket",i.createConnection());let u,l=0;c.on("data",function(f){l+=f.length,l>=u&&s.unpauseAndTime(t)}),r.take(c);function p(d){u=parseInt(d["content-length"]),u<0&&this.http2Debouncer.unpauseAndTime(t),e.httpCompatibleResponse(c,i,d),r.emit("http1.response",c),o&&o(c)}p.http2Safe=!0,c.once("response",p.bind(this))}static httpCompatibleResponse(t,r,n){t.httpVersion="2.0",t.rawHeaders=n,t.headers=n,t.statusCode=n[":status"],delete n[":status"]}identifyConnection(t,r){var n=this.connect(t,{allowHTTP1:!0},function(){n.removeListener("error",r),n.alpnProtocol=="h2"?r(null,"h2"):(n.end(),r(null,"h1"))});return n.on("error",r),n}connect(t,r,n){typeof r=="function"&&(n=r,r=void 0),tqu(r,"options"),r=Object.assign({},r),typeof t=="string"&&(t=new qYr(t)),tqu(t,"authority",["string","Object","URL"]);var i=t.protocol||r.protocol||(this.enforceProtocol!="detect"?this.enforceProtocol:null)||"http:",o=""+(t.port!==""?t.port:t.protocol==="http:"?80:443),s=t.hostname||t.host||"localhost",a;if(typeof r.createConnection=="function")a=r.createConnection(t,r);else switch(i){case"http:":a=this.net.connect(o,s,n);break;case"https:":a=this.tls.connect(o,s,PFm.call(this,r,s),n);break;default:throw new Error("Not supprted"+i)}return a}};function Cqo(e){var t={protocol:e.protocol,hostname:e.hostname,hash:e.hash,search:e.search,pathname:e.pathname,path:`${e.pathname}${e.search}`,href:e.href};return e.port!==""&&(t.port=Number(e.port)),(e.username||e.password)&&(t.auth=`${e.username}:${e.password}`),t}var yWt=class e{constructor(t){if(t[0]instanceof e)return t[0];this.args=t,this.method=null,this.protocol=null}},bwe=class extends ywe{constructor(){super(...arguments),this.Agent=vqo.Agent,this.globalAgent=vqo.globalAgent,this.enforceProtocol="https:"}},kFm=new bwe;bwe.globalManager=kFm;bwe.Manager=bwe;var Ewe=class extends ywe{constructor(){super(...arguments),this.Agent=gWt.Agent,this.globalAgent=gWt.globalAgent,this.enforceProtocol="http:"}},FFm=new Ewe;Ewe.globalManager=FFm;Ewe.Manager=Ewe;var nqu=new ywe;nqu.enforceProtocol="detect";ywe.globalManager=nqu;iqu.exports={HttpRequest:Ewe,HttpsRequest:bwe,HTTP2OutgoingMessage:AWt,ClientRequest:AWt,HttpRequestManager:ywe}});var squ=E((xDv,oqu)=>{"use strict";var{HttpRequest:NFm,ClientRequest:jFm}=KYr(),bWt=NFm.globalManager,zFm=bWt.request.bind(bWt),QFm=bWt.get.bind(bWt),MFm=Object.assign({},require("http"));oqu.exports=Object.assign(MFm,{ClientRequest:jFm,globalManager:bWt,request:zFm,get:QFm})});var cqu=E((SDv,aqu)=>{"use strict";var{HttpsRequest:LFm,ClientRequest:_Fm}=KYr(),EWt=LFm.globalManager,UFm=EWt.request.bind(EWt),VFm=EWt.get.bind(EWt),GFm=Object.assign({},require("https"));aqu.exports=Object.assign(GFm,{ClientRequest:_Fm,globalManager:EWt,request:UFm,get:VFm})});var lqu=E((wDv,uqu)=>{"use strict";var{HttpRequestManager:xqo,HTTP2OutgoingMessage:qFm,ClientRequest:WFm}=KYr(),HFm=squ(),KFm=cqu(),IWt=new xqo;xqo.globalManager=IWt;var JFm=IWt.request.bind(IWt),YFm=IWt.get.bind(IWt);uqu.exports={HTTP2OutgoingMessage:qFm,ClientRequest:WFm,globalManager:xqo.globalManager,request:JFm,get:YFm,http:HFm,https:KFm}});var kqo={};$(kqo,{FetchError:()=>rk,Headers:()=>F8,Request:()=>vwe,Response:()=>rne,default:()=>a2m});function rk(e,t,r){Error.call(this,e),this.message=e,this.type=t,r&&(this.code=this.errno=r.code),Error.captureStackTrace(this,this.constructor)}function nO(e){var t=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=r.size;let i=n===void 0?0:n;var o=r.timeout;let s=o===void 0?0:o;e==null?e=null:gqu(e)?e=Buffer.from(e.toString()):e instanceof TVe?e=e[wVe]:Buffer.isBuffer(e)||(Object.prototype.toString.call(e)==="[object ArrayBuffer]"?e=Buffer.from(e):ArrayBuffer.isView(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof DJ.default||(e=Buffer.from(String(e)))),this[vhe]={body:e,disturbed:!1,error:null},this.size=i,this.timeout=s,e instanceof DJ.default&&e.on("error",function(a){let c=a.name==="AbortError"?a:new rk(`Invalid response body while trying to fetch ${t.url}: ${a.message}`,"system",a);t[vhe].error=c})}function Elt(){var e=this;if(this[vhe].disturbed)return nO.Promise.reject(new TypeError(`body used already for: ${this.url}`));if(this[vhe].disturbed=!0,this[vhe].error)return nO.Promise.reject(this[vhe].error);if(this.body===null)return nO.Promise.resolve(Buffer.alloc(0));if(Buffer.isBuffer(this.body))return nO.Promise.resolve(this.body);if(!(this.body instanceof DJ.default))return nO.Promise.resolve(Buffer.alloc(0));let t=[],r=0,n=!1;return new nO.Promise(function(i,o){let s;e.timeout&&(s=setTimeout(function(){n=!0,o(new rk(`Response timeout while trying to fetch ${e.url} (over ${e.timeout}ms)`,"body-timeout"))},e.timeout)),e.body.on("error",function(a){a.name==="AbortError"?(n=!0,o(a)):o(new rk(`Invalid response body while trying to fetch ${e.url}: ${a.message}`,"system",a))}),e.body.on("data",function(a){if(!(n||a===null)){if(e.size&&r+a.length>e.size){n=!0,o(new rk(`content size at ${e.url} over limit: ${e.size}`,"max-size"));return}r+=a.length,t.push(a)}}),e.body.on("end",function(){if(!n){clearTimeout(s);try{i(Buffer.concat(t))}catch(a){o(new rk(`Could not create Buffer from response body for ${e.url}: ${a.message}`,"system",a))}}})})}function XFm(e,t){if(typeof Oqo!="function")throw new Error("The package `encoding` must be installed to use the textConverted() function");let r=t.get("content-type"),n="utf-8",i,o;return r&&(i=/charset=([^;]*)/i.exec(r)),o=e.slice(0,1024).toString(),!i&&o&&(i=/<meta.+?charset=(['"])(.+?)\1/i.exec(o)),!i&&o&&(i=/<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(o),i&&(i=/charset=(.*)/i.exec(i.pop()))),!i&&o&&(i=/<\?xml.+?encoding=(['"])(.+?)\1/i.exec(o)),i&&(n=i.pop(),(n==="gb2312"||n==="gbk")&&(n="gb18030")),Oqo(e,"UTF-8",n).toString()}function gqu(e){return typeof e!="object"||typeof e.append!="function"||typeof e.delete!="function"||typeof e.get!="function"||typeof e.getAll!="function"||typeof e.has!="function"||typeof e.set!="function"?!1:e.constructor.name==="URLSearchParams"||Object.prototype.toString.call(e)==="[object URLSearchParams]"||typeof e.sort=="function"}function Aqu(e){let t,r,n=e.body;if(e.bodyUsed)throw new Error("cannot clone body after it is used");return n instanceof DJ.default&&typeof n.getBoundary!="function"&&(t=new pqu,r=new pqu,n.pipe(t),n.pipe(r),e[vhe].body=t,n=r),n}function yqu(e){return e===null?null:typeof e=="string"?"text/plain;charset=UTF-8":gqu(e)?"application/x-www-form-urlencoded;charset=UTF-8":e instanceof TVe?e.type||null:Buffer.isBuffer(e)||Object.prototype.toString.call(e)==="[object ArrayBuffer]"||ArrayBuffer.isView(e)?null:typeof e.getBoundary=="function"?`multipart/form-data;boundary=${e.getBoundary()}`:e instanceof DJ.default?null:"text/plain;charset=UTF-8"}function bqu(e){let t=e.body;return t===null?0:Buffer.isBuffer(t)?t.length:t&&typeof t.getLengthSync=="function"&&(t._lengthRetrievers&&t._lengthRetrievers.length==0||t.hasKnownLength&&t.hasKnownLength())?t.getLengthSync():null}function ZFm(e,t){let r=t.body;r===null?e.end():Buffer.isBuffer(r)?(e.write(r),e.end()):r.pipe(e)}function vWt(e){if(e=`${e}`,Equ.test(e))throw new TypeError(`${e} is not a legal HTTP header name`)}function fqu(e){if(e=`${e}`,Pqo.test(e))throw new TypeError(`${e} is not a legal HTTP header value`)}function vlt(e,t){t=t.toLowerCase();for(let r in e)if(r.toLowerCase()===t)return r}function Bqo(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"key+value";return Object.keys(e[WC]).sort().map(t==="key"?function(n){return n.toLowerCase()}:t==="value"?function(n){return e[WC][n].join(", ")}:function(n){return[n.toLowerCase(),e[WC][n].join(", ")]})}function wqo(e,t){let r=Object.create(Dqo);return r[Rqo]={target:e,kind:t,index:0},r}function $Fm(e){let t=Object.assign({__proto__:null},e[WC]),r=vlt(e[WC],"Host");return r!==void 0&&(t[r]=t[r][0]),t}function e2m(e){let t=new F8;for(let r of Object.keys(e))if(!Equ.test(r))if(Array.isArray(e[r]))for(let n of e[r])Pqo.test(n)||(t[WC][r]===void 0?t[WC][r]=[n]:t[WC][r].push(n));else Pqo.test(e[r])||(t[WC][r]=[e[r]]);return t}function JYr(e){return typeof e=="object"&&typeof e[Ihe]=="object"}function i2m(e){let t=e&&typeof e=="object"&&Object.getPrototypeOf(e);return!!(t&&t.constructor.name==="AbortSignal")}function o2m(e){let t=e[Ihe].parsedURL,r=new F8(e[Ihe].headers);if(r.has("Accept")||r.set("Accept","*/*"),!t.protocol||!t.hostname)throw new TypeError("Only absolute URLs are supported");if(!/^https?:$/.test(t.protocol))throw new TypeError("Only HTTP(S) protocols are supported");if(e.signal&&e.body instanceof DJ.default.Readable&&!n2m)throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8");let n=null;if(e.body==null&&/^(POST|PUT)$/i.test(e.method)&&(n="0"),e.body!=null){let i=bqu(e);typeof i=="number"&&(n=String(i))}return n&&r.set("Content-Length",n),r.has("User-Agent")||r.set("User-Agent","node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"),e.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip,deflate"),!r.has("Connection")&&!e.agent&&r.set("Connection","close"),Object.assign({},t,{method:e.method,headers:$Fm(r),agent:e.agent})}function CWt(e){Error.call(this,e),this.type="aborted",this.message=e,Error.captureStackTrace(this,this.constructor)}function Iwe(e,t){if(!Iwe.Promise)throw new Error("native promise missing, set fetch.Promise to your favorite alternative");return nO.Promise=Iwe.Promise,new Iwe.Promise(function(r,n){let i=new vwe(e,t),o=o2m(i),s=hqu.default.request,a=i.signal,c=null,u=function(){let g=new CWt("The user aborted a request.");n(g),i.body&&i.body instanceof DJ.default.Readable&&i.body.destroy(g),!(!c||!c.body)&&c.body.emit("error",g)};if(a&&a.aborted){u();return}let l=function(){u(),f()},p=s(o),d;a&&a.addEventListener("abort",l);function f(){p.abort(),a&&a.removeEventListener("abort",l),clearTimeout(d)}i.timeout&&p.once("socket",function(m){d=setTimeout(function(){n(new rk(`network timeout at: ${i.url}`,"request-timeout")),f()},i.timeout)}),p.on("error",function(m){n(new rk(`request to ${i.url} failed, reason: ${m.message}`,"system",m)),f()}),p.on("response",function(m){clearTimeout(d);let g=e2m(m.headers);if(Iwe.isRedirect(m.statusCode)){let v=g.get("Location"),S=v===null?null:s2m(i.url,v);switch(i.redirect){case"error":n(new rk(`redirect mode is set to error: ${i.url}`,"no-redirect")),f();return;case"manual":if(S!==null)try{g.set("Location",S)}catch(R){n(R)}break;case"follow":if(S===null)break;if(i.counter>=i.follow){n(new rk(`maximum redirect reached at: ${i.url}`,"max-redirect")),f();return}let B={headers:new F8(i.headers),follow:i.follow,counter:i.counter+1,agent:i.agent,compress:i.compress,method:i.method,body:i.body,signal:i.signal};if(m.statusCode!==303&&i.body&&bqu(i)===null){n(new rk("Cannot follow redirect with body being a readable stream","unsupported-redirect")),f();return}(m.statusCode===303||(m.statusCode===301||m.statusCode===302)&&i.method==="POST")&&(B.method="GET",B.body=void 0,B.headers.delete("content-length")),r(Iwe(new vwe(S,B))),f();return}}m.once("end",function(){a&&a.removeEventListener("abort",l)});let A=m.pipe(new dqu),y={url:i.url,status:m.statusCode,statusText:m.statusMessage,headers:g,size:i.size,timeout:i.timeout},I=g.get("Content-Encoding");if(!i.compress||i.method==="HEAD"||I===null||m.statusCode===204||m.statusCode===304){c=new rne(A,y),r(c);return}let x={flush:Ilt.default.Z_SYNC_FLUSH,finishFlush:Ilt.default.Z_SYNC_FLUSH};if(I=="gzip"||I=="x-gzip"){A=A.pipe(Ilt.default.createGunzip(x)),c=new rne(A,y),r(c);return}if(I=="deflate"||I=="x-deflate"){m.pipe(new dqu).once("data",function(S){(S[0]&15)===8?A=A.pipe(Ilt.default.createInflate()):A=A.pipe(Ilt.default.createInflateRaw()),c=new rne(A,y),r(c)});return}c=new rne(A,y),r(c)}),ZFm(p,i)})}var DJ,mqu,YYr,hqu,Ilt,wVe,Sqo,TVe,Oqo,vhe,pqu,Equ,Pqo,WC,F8,Rqo,Dqo,SVe,t2m,rne,Ihe,Tqo,r2m,n2m,vwe,dqu,s2m,a2m,Fqo=h(()=>{"use strict";DJ=ye(require("stream"),1),mqu=ye(require("http"),1),YYr=ye(require("url"),1),hqu=ye(lqu(),1),Ilt=ye(require("zlib"),1),wVe=Symbol("buffer"),Sqo=Symbol("type"),TVe=class e{constructor(){this[Sqo]="";let t=arguments[0],r=arguments[1],n=[];if(t){let o=t,s=Number(o.length);for(let a=0;a<s;a++){let c=o[a],u;c instanceof Buffer?u=c:ArrayBuffer.isView(c)?u=Buffer.from(c.buffer,c.byteOffset,c.byteLength):c instanceof ArrayBuffer?u=Buffer.from(c):c instanceof e?u=c[wVe]:u=Buffer.from(typeof c=="string"?c:String(c)),n.push(u)}}this[wVe]=Buffer.concat(n);let i=r&&r.type!==void 0&&String(r.type).toLowerCase();i&&!/[^\u0020-\u007E]/.test(i)&&(this[Sqo]=i)}get size(){return this[wVe].length}get type(){return this[Sqo]}slice(){let t=this.size,r=arguments[0],n=arguments[1],i,o;r===void 0?i=0:r<0?i=Math.max(t+r,0):i=Math.min(r,t),n===void 0?o=t:n<0?o=Math.max(t+n,0):o=Math.min(n,t);let s=Math.max(o-i,0),c=this[wVe].slice(i,i+s),u=new e([],{type:arguments[2]});return u[wVe]=c,u}};Object.defineProperties(TVe.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(TVe.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});rk.prototype=Object.create(Error.prototype);rk.prototype.constructor=rk;rk.prototype.name="FetchError";try{Oqo=require("encoding").convert}catch{}vhe=Symbol("Body internals"),pqu=DJ.default.PassThrough;nO.prototype={get body(){return this[vhe].body},get bodyUsed(){return this[vhe].disturbed},arrayBuffer(){return Elt.call(this).then(function(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)})},blob(){let e=this.headers&&this.headers.get("content-type")||"";return Elt.call(this).then(function(t){return Object.assign(new TVe([],{type:e.toLowerCase()}),{[wVe]:t})})},json(){var e=this;return Elt.call(this).then(function(t){try{return JSON.parse(t.toString())}catch(r){return nO.Promise.reject(new rk(`invalid json response body at ${e.url} reason: ${r.message}`,"invalid-json"))}})},text(){return Elt.call(this).then(function(e){return e.toString()})},buffer(){return Elt.call(this)},textConverted(){var e=this;return Elt.call(this).then(function(t){return XFm(t,e.headers)})}};Object.defineProperties(nO.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});nO.mixIn=function(e){for(let t of Object.getOwnPropertyNames(nO.prototype))if(!(t in e)){let r=Object.getOwnPropertyDescriptor(nO.prototype,t);Object.defineProperty(e,t,r)}};nO.Promise=global.Promise;Equ=/[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/,Pqo=/[^\t\x20-\x7e\x80-\xff]/;WC=Symbol("map"),F8=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;if(this[WC]=Object.create(null),t instanceof e){let r=t.raw(),n=Object.keys(r);for(let i of n)for(let o of r[i])this.append(i,o);return}if(t!=null)if(typeof t=="object"){let r=t[Symbol.iterator];if(r!=null){if(typeof r!="function")throw new TypeError("Header pairs must be iterable");let n=[];for(let i of t){if(typeof i!="object"||typeof i[Symbol.iterator]!="function")throw new TypeError("Each header pair must be iterable");n.push(Array.from(i))}for(let i of n){if(i.length!==2)throw new TypeError("Each header pair must be a name/value tuple");this.append(i[0],i[1])}}else for(let n of Object.keys(t)){let i=t[n];this.append(n,i)}}else throw new TypeError("Provided initializer must be an object")}get(t){t=`${t}`,vWt(t);let r=vlt(this[WC],t);return r===void 0?null:this[WC][r].join(", ")}forEach(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=Bqo(this),i=0;for(;i<n.length;){var o=n[i];let s=o[0],a=o[1];t.call(r,a,s,this),n=Bqo(this),i++}}set(t,r){t=`${t}`,r=`${r}`,vWt(t),fqu(r);let n=vlt(this[WC],t);this[WC][n!==void 0?n:t]=[r]}append(t,r){t=`${t}`,r=`${r}`,vWt(t),fqu(r);let n=vlt(this[WC],t);n!==void 0?this[WC][n].push(r):this[WC][t]=[r]}has(t){return t=`${t}`,vWt(t),vlt(this[WC],t)!==void 0}delete(t){t=`${t}`,vWt(t);let r=vlt(this[WC],t);r!==void 0&&delete this[WC][r]}raw(){return this[WC]}keys(){return wqo(this,"key")}values(){return wqo(this,"value")}[Symbol.iterator](){return wqo(this,"key+value")}};F8.prototype.entries=F8.prototype[Symbol.iterator];Object.defineProperty(F8.prototype,Symbol.toStringTag,{value:"Headers",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(F8.prototype,{get:{enumerable:!0},forEach:{enumerable:!0},set:{enumerable:!0},append:{enumerable:!0},has:{enumerable:!0},delete:{enumerable:!0},keys:{enumerable:!0},values:{enumerable:!0},entries:{enumerable:!0}});Rqo=Symbol("internal");Dqo=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==Dqo)throw new TypeError("Value of `this` is not a HeadersIterator");var e=this[Rqo];let t=e.target,r=e.kind,n=e.index,i=Bqo(t,r),o=i.length;return n>=o?{value:void 0,done:!0}:(this[Rqo].index=n+1,{value:i[n],done:!1})}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));Object.defineProperty(Dqo,Symbol.toStringTag,{value:"HeadersIterator",writable:!1,enumerable:!1,configurable:!0});SVe=Symbol("Response internals"),t2m=mqu.default.STATUS_CODES,rne=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};nO.call(this,t,r);let n=r.status||200,i=new F8(r.headers);if(t!=null&&!i.has("Content-Type")){let o=yqu(t);o&&i.append("Content-Type",o)}this[SVe]={url:r.url,status:n,statusText:r.statusText||t2m[n],headers:i}}get url(){return this[SVe].url}get status(){return this[SVe].status}get ok(){return this[SVe].status>=200&&this[SVe].status<300}get statusText(){return this[SVe].statusText}get headers(){return this[SVe].headers}clone(){return new e(Aqu(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok})}};nO.mixIn(rne.prototype);Object.defineProperties(rne.prototype,{url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});Object.defineProperty(rne.prototype,Symbol.toStringTag,{value:"Response",writable:!1,enumerable:!1,configurable:!0});Ihe=Symbol("Request internals"),Tqo=YYr.default.parse,r2m=YYr.default.format,n2m="destroy"in DJ.default.Readable.prototype;vwe=class e{constructor(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;JYr(t)?n=Tqo(t.url):(t&&t.href?n=Tqo(t.href):n=Tqo(`${t}`),t={});let i=r.method||t.method||"GET";if(i=i.toUpperCase(),(r.body!=null||JYr(t)&&t.body!==null)&&(i==="GET"||i==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let o=r.body!=null?r.body:JYr(t)&&t.body!==null?Aqu(t):null;nO.call(this,o,{timeout:r.timeout||t.timeout||0,size:r.size||t.size||0});let s=new F8(r.headers||t.headers||{});if(o!=null&&!s.has("Content-Type")){let c=yqu(o);c&&s.append("Content-Type",c)}let a=JYr(t)?t.signal:null;if("signal"in r&&(a=r.signal),a!=null&&!i2m(a))throw new TypeError("Expected signal to be an instanceof AbortSignal");this[Ihe]={method:i,redirect:r.redirect||t.redirect||"follow",headers:s,parsedURL:n,signal:a},this.follow=r.follow!==void 0?r.follow:t.follow!==void 0?t.follow:20,this.compress=r.compress!==void 0?r.compress:t.compress!==void 0?t.compress:!0,this.counter=r.counter||t.counter||0,this.agent=r.agent||t.agent}get method(){return this[Ihe].method}get url(){return r2m(this[Ihe].parsedURL)}get headers(){return this[Ihe].headers}get redirect(){return this[Ihe].redirect}get signal(){return this[Ihe].signal}clone(){return new e(this)}};nO.mixIn(vwe.prototype);Object.defineProperty(vwe.prototype,Symbol.toStringTag,{value:"Request",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(vwe.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0}});CWt.prototype=Object.create(Error.prototype);CWt.prototype.constructor=CWt;CWt.prototype.name="AbortError";dqu=DJ.default.PassThrough,s2m=YYr.default.resolve;Iwe.isRedirect=function(e){return e===301||e===302||e===303||e===307||e===308};Iwe.Promise=global.Promise;a2m=Iwe});var PVe=E(IM=>{"use strict";var Che={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},xWt={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"},c2m="tag:yaml.org,2002:",u2m={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function Iqu(e){let t=[0],r=e.indexOf(`
|
|
539
|
+
`).reduce(nDm,Object.create(null)),nDm=(e,t)=>{let r=parseInt(t,10);if(r!==Buffer.byteLength(t)+1)return e;t=t.slice((r+" ").length);let n=t.split("="),i=n.shift();if(!i)return e;let o=i.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),s=n.join("=");return e[o]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(o)?new Date(Number(s)*1e3):/^[0-9]+$/.test(s)?+s:s,e},iDm=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Pf=iDm!=="win32"?e=>e:e=>e&&e.replaceAll(/\\/g,"/"),oDm=class extends AVe{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(e,t,r){switch(super({}),this.pause(),this.extended=t,this.globalExtended=r,this.header=e,this.remain=e.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=e.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!e.path)throw new Error("no path provided for tar.ReadEntry");this.path=Pf(e.path),this.mode=e.mode,this.mode&&(this.mode=this.mode&4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=this.remain,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=e.linkpath?Pf(e.linkpath):void 0,this.uname=e.uname,this.gname=e.gname,t&&this.#e(t),r&&this.#e(r,!0)}write(e){let t=e.length;if(t>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,n=this.blockRemain;return this.remain=Math.max(0,r-t),this.blockRemain=Math.max(0,n-t),this.ignore?!0:r>=t?super.write(e):super.write(e.subarray(0,r))}#e(e,t=!1){e.path&&(e.path=Pf(e.path)),e.linkpath&&(e.linkpath=Pf(e.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(e).filter(([r,n])=>!(n==null||r==="path"&&t))))}},UJr=(e,t,r,n={})=>{e.file&&(n.file=e.file),e.cwd&&(n.cwd=e.cwd),n.code=r instanceof Error&&r.code||t,n.tarCode=t,!e.strict&&n.recoverable!==!1?(r instanceof Error&&(n=Object.assign(r,n),r=r.message),e.emit("warn",t,r,n)):r instanceof Error?e.emit("error",Object.assign(r,n)):e.emit("error",Object.assign(new Error(`${t}: ${r}`),n))},sDm=1024*1024,$8o=Buffer.from([31,139]),eGo=Buffer.from([40,181,47,253]),aDm=Math.max($8o.length,eGo.length),D8=Symbol("state"),cVe=Symbol("writeEntry"),ghe=Symbol("readEntry"),M8o=Symbol("nextEntry"),RVu=Symbol("processEntry"),Zre=Symbol("extendedHeader"),Q9t=Symbol("globalExtendedHeader"),ZSe=Symbol("meta"),DVu=Symbol("emitMeta"),x0=Symbol("buffer"),Ahe=Symbol("queue"),$Se=Symbol("ended"),L8o=Symbol("emittedEnd"),uVe=Symbol("emit"),yS=Symbol("unzip"),hJr=Symbol("consumeChunk"),gJr=Symbol("consumeChunkSub"),_8o=Symbol("consumeBody"),kVu=Symbol("consumeMeta"),FVu=Symbol("consumeHeader"),M9t=Symbol("consuming"),U8o=Symbol("bufferConcat"),AJr=Symbol("maybeEnd"),Hut=Symbol("writing"),ewe=Symbol("aborted"),yJr=Symbol("onDone"),lVe=Symbol("sawValidEntry"),bJr=Symbol("sawNullBlock"),EJr=Symbol("sawEOF"),NVu=Symbol("closeStream"),cDm=()=>!0,eWt=class extends a5u.EventEmitter{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Ahe]=[];[x0];[ghe];[cVe];[D8]="begin";[ZSe]="";[Zre];[Q9t];[$Se]=!1;[yS];[ewe]=!1;[lVe];[bJr]=!1;[EJr]=!1;[Hut]=!1;[M9t]=!1;[L8o]=!1;constructor(e={}){super(),this.file=e.file||"",this.on(yJr,()=>{(this[D8]==="begin"||this[lVe]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),e.ondone?this.on(yJr,e.ondone):this.on(yJr,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||sDm,this.filter=typeof e.filter=="function"?e.filter:cDm;let t=e.file&&(e.file.endsWith(".tar.br")||e.file.endsWith(".tbr"));this.brotli=!(e.gzip||e.zstd)&&e.brotli!==void 0?e.brotli:t?void 0:!1;let r=e.file&&(e.file.endsWith(".tar.zst")||e.file.endsWith(".tzst"));this.zstd=!(e.gzip||e.brotli)&&e.zstd!==void 0?e.zstd:r?!0:void 0,this.on("end",()=>this[NVu]()),typeof e.onwarn=="function"&&this.on("warn",e.onwarn),typeof e.onReadEntry=="function"&&this.on("entry",e.onReadEntry)}warn(e,t,r={}){UJr(this,e,t,r)}[FVu](e,t){this[lVe]===void 0&&(this[lVe]=!1);let r;try{r=new gVe(e,t,this[Zre],this[Q9t])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[bJr]?(this[EJr]=!0,this[D8]==="begin"&&(this[D8]="header"),this[uVe]("eof")):(this[bJr]=!0,this[uVe]("nullBlock"));else if(this[bJr]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let n=r.type;if(/^(Symbolic)?Link$/.test(n)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(n)&&!/^(Global)?ExtendedHeader$/.test(n)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let i=this[cVe]=new oDm(r,this[Zre],this[Q9t]);if(!this[lVe])if(i.remain){let o=()=>{i.invalid||(this[lVe]=!0)};i.on("end",o)}else this[lVe]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[uVe]("ignoredEntry",i),this[D8]="ignore",i.resume()):i.size>0&&(this[ZSe]="",i.on("data",o=>this[ZSe]+=o),this[D8]="meta"):(this[Zre]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[uVe]("ignoredEntry",i),this[D8]=i.remain?"ignore":"header",i.resume()):(i.remain?this[D8]="body":(this[D8]="header",i.end()),this[ghe]?this[Ahe].push(i):(this[Ahe].push(i),this[M8o]())))}}}[NVu](){queueMicrotask(()=>this.emit("close"))}[RVu](e){let t=!0;if(!e)this[ghe]=void 0,t=!1;else if(Array.isArray(e)){let[r,...n]=e;this.emit(r,...n)}else this[ghe]=e,this.emit("entry",e),e.emittedEnd||(e.on("end",()=>this[M8o]()),t=!1);return t}[M8o](){do;while(this[RVu](this[Ahe].shift()));if(this[Ahe].length===0){let e=this[ghe];!e||e.flowing||e.size===e.remain?this[Hut]||this.emit("drain"):e.once("drain",()=>this.emit("drain"))}}[_8o](e,t){let r=this[cVe];if(!r)throw new Error("attempt to consume body without entry??");let n=r.blockRemain??0,i=n>=e.length&&t===0?e:e.subarray(t,t+n);return r.write(i),r.blockRemain||(this[D8]="header",this[cVe]=void 0,r.end()),i.length}[kVu](e,t){let r=this[cVe],n=this[_8o](e,t);return!this[cVe]&&r&&this[DVu](r),n}[uVe](e,t,r){this[Ahe].length===0&&!this[ghe]?this.emit(e,t,r):this[Ahe].push([e,t,r])}[DVu](e){switch(this[uVe]("meta",this[ZSe]),e.type){case"ExtendedHeader":case"OldExtendedHeader":this[Zre]=NJr.parse(this[ZSe],this[Zre],!1);break;case"GlobalExtendedHeader":this[Q9t]=NJr.parse(this[ZSe],this[Q9t],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let t=this[Zre]??Object.create(null);this[Zre]=t,t.path=this[ZSe].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let t=this[Zre]||Object.create(null);this[Zre]=t,t.linkpath=this[ZSe].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+e.type)}}abort(e){this[ewe]=!0,this.emit("abort",e),this.warn("TAR_ABORT",e,{recoverable:!1})}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this[ewe])return r?.(),!1;if((this[yS]===void 0||this.brotli===void 0&&this[yS]===!1)&&e){if(this[x0]&&(e=Buffer.concat([this[x0],e]),this[x0]=void 0),e.length<aDm)return this[x0]=e,r?.(),!0;for(let s=0;this[yS]===void 0&&s<$8o.length;s++)e[s]!==$8o[s]&&(this[yS]=!1);let i=!1;if(this[yS]===!1&&this.zstd!==!1){i=!0;for(let s=0;s<eGo.length;s++)if(e[s]!==eGo[s]){i=!1;break}}let o=this.brotli===void 0&&!i;if(this[yS]===!1&&o)if(e.length<512)if(this[$Se])this.brotli=!0;else return this[x0]=e,r?.(),!0;else try{new gVe(e.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[yS]===void 0||this[yS]===!1&&(this.brotli||i)){let s=this[$Se];this[$Se]=!1,this[yS]=this[yS]===void 0?new kRm({}):i?new zRm({}):new NRm({}),this[yS].on("data",c=>this[hJr](c)),this[yS].on("error",c=>this.abort(c)),this[yS].on("end",()=>{this[$Se]=!0,this[hJr]()}),this[Hut]=!0;let a=!!this[yS][s?"end":"write"](e);return this[Hut]=!1,r?.(),a}}this[Hut]=!0,this[yS]?this[yS].write(e):this[hJr](e),this[Hut]=!1;let n=this[Ahe].length>0?!1:this[ghe]?this[ghe].flowing:!0;return!n&&this[Ahe].length===0&&this[ghe]?.once("drain",()=>this.emit("drain")),r?.(),n}[U8o](e){e&&!this[ewe]&&(this[x0]=this[x0]?Buffer.concat([this[x0],e]):e)}[AJr](){if(this[$Se]&&!this[L8o]&&!this[ewe]&&!this[M9t]){this[L8o]=!0;let e=this[cVe];if(e&&e.blockRemain){let t=this[x0]?this[x0].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[x0]&&e.write(this[x0]),e.end()}this[uVe](yJr)}}[hJr](e){if(this[M9t]&&e)this[U8o](e);else if(!e&&!this[x0])this[AJr]();else if(e){if(this[M9t]=!0,this[x0]){this[U8o](e);let t=this[x0];this[x0]=void 0,this[gJr](t)}else this[gJr](e);for(;this[x0]&&this[x0]?.length>=512&&!this[ewe]&&!this[EJr];){let t=this[x0];this[x0]=void 0,this[gJr](t)}this[M9t]=!1}(!this[x0]||this[$Se])&&this[AJr]()}[gJr](e){let t=0,r=e.length;for(;t+512<=r&&!this[ewe]&&!this[EJr];)switch(this[D8]){case"begin":case"header":this[FVu](e,t),t+=512;break;case"ignore":case"body":t+=this[_8o](e,t);break;case"meta":t+=this[kVu](e,t);break;default:throw new Error("invalid state: "+this[D8])}t<r&&(this[x0]=this[x0]?Buffer.concat([e.subarray(t),this[x0]]):e.subarray(t))}end(e,t,r){return typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t)),r&&this.once("finish",r),this[ewe]||(this[yS]?(e&&this[yS].write(e),this[yS].end()):(this[$Se]=!0,(this.brotli===void 0||this.zstd===void 0)&&(e=e||Buffer.alloc(0)),e&&this.write(e),this[AJr]())),this}},K9t=e=>{let t=e.length-1,r=-1;for(;t>-1&&e.charAt(t)==="/";)r=t,t--;return r===-1?e:e.slice(0,r)},uDm=e=>{let t=e.onReadEntry;e.onReadEntry=t?r=>{t(r),r.resume()}:r=>r.resume()},A5u=(e,t)=>{let r=new Map(t.map(o=>[K9t(o),!0])),n=e.filter,i=(o,s="")=>{let a=s||(0,LJr.parse)(o).root||".",c;if(o===a)c=!1;else{let u=r.get(o);c=u!==void 0?u:i((0,LJr.dirname)(o),a)}return r.set(o,c),c};e.filter=n?(o,s)=>n(o,s)&&i(K9t(o)):o=>i(K9t(o))},lDm=e=>{let t=new eWt(e),r=e.file,n;try{n=dVe.default.openSync(r,"r");let i=dVe.default.fstatSync(n),o=e.maxReadSize||16*1024*1024;if(i.size<o){let s=Buffer.allocUnsafe(i.size),a=dVe.default.readSync(n,s,0,i.size,0);t.end(a===s.byteLength?s:s.subarray(0,a))}else{let s=0,a=Buffer.allocUnsafe(o);for(;s<i.size;){let c=dVe.default.readSync(n,a,0,o,s);if(c===0)break;s+=c,t.write(a.subarray(0,c))}t.end()}}finally{if(typeof n=="number")try{dVe.default.closeSync(n)}catch{}}},pDm=(e,t)=>{let r=new eWt(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("end",o),dVe.default.stat(i,(a,c)=>{if(a)s(a);else{let u=new EGo(i,{readSize:n,size:c.size});u.on("error",s),u.pipe(r)}})})},VJr=nWt(lDm,pDm,e=>new eWt(e),e=>new eWt(e),(e,t)=>{t?.length&&A5u(e,t),e.noResume||uDm(e)}),y5u=(e,t,r)=>(e&=4095,r&&(e=(e|384)&-19),t&&(e&256&&(e|=64),e&32&&(e|=8),e&4&&(e|=1)),e),{isAbsolute:fDm,parse:jVu}=b5u.win32,SGo=e=>{let t="",r=jVu(e);for(;fDm(e)||r.root;){let n=e.charAt(0)==="/"&&e.slice(0,4)!=="//?/"?"/":r.root;e=e.slice(n.length),t+=n,r=jVu(e)}return[t,e]},GJr=["|","<",">","?",":"],wGo=GJr.map(e=>String.fromCodePoint(61440+Number(e.codePointAt(0)))),dDm=new Map(GJr.map((e,t)=>[e,wGo[t]])),mDm=new Map(wGo.map((e,t)=>[e,GJr[t]])),zVu=e=>GJr.reduce((t,r)=>t.split(r).join(dDm.get(r)),e),hDm=e=>wGo.reduce((t,r)=>t.split(r).join(mDm.get(r)),e),E5u=(e,t)=>t?(e=Pf(e).replace(/^\.(\/|$)/,""),K9t(t)+"/"+e):Pf(e),gDm=16*1024*1024,QVu=Symbol("process"),MVu=Symbol("file"),LVu=Symbol("directory"),rGo=Symbol("symlink"),_Vu=Symbol("hardlink"),L9t=Symbol("header"),wJr=Symbol("read"),nGo=Symbol("lstat"),TJr=Symbol("onlstat"),iGo=Symbol("onread"),oGo=Symbol("onreadlink"),sGo=Symbol("openfile"),aGo=Symbol("onopenfile"),owe=Symbol("close"),jJr=Symbol("mode"),cGo=Symbol("awaitDrain"),V8o=Symbol("ondrain"),$re=Symbol("prefix"),I5u=class extends AVe{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(e,t={}){let r=vGo(t);super(),this.path=Pf(e),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||gDm,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Pf(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Pf(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let n=!1;if(!this.preservePaths){let[o,s]=SGo(this.path);o&&typeof s=="string"&&(this.path=s,n=o)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=hDm(this.path.replaceAll(/\\/g,"/")),e=e.replaceAll(/\\/g,"/")),this.absolute=Pf(r.absolute||tGo.default.resolve(this.cwd,e)),this.path===""&&(this.path="./"),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path});let i=this.statCache.get(this.absolute);i?this[TJr](i):this[nGo]()}warn(e,t,r={}){return UJr(this,e,t,r)}emit(e,...t){return e==="error"&&(this.#e=!0),super.emit(e,...t)}[nGo](){wJ.default.lstat(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[TJr](t)})}[TJr](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=bDm(e),this.emit("stat",e),this[QVu]()}[QVu](){switch(this.type){case"File":return this[MVu]();case"Directory":return this[LVu]();case"SymbolicLink":return this[rGo]();default:return this.end()}}[jJr](e){return y5u(e,this.type==="Directory",this.portable)}[$re](e){return E5u(e,this.prefix)}[L9t](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new gVe({path:this[$re](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[$re](this.linkpath):this.linkpath,mode:this[jJr](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new NJr({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[$re](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[$re](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let e=this.header?.block;if(!e)throw new Error("failed to encode header");super.write(e)}[LVu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[L9t](),this.end()}[rGo](){wJ.default.readlink(this.absolute,(e,t)=>{if(e)return this.emit("error",e);this[oGo](t)})}[oGo](e){this.linkpath=Pf(e),this[L9t](),this.end()}[_Vu](e){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Pf(tGo.default.relative(this.cwd,e)),this.stat.size=0,this[L9t](),this.end()}[MVu](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let e=`${this.stat.dev}:${this.stat.ino}`,t=this.linkCache.get(e);if(t?.indexOf(this.cwd)===0)return this[_Vu](t);this.linkCache.set(e,this.absolute)}if(this[L9t](),this.stat.size===0)return this.end();this[sGo]()}[sGo](){wJ.default.open(this.absolute,"r",(e,t)=>{if(e)return this.emit("error",e);this[aGo](t)})}[aGo](e){if(this.fd=e,this.#e)return this[owe]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let t=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(t),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[wJr]()}[wJr](){let{fd:e,buf:t,offset:r,length:n,pos:i}=this;if(e===void 0||t===void 0)throw new Error("cannot read file without first opening");wJ.default.read(e,t,r,n,i,(o,s)=>{if(o)return this[owe](()=>this.emit("error",o));this[iGo](s)})}[owe](e=()=>{}){this.fd!==void 0&&wJ.default.close(this.fd,e)}[iGo](e){if(e<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[owe](()=>this.emit("error",r))}if(e>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[owe](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(e===this.remain)for(let r=e;r<this.length&&e<this.blockRemain;r++)this.buf[r+this.offset]=0,e++,this.remain++;let t=this.offset===0&&e===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+e);this.write(t)?this[V8o]():this[cGo](()=>this[V8o]())}[cGo](e){this.once("drain",e)}write(e,t,r){if(typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8")),this.blockRemain<e.length){let n=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",n)}return this.remain-=e.length,this.blockRemain-=e.length,this.pos+=e.length,this.offset+=e.length,super.write(e,null,r)}[V8o](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[owe](e=>e?this.emit("error",e):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[wJr]()}},ADm=class extends I5u{sync=!0;[nGo](){this[TJr](wJ.default.lstatSync(this.absolute))}[rGo](){this[oGo](wJ.default.readlinkSync(this.absolute))}[sGo](){this[aGo](wJ.default.openSync(this.absolute,"r"))}[wJr](){let e=!0;try{let{fd:t,buf:r,offset:n,length:i,pos:o}=this;if(t===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let s=wJ.default.readSync(t,r,n,i,o);this[iGo](s),e=!1}finally{if(e)try{this[owe](()=>{})}catch{}}}[cGo](e){e()}[owe](e=()=>{}){this.fd!==void 0&&wJ.default.closeSync(this.fd),e()}},yDm=class extends AVe{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(e,t,r={}){return UJr(this,e,t,r)}constructor(e,t={}){let r=vGo(t);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=e;let{type:n}=e;if(n==="Unsupported")throw new Error("writing entry that should be ignored");this.type=n,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=Pf(e.path),this.mode=e.mode!==void 0?this[jJr](e.mode):void 0,this.uid=this.portable?void 0:e.uid,this.gid=this.portable?void 0:e.gid,this.uname=this.portable?void 0:e.uname,this.gname=this.portable?void 0:e.gname,this.size=e.size,this.mtime=this.noMtime?void 0:r.mtime||e.mtime,this.atime=this.portable?void 0:e.atime,this.ctime=this.portable?void 0:e.ctime,this.linkpath=e.linkpath!==void 0?Pf(e.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[s,a]=SGo(this.path);s&&typeof a=="string"&&(this.path=a,i=s)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.onWriteEntry?.(this),this.header=new gVe({path:this[$re](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[$re](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.header.encode()&&!this.noPax&&super.write(new NJr({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[$re](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[$re](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),e.pipe(this)}[$re](e){return E5u(e,this.prefix)}[jJr](e){return y5u(e,this.type==="Directory",this.portable)}write(e,t,r){typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,typeof t=="string"?t:"utf8"));let n=e.length;if(n>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=n,super.write(e,r)}end(e,t,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof e=="function"&&(r=e,t=void 0,e=void 0),typeof t=="function"&&(r=t,t=void 0),typeof e=="string"&&(e=Buffer.from(e,t??"utf8")),r&&this.once("finish",r),e?super.end(e,r):super.end(r),this}},bDm=e=>e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":"Unsupported",EDm=class $ut{tail;head;length=0;static create(t=[]){return new $ut(t)}constructor(t=[]){for(let r of t)this.push(r)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw new Error("removing node which does not belong to this list");let r=t.next,n=t.prev;return r&&(r.prev=n),n&&(n.next=r),t===this.head&&(this.head=r),t===this.tail&&(this.tail=n),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,r}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let r=this.head;t.list=this,t.next=r,r&&(r.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let r=this.tail;t.list=this,t.prev=r,r&&(r.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let r=0,n=t.length;r<n;r++)vDm(this,t[r]);return this.length}unshift(...t){for(var r=0,n=t.length;r<n;r++)CDm(this,t[r]);return this.length}pop(){if(!this.tail)return;let t=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,t}shift(){if(!this.head)return;let t=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,t}forEach(t,r){r=r||this;for(let n=this.head,i=0;n;i++)t.call(r,n.value,i,this),n=n.next}forEachReverse(t,r){r=r||this;for(let n=this.tail,i=this.length-1;n;i--)t.call(r,n.value,i,this),n=n.prev}get(t){let r=0,n=this.head;for(;n&&r<t;r++)n=n.next;if(r===t&&n)return n.value}getReverse(t){let r=0,n=this.tail;for(;n&&r<t;r++)n=n.prev;if(r===t&&n)return n.value}map(t,r){r=r||this;let n=new $ut;for(let i=this.head;i;)n.push(t.call(r,i.value,this)),i=i.next;return n}mapReverse(t,r){r=r||this;var n=new $ut;for(let i=this.tail;i;)n.push(t.call(r,i.value,this)),i=i.prev;return n}reduce(t,r){let n,i=this.head;if(arguments.length>1)n=r;else if(this.head)i=this.head.next,n=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var o=0;i;o++)n=t(n,i.value,o),i=i.next;return n}reduceReverse(t,r){let n,i=this.tail;if(arguments.length>1)n=r;else if(this.tail)i=this.tail.prev,n=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let o=this.length-1;i;o--)n=t(n,i.value,o),i=i.prev;return n}toArray(){let t=new Array(this.length);for(let r=0,n=this.head;n;r++)t[r]=n.value,n=n.next;return t}toArrayReverse(){let t=new Array(this.length);for(let r=0,n=this.tail;n;r++)t[r]=n.value,n=n.prev;return t}slice(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let n=new $ut;if(r<t||r<0)return n;t<0&&(t=0),r>this.length&&(r=this.length);let i=this.head,o=0;for(o=0;i&&o<t;o++)i=i.next;for(;i&&o<r;o++,i=i.next)n.push(i.value);return n}sliceReverse(t=0,r=this.length){r<0&&(r+=this.length),t<0&&(t+=this.length);let n=new $ut;if(r<t||r<0)return n;t<0&&(t=0),r>this.length&&(r=this.length);let i=this.length,o=this.tail;for(;o&&i>r;i--)o=o.prev;for(;o&&i>t;i--,o=o.prev)n.push(o.value);return n}splice(t,r=0,...n){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let i=this.head;for(let s=0;i&&s<t;s++)i=i.next;let o=[];for(let s=0;i&&s<r;s++)o.push(i.value),i=this.removeNode(i);i?i!==this.tail&&(i=i.prev):i=this.tail;for(let s of n)i=IDm(this,i,s);return o}reverse(){let t=this.head,r=this.tail;for(let n=t;n;n=n.prev){let i=n.prev;n.prev=n.next,n.next=i}return this.head=r,this.tail=t,this}};TGo=class{list;next;prev;value;constructor(e,t,r,n){this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},UVu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(e,t){this.path=e||"./",this.absolute=t}},VVu=Buffer.alloc(1024),OJr=Symbol("onStat"),_9t=Symbol("ended"),xJ=Symbol("queue"),U9t=Symbol("pendingLinks"),twe=Symbol("current"),pVe=Symbol("process"),V9t=Symbol("processing"),IJr=Symbol("processJob"),SJ=Symbol("jobs"),G8o=Symbol("jobDone"),PJr=Symbol("addFSEntry"),GVu=Symbol("addTarEntry"),lGo=Symbol("stat"),pGo=Symbol("readdir"),BJr=Symbol("onreaddir"),RJr=Symbol("pipe"),qVu=Symbol("entry"),q8o=Symbol("entryOpt"),DJr=Symbol("writeEntryClass"),v5u=Symbol("write"),W8o=Symbol("ondrain"),qJr=class extends AVe{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[DJr];onWriteEntry;[xJ];[U9t]=new Map;[SJ]=0;[V9t]=!1;[_9t]=!1;constructor(e={}){if(super(),this.opt=e,this.file=e.file||"",this.cwd=e.cwd||process.cwd(),this.maxReadSize=e.maxReadSize,this.preservePaths=!!e.preservePaths,this.strict=!!e.strict,this.noPax=!!e.noPax,this.prefix=Pf(e.prefix||""),this.linkCache=e.linkCache||new Map,this.statCache=e.statCache||new Map,this.readdirCache=e.readdirCache||new Map,this.onWriteEntry=e.onWriteEntry,this[DJr]=I5u,typeof e.onwarn=="function"&&this.on("warn",e.onwarn),this.portable=!!e.portable,e.gzip||e.brotli||e.zstd){if((e.gzip?1:0)+(e.brotli?1:0)+(e.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(e.gzip&&(typeof e.gzip!="object"&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new DRm(e.gzip)),e.brotli&&(typeof e.brotli!="object"&&(e.brotli={}),this.zip=new FRm(e.brotli)),e.zstd&&(typeof e.zstd!="object"&&(e.zstd={}),this.zip=new jRm(e.zstd)),!this.zip)throw new Error("impossible");let t=this.zip;t.on("data",r=>super.write(r)),t.on("end",()=>super.end()),t.on("drain",()=>this[W8o]()),this.on("resume",()=>t.resume())}else this.on("drain",this[W8o]);this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,e.mtime&&(this.mtime=e.mtime),this.filter=typeof e.filter=="function"?e.filter:()=>!0,this[xJ]=new EDm,this[SJ]=0,this.jobs=Number(e.jobs)||4,this[V9t]=!1,this[_9t]=!1}[v5u](e){return super.write(e)}add(e){return this.write(e),this}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t=void 0),e&&this.add(e),this[_9t]=!0,this[pVe](),r&&r(),this}write(e){if(this[_9t])throw new Error("write after end");return typeof e=="string"?this[PJr](e):this[GVu](e),this.flowing}[GVu](e){let t=Pf(uGo.default.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new UVu(e.path,t);r.entry=new yDm(e,this[q8o](r)),r.entry.on("end",()=>this[G8o](r)),this[SJ]+=1,this[xJ].push(r)}this[pVe]()}[PJr](e){let t=Pf(uGo.default.resolve(this.cwd,e));this[xJ].push(new UVu(e,t)),this[pVe]()}[lGo](e){e.pending=!0,this[SJ]+=1;let t=this.follow?"stat":"lstat";tWt.default[t](e.absolute,(r,n)=>{e.pending=!1,this[SJ]-=1,r?this.emit("error",r):this[OJr](e,n)})}[OJr](e,t){if(this.statCache.set(e.absolute,t),e.stat=t,!this.filter(e.path,t))e.ignore=!0;else if(t.isFile()&&t.nlink>1&&!this.linkCache.get(`${t.dev}:${t.ino}`)&&!this.sync)if(e===this[twe])this[IJr](e);else{let r=`${t.dev}:${t.ino}`,n=this[U9t].get(r);n?n.push(e):this[U9t].set(r,[e]),e.pendingLink=!0,e.pending=!0}this[pVe]()}[pGo](e){e.pending=!0,this[SJ]+=1,tWt.default.readdir(e.absolute,(t,r)=>{if(e.pending=!1,this[SJ]-=1,t)return this.emit("error",t);this[BJr](e,r)})}[BJr](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[pVe]()}[pVe](){if(!this[V9t]){this[V9t]=!0;for(let e=this[xJ].head;e&&this[SJ]<this.jobs;e=e.next)if(this[IJr](e.value),e.value.ignore){let t=e.next;this[xJ].removeNode(e),e.next=t}this[V9t]=!1,this[_9t]&&this[xJ].length===0&&this[SJ]===0&&(this.zip?this.zip.end(VVu):(super.write(VVu),super.end()))}}get[twe](){return this[xJ]&&this[xJ].head&&this[xJ].head.value}[G8o](e){this[xJ].shift(),this[SJ]-=1;let{stat:t}=e;if(t&&t.isFile()&&t.nlink>1){let r=`${t.dev}:${t.ino}`,n=this[U9t].get(r);if(n){this[U9t].delete(r);for(let i of n)i.pending=!1,this[IJr](i)}}this[pVe]()}[IJr](e){if(e.pending&&e.pendingLink&&e===this[twe]&&(e.pending=!1,e.pendingLink=!1),!e.pending){if(e.entry){e===this[twe]&&!e.piped&&this[RJr](e);return}if(!e.stat){let t=this.statCache.get(e.absolute);t?this[OJr](e,t):this[lGo](e)}if(e.stat&&!e.ignore){if(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir){let t=this.readdirCache.get(e.absolute);if(t?this[BJr](e,t):this[pGo](e),!e.readdir)return}if(e.entry=this[qVu](e),!e.entry){e.ignore=!0;return}e===this[twe]&&!e.piped&&this[RJr](e)}}}[q8o](e){return{onwarn:(t,r,n)=>this.warn(t,r,n),noPax:this.noPax,cwd:this.cwd,absolute:e.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[qVu](e){this[SJ]+=1;try{return new this[DJr](e.path,this[q8o](e)).on("end",()=>this[G8o](e)).on("error",t=>this.emit("error",t))}catch(t){this.emit("error",t)}}[W8o](){this[twe]&&this[twe].entry&&this[twe].entry.resume()}[RJr](e){e.piped=!0,e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[PJr](o+n)});let t=e.entry,r=this.zip;if(!t)throw new Error("cannot pipe without source");r?t.on("data",n=>{r.write(n)||t.pause()}):t.on("data",n=>{super.write(n)||t.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(e,t,r={}){UJr(this,e,t,r)}},OGo=class extends qJr{sync=!0;constructor(e){super(e),this[DJr]=ADm}pause(){}resume(){}[lGo](e){let t=this.follow?"statSync":"lstatSync";this[OJr](e,tWt.default[t](e.absolute))}[pGo](e){this[BJr](e,tWt.default.readdirSync(e.absolute))}[RJr](e){let t=e.entry,r=this.zip;if(e.readdir&&e.readdir.forEach(n=>{let i=e.path,o=i==="./"?"":i.replace(/\/*$/,"/");this[PJr](o+n)}),!t)throw new Error("Cannot pipe without source");r?t.on("data",n=>{r.write(n)}):t.on("data",n=>{super[v5u](n)})}},xDm=(e,t)=>{let r=new OGo(e),n=new s5u(e.file,{mode:e.mode||438});r.pipe(n),C5u(r,t)},SDm=(e,t)=>{let r=new qJr(e),n=new MJr(e.file,{mode:e.mode||438});r.pipe(n);let i=new Promise((o,s)=>{n.on("error",s),n.on("close",o),r.on("error",s)});return x5u(r,t).catch(o=>r.emit("error",o)),i},C5u=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?VJr({file:IGo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},x5u=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await VJr({file:IGo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>{e.add(n)}}):e.add(r);e.end()},wDm=(e,t)=>{let r=new OGo(e);return C5u(r,t),r},TDm=(e,t)=>{let r=new qJr(e);return x5u(r,t).catch(n=>r.emit("error",n)),r},WJr=nWt(xDm,SDm,wDm,TDm,(e,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")}),ODm=process.env.__FAKE_PLATFORM__||process.platform,w5u=ODm==="win32",{O_CREAT:T5u,O_NOFOLLOW:WVu,O_TRUNC:O5u,O_WRONLY:P5u}=RGo.default.constants,B5u=Number(process.env.__FAKE_FS_O_FILENAME__)||RGo.default.constants.UV_FS_O_FILEMAP||0,PDm=w5u&&!!B5u,BDm=512*1024,RDm=B5u|O5u|T5u|P5u,HVu=!w5u&&typeof WVu=="number"?WVu|O5u|T5u|P5u:null,R5u=HVu!==null?()=>HVu:PDm?e=>e<BDm?RDm:"w":()=>"w",fGo=(e,t,r)=>{try{return iWt.default.lchownSync(e,t,r)}catch(n){if(n?.code!=="ENOENT")throw n}},zJr=(e,t,r,n)=>{iWt.default.lchown(e,t,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},DDm=(e,t,r,n,i)=>{if(t.isDirectory())D5u(tlt.default.resolve(e,t.name),r,n,o=>{if(o)return i(o);let s=tlt.default.resolve(e,t.name);zJr(s,r,n,i)});else{let o=tlt.default.resolve(e,t.name);zJr(o,r,n,i)}},D5u=(e,t,r,n)=>{iWt.default.readdir(e,{withFileTypes:!0},(i,o)=>{if(i){if(i.code==="ENOENT")return n();if(i.code!=="ENOTDIR"&&i.code!=="ENOTSUP")return n(i)}if(i||!o.length)return zJr(e,t,r,n);let s=o.length,a=null,c=u=>{if(!a){if(u)return n(a=u);if(--s===0)return zJr(e,t,r,n)}};for(let u of o)DDm(e,u,t,r,c)})},kDm=(e,t,r,n)=>{t.isDirectory()&&k5u(tlt.default.resolve(e,t.name),r,n),fGo(tlt.default.resolve(e,t.name),r,n)},k5u=(e,t,r)=>{let n;try{n=iWt.default.readdirSync(e,{withFileTypes:!0})}catch(i){let o=i;if(o?.code==="ENOENT")return;if(o?.code==="ENOTDIR"||o?.code==="ENOTSUP")return fGo(e,t,r);throw o}for(let i of n)kDm(e,i,t,r);return fGo(e,t,r)},N5u=class extends Error{path;code;syscall="chdir";constructor(e,t){super(`${t}: Cannot cd into '${e}'`),this.path=e,this.code=t}get name(){return"CwdError"}},HJr=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(e,t){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=e,this.path=t}get name(){return"SymlinkError"}},FDm=(e,t)=>{EM.default.stat(e,(r,n)=>{(r||!n.isDirectory())&&(r=new N5u(e,r?.code||"ENOTDIR")),t(r)})},NDm=(e,t,r)=>{e=Pf(e);let n=t.umask??18,i=t.mode|448,o=(i&n)!==0,s=t.uid,a=t.gid,c=typeof s=="number"&&typeof a=="number"&&(s!==t.processUid||a!==t.processGid),u=t.preserve,l=t.unlink,p=Pf(t.cwd),d=(m,g)=>{m?r(m):g&&c?D5u(g,s,a,A=>d(A)):o?EM.default.chmod(e,i,r):r()};if(e===p)return FDm(e,d);if(u)return F5u.default.mkdir(e,{mode:i,recursive:!0}).then(m=>d(null,m??void 0),d);let f=Pf(rWt.default.relative(p,e)).split("/");dGo(p,f,i,l,p,void 0,d)},dGo=(e,t,r,n,i,o,s)=>{if(t.length===0)return s(null,o);let a=t.shift(),c=Pf(rWt.default.resolve(e+"/"+a));EM.default.mkdir(c,r,j5u(c,t,r,n,i,o,s))},j5u=(e,t,r,n,i,o,s)=>a=>{a?EM.default.lstat(e,(c,u)=>{if(c)c.path=c.path&&Pf(c.path),s(c);else if(u.isDirectory())dGo(e,t,r,n,i,o,s);else if(n)EM.default.unlink(e,l=>{if(l)return s(l);EM.default.mkdir(e,r,j5u(e,t,r,n,i,o,s))});else{if(u.isSymbolicLink())return s(new HJr(e,e+"/"+t.join("/")));s(a)}}):(o=o||e,dGo(e,t,r,n,i,o,s))},jDm=e=>{let t=!1,r;try{t=EM.default.statSync(e).isDirectory()}catch(n){r=n?.code}finally{if(!t)throw new N5u(e,r??"ENOTDIR")}},zDm=(e,t)=>{e=Pf(e);let r=t.umask??18,n=t.mode|448,i=(n&r)!==0,o=t.uid,s=t.gid,a=typeof o=="number"&&typeof s=="number"&&(o!==t.processUid||s!==t.processGid),c=t.preserve,u=t.unlink,l=Pf(t.cwd),p=m=>{m&&a&&k5u(m,o,s),i&&EM.default.chmodSync(e,n)};if(e===l)return jDm(l),p();if(c)return p(EM.default.mkdirSync(e,{mode:n,recursive:!0})??void 0);let d=Pf(rWt.default.relative(l,e)).split("/"),f;for(let m=d.shift(),g=l;m&&(g+="/"+m);m=d.shift()){g=Pf(rWt.default.resolve(g));try{EM.default.mkdirSync(g,n),f=f||g}catch{let A=EM.default.lstatSync(g);if(A.isDirectory())continue;if(u){EM.default.unlinkSync(g),EM.default.mkdirSync(g,n),f=f||g;continue}else if(A.isSymbolicLink())return new HJr(g,g+"/"+d.join("/"))}}return p(f)},H8o=Object.create(null),KVu=1e4,Kut=new Set,QDm=e=>{Kut.has(e)?Kut.delete(e):H8o[e]=e.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Kut.add(e);let t=H8o[e],r=Kut.size-KVu;if(r>KVu/10){for(let n of Kut)if(Kut.delete(n),delete H8o[n],--r<=0)break}return t},MDm=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,LDm=MDm==="win32",_Dm=e=>e.split("/").slice(0,-1).reduce((t,r)=>{let n=t.at(-1);return n!==void 0&&(r=(0,DGo.join)(n,r)),t.push(r||"/"),t},[]),UDm=class{#e=new Map;#t=new Map;#r=new Set;reserve(e,t){e=LDm?["win32 parallelization disabled"]:e.map(n=>K9t((0,DGo.join)(QDm(n))));let r=new Set(e.map(n=>_Dm(n)).reduce((n,i)=>n.concat(i)));this.#t.set(t,{dirs:r,paths:e});for(let n of e){let i=this.#e.get(n);i?i.push(t):this.#e.set(n,[t])}for(let n of r){let i=this.#e.get(n);if(!i)this.#e.set(n,[new Set([t])]);else{let o=i.at(-1);o instanceof Set?o.add(t):i.push(new Set([t]))}}return this.#i(t)}#n(e){let t=this.#t.get(e);if(!t)throw new Error("function does not have any path reservations");return{paths:t.paths.map(r=>this.#e.get(r)),dirs:[...t.dirs].map(r=>this.#e.get(r))}}check(e){let{paths:t,dirs:r}=this.#n(e);return t.every(n=>n&&n[0]===e)&&r.every(n=>n&&n[0]instanceof Set&&n[0].has(e))}#i(e){return this.#r.has(e)||!this.check(e)?!1:(this.#r.add(e),e(()=>this.#o(e)),!0)}#o(e){if(!this.#r.has(e))return!1;let t=this.#t.get(e);if(!t)throw new Error("invalid reservation");let{paths:r,dirs:n}=t,i=new Set;for(let o of r){let s=this.#e.get(o);if(!s||s?.[0]!==e)continue;let a=s[1];if(!a){this.#e.delete(o);continue}if(s.shift(),typeof a=="function")i.add(a);else for(let c of a)i.add(c)}for(let o of n){let s=this.#e.get(o),a=s?.[0];if(!(!s||!(a instanceof Set)))if(a.size===1&&s.length===1){this.#e.delete(o);continue}else if(a.size===1){s.shift();let c=s[0];typeof c=="function"&&i.add(c)}else a.delete(e)}return this.#r.delete(e),i.forEach(o=>this.#i(o)),!0}},VDm=()=>process.umask(),JVu=Symbol("onEntry"),mGo=Symbol("checkFs"),YVu=Symbol("checkFs2"),hGo=Symbol("isReusable"),k8=Symbol("makeFs"),gGo=Symbol("file"),AGo=Symbol("directory"),kJr=Symbol("link"),XVu=Symbol("symlink"),ZVu=Symbol("hardlink"),W9t=Symbol("ensureNoSymlink"),$Vu=Symbol("unsupported"),e5u=Symbol("checkPath"),K8o=Symbol("stripAbsolutePath"),awe=Symbol("mkdir"),tO=Symbol("onError"),vJr=Symbol("pending"),t5u=Symbol("pend"),Jut=Symbol("unpend"),J8o=Symbol("ended"),Y8o=Symbol("maybeClose"),yGo=Symbol("skip"),J9t=Symbol("doChown"),Y9t=Symbol("uid"),X9t=Symbol("gid"),Z9t=Symbol("checkedCwd"),GDm=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,$9t=GDm==="win32",qDm=1024,WDm=(e,t)=>{if(!$9t)return Md.default.unlink(e,t);let r=e+".DELETE."+(0,BGo.randomBytes)(16).toString("hex");Md.default.rename(e,r,n=>{if(n)return t(n);Md.default.unlink(r,t)})},HDm=e=>{if(!$9t)return Md.default.unlinkSync(e);let t=e+".DELETE."+(0,BGo.randomBytes)(16).toString("hex");Md.default.renameSync(e,t),Md.default.unlinkSync(t)},r5u=(e,t,r)=>e!==void 0&&e===e>>>0?e:t!==void 0&&t===t>>>0?t:r,kGo=class extends eWt{[J8o]=!1;[Z9t]=!1;[vJr]=0;reservations=new UDm;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(e={}){if(e.ondone=()=>{this[J8o]=!0,this[Y8o]()},super(e),this.transform=e.transform,this.chmod=!!e.chmod,typeof e.uid=="number"||typeof e.gid=="number"){if(typeof e.uid!="number"||typeof e.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(e.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=e.preserveOwner===void 0&&typeof e.uid!="number"?!!(process.getuid&&process.getuid()===0):!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:qDm,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||$9t,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=Pf(bS.default.resolve(e.cwd||process.cwd())),this.strip=Number(e.strip)||0,this.processUmask=this.chmod?typeof e.processUmask=="number"?e.processUmask:VDm():0,this.umask=typeof e.umask=="number"?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on("entry",t=>this[JVu](t))}warn(e,t,r={}){return(e==="TAR_BAD_ARCHIVE"||e==="TAR_ABORT")&&(r.recoverable=!1),super.warn(e,t,r)}[Y8o](){this[J8o]&&this[vJr]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[K8o](e,t){let r=e[t],{type:n}=e;if(!r||this.preservePaths)return!0;let[i,o]=SGo(r),s=o.replaceAll(/\\/g,"/").split("/");if(s.includes("..")||$9t&&/^[a-z]:\.\.$/i.test(s[0]??"")){if(t==="path"||n==="Link")return this.warn("TAR_ENTRY_ERROR",`${t} contains '..'`,{entry:e,[t]:r}),!1;let a=bS.default.posix.dirname(e.path),c=bS.default.posix.normalize(bS.default.posix.join(a,s.join("/")));if(c.startsWith("../")||c==="..")return this.warn("TAR_ENTRY_ERROR",`${t} escapes extraction directory`,{entry:e,[t]:r}),!1}return i&&(e[t]=String(o),this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute ${t}`,{entry:e,[t]:r})),!0}[e5u](e){let t=Pf(e.path),r=t.split("/");if(this.strip){if(r.length<this.strip)return!1;if(e.type==="Link"){let n=Pf(String(e.linkpath)).split("/");if(n.length>=this.strip)e.linkpath=n.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),e.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:e,path:t,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[K8o](e,"path")||!this[K8o](e,"linkpath"))return!1;if(e.absolute=bS.default.isAbsolute(e.path)?Pf(bS.default.resolve(e.path)):Pf(bS.default.resolve(this.cwd,e.path)),!this.preservePaths&&typeof e.absolute=="string"&&e.absolute.indexOf(this.cwd+"/")!==0&&e.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:e,path:Pf(e.path),resolvedPath:e.absolute,cwd:this.cwd}),!1;if(e.absolute===this.cwd&&e.type!=="Directory"&&e.type!=="GNUDumpDir")return!1;if(this.win32){let{root:n}=bS.default.win32.parse(String(e.absolute));e.absolute=n+zVu(String(e.absolute).slice(n.length));let{root:i}=bS.default.win32.parse(e.path);e.path=i+zVu(e.path.slice(i.length))}return!0}[JVu](e){if(!this[e5u](e))return e.resume();switch(S5u.default.equal(typeof e.absolute,"string"),e.type){case"Directory":case"GNUDumpDir":e.mode&&(e.mode=e.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[mGo](e);default:return this[$Vu](e)}}[tO](e,t){e.name==="CwdError"?this.emit("error",e):(this.warn("TAR_ENTRY_ERROR",e,{entry:t}),this[Jut](),t.resume())}[awe](e,t,r){NDm(Pf(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t},r)}[J9t](e){return this.forceChown||this.preserveOwner&&(typeof e.uid=="number"&&e.uid!==this.processUid||typeof e.gid=="number"&&e.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Y9t](e){return r5u(this.uid,e.uid,this.processUid)}[X9t](e){return r5u(this.gid,e.gid,this.processGid)}[gGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=new MJr(String(e.absolute),{flags:R5u(e.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&Md.default.close(n.fd,()=>{}),n.write=()=>!0,this[tO](a,e),t()});let i=1,o=a=>{if(a){n.fd&&Md.default.close(n.fd,()=>{}),this[tO](a,e),t();return}--i===0&&n.fd!==void 0&&Md.default.close(n.fd,c=>{c?this[tO](c,e):this[Jut](),t()})};n.on("finish",()=>{let a=String(e.absolute),c=n.fd;if(typeof c=="number"&&e.mtime&&!this.noMtime){i++;let u=e.atime||new Date,l=e.mtime;Md.default.futimes(c,u,l,p=>p?Md.default.utimes(a,u,l,d=>o(d&&p)):o())}if(typeof c=="number"&&this[J9t](e)){i++;let u=this[Y9t](e),l=this[X9t](e);typeof u=="number"&&typeof l=="number"&&Md.default.fchown(c,u,l,p=>p?Md.default.chown(a,u,l,d=>o(d&&p)):o())}o()});let s=this.transform&&this.transform(e)||e;s!==e&&(s.on("error",a=>{this[tO](a,e),t()}),e.pipe(s)),s.pipe(n)}[AGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode;this[awe](String(e.absolute),r,n=>{if(n){this[tO](n,e),t();return}let i=1,o=()=>{--i===0&&(t(),this[Jut](),e.resume())};e.mtime&&!this.noMtime&&(i++,Md.default.utimes(String(e.absolute),e.atime||new Date,e.mtime,o)),this[J9t](e)&&(i++,Md.default.chown(String(e.absolute),Number(this[Y9t](e)),Number(this[X9t](e)),o)),o()})}[$Vu](e){e.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[XVu](e,t){let r=Pf(bS.default.relative(this.cwd,bS.default.resolve(bS.default.dirname(String(e.absolute)),String(e.linkpath)))).split("/");this[W9t](e,this.cwd,r,()=>this[kJr](e,String(e.linkpath),"symlink",t),n=>{this[tO](n,e),t()})}[ZVu](e,t){let r=Pf(bS.default.resolve(this.cwd,String(e.linkpath))),n=Pf(String(e.linkpath)).split("/");this[W9t](e,this.cwd,n,()=>this[kJr](e,r,"link",t),i=>{this[tO](i,e),t()})}[W9t](e,t,r,n,i){let o=r.shift();if(this.preservePaths||o===void 0)return n();let s=bS.default.resolve(t,o);Md.default.lstat(s,(a,c)=>{if(a)return n();if(c?.isSymbolicLink())return i(new HJr(s,bS.default.resolve(s,r.join("/"))));this[W9t](e,s,r,n,i)})}[t5u](){this[vJr]++}[Jut](){this[vJr]--,this[Y8o]()}[yGo](e){this[Jut](),e.resume()}[hGo](e,t){return e.type==="File"&&!this.unlink&&t.isFile()&&t.nlink<=1&&!$9t}[mGo](e){this[t5u]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,r=>this[YVu](e,r))}[YVu](e,t){let r=s=>{t(s)},n=()=>{this[awe](this.cwd,this.dmode,s=>{if(s){this[tO](s,e),r();return}this[Z9t]=!0,i()})},i=()=>{if(e.absolute!==this.cwd){let s=Pf(bS.default.dirname(String(e.absolute)));if(s!==this.cwd)return this[awe](s,this.dmode,a=>{if(a){this[tO](a,e),r();return}o()})}o()},o=()=>{Md.default.lstat(String(e.absolute),(s,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(e.mtime??a.mtime))){this[yGo](e),r();return}if(s||this[hGo](e,a))return this[k8](null,e,r);if(a.isDirectory()){if(e.type==="Directory"){let c=this.chmod&&e.mode&&(a.mode&4095)!==e.mode,u=l=>this[k8](l??null,e,r);return c?Md.default.chmod(String(e.absolute),Number(e.mode),u):u()}if(e.absolute!==this.cwd)return Md.default.rmdir(String(e.absolute),c=>this[k8](c??null,e,r))}if(e.absolute===this.cwd)return this[k8](null,e,r);WDm(String(e.absolute),c=>this[k8](c??null,e,r))})};this[Z9t]?i():n()}[k8](e,t,r){if(e){this[tO](e,t),r();return}switch(t.type){case"File":case"OldFile":case"ContiguousFile":return this[gGo](t,r);case"Link":return this[ZVu](t,r);case"SymbolicLink":return this[XVu](t,r);case"Directory":case"GNUDumpDir":return this[AGo](t,r)}}[kJr](e,t,r,n){Md.default[r](t,String(e.absolute),i=>{i?this[tO](i,e):(this[Jut](),e.resume()),n()})}},G9t=e=>{try{return[null,e()]}catch(t){return[t,null]}},z5u=class extends kGo{sync=!0;[k8](e,t){return super[k8](e,t,()=>{})}[mGo](e){if(!this[Z9t]){let i=this[awe](this.cwd,this.dmode);if(i)return this[tO](i,e);this[Z9t]=!0}if(e.absolute!==this.cwd){let i=Pf(bS.default.dirname(String(e.absolute)));if(i!==this.cwd){let o=this[awe](i,this.dmode);if(o)return this[tO](o,e)}}let[t,r]=G9t(()=>Md.default.lstatSync(String(e.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(e.mtime??r.mtime)))return this[yGo](e);if(t||this[hGo](e,r))return this[k8](null,e);if(r.isDirectory()){if(e.type==="Directory"){let o=this.chmod&&e.mode&&(r.mode&4095)!==e.mode,[s]=o?G9t(()=>{Md.default.chmodSync(String(e.absolute),Number(e.mode))}):[];return this[k8](s,e)}let[i]=G9t(()=>Md.default.rmdirSync(String(e.absolute)));this[k8](i,e)}let[n]=e.absolute===this.cwd?[]:G9t(()=>HDm(String(e.absolute)));this[k8](n,e)}[gGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.fmode,n=s=>{let a;try{Md.default.closeSync(i)}catch(c){a=c}(s||a)&&this[tO](s||a,e),t()},i;try{i=Md.default.openSync(String(e.absolute),R5u(e.size),r)}catch(s){return n(s)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on("error",s=>this[tO](s,e)),e.pipe(o)),o.on("data",s=>{try{Md.default.writeSync(i,s,0,s.length)}catch(a){n(a)}}),o.on("end",()=>{let s=null;if(e.mtime&&!this.noMtime){let a=e.atime||new Date,c=e.mtime;try{Md.default.futimesSync(i,a,c)}catch(u){try{Md.default.utimesSync(String(e.absolute),a,c)}catch{s=u}}}if(this[J9t](e)){let a=this[Y9t](e),c=this[X9t](e);try{Md.default.fchownSync(i,Number(a),Number(c))}catch(u){try{Md.default.chownSync(String(e.absolute),Number(a),Number(c))}catch{s=s||u}}}n(s)})}[AGo](e,t){let r=typeof e.mode=="number"?e.mode&4095:this.dmode,n=this[awe](String(e.absolute),r);if(n){this[tO](n,e),t();return}if(e.mtime&&!this.noMtime)try{Md.default.utimesSync(String(e.absolute),e.atime||new Date,e.mtime)}catch{}if(this[J9t](e))try{Md.default.chownSync(String(e.absolute),Number(this[Y9t](e)),Number(this[X9t](e)))}catch{}t(),e.resume()}[awe](e,t){try{return zDm(Pf(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:t})}catch(r){return r}}[W9t](e,t,r,n,i){if(this.preservePaths||r.length===0)return n();let o=t;for(let s of r){o=bS.default.resolve(o,s);let[a,c]=G9t(()=>Md.default.lstatSync(o));if(a)return n();if(c.isSymbolicLink())return i(new HJr(o,bS.default.resolve(t,r.join("/"))))}n()}[kJr](e,t,r,n){let i=`${r}Sync`;try{Md.default[i](t,String(e.absolute)),n(),e.resume()}catch(o){return this[tO](o,e)}}},KDm=e=>{let t=new z5u(e),r=e.file,n=PGo.default.statSync(r),i=e.maxReadSize||16*1024*1024;new IRm(r,{readSize:i,size:n.size}).pipe(t)},JDm=(e,t)=>{let r=new kGo(e),n=e.maxReadSize||16*1024*1024,i=e.file;return new Promise((o,s)=>{r.on("error",s),r.on("close",o),PGo.default.stat(i,(a,c)=>{if(a)s(a);else{let u=new EGo(i,{readSize:n,size:c.size});u.on("error",s),u.pipe(r)}})})},Q5u=nWt(KDm,JDm,e=>new z5u(e),e=>new kGo(e),(e,t)=>{t?.length&&A5u(e,t)}),YDm=(e,t)=>{let r=new OGo(e),n=!0,i,o;try{try{i=bM.default.openSync(e.file,"r+")}catch(c){if(c?.code==="ENOENT")i=bM.default.openSync(e.file,"w+");else throw c}let s=bM.default.fstatSync(i),a=Buffer.alloc(512);e:for(o=0;o<s.size;o+=512){for(let l=0,p=0;l<512;l+=p){if(p=bM.default.readSync(i,a,l,a.length-l,o+l),o===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let c=new gVe(a);if(!c.cksumValid)break;let u=512*Math.ceil((c.size||0)/512);if(o+u+512>s.size)break;o+=u,e.mtimeCache&&c.mtime&&e.mtimeCache.set(String(c.path),c.mtime)}n=!1,XDm(e,r,o,i,t)}finally{if(n)try{bM.default.closeSync(i)}catch{}}},XDm=(e,t,r,n,i)=>{let o=new s5u(e.file,{fd:n,start:r});t.pipe(o),$Dm(t,i)},ZDm=(e,t)=>{t=Array.from(t);let r=new qJr(e),n=(i,o,s)=>{let a=(d,f)=>{d?bM.default.close(i,m=>s(d)):s(null,f)},c=0;if(o===0)return a(null,0);let u=0,l=Buffer.alloc(512),p=(d,f)=>{if(d||f===void 0)return a(d);if(u+=f,u<512&&f)return bM.default.read(i,l,u,l.length-u,c+u,p);if(c===0&&l[0]===31&&l[1]===139)return a(new Error("cannot append to compressed archives"));if(u<512)return a(null,c);let m=new gVe(l);if(!m.cksumValid)return a(null,c);let g=512*Math.ceil((m.size??0)/512);if(c+g+512>o||(c+=g+512,c>=o))return a(null,c);e.mtimeCache&&m.mtime&&e.mtimeCache.set(String(m.path),m.mtime),u=0,bM.default.read(i,l,0,512,c,p)};bM.default.read(i,l,0,512,c,p)};return new Promise((i,o)=>{r.on("error",o);let s="r+",a=(c,u)=>{if(c&&c.code==="ENOENT"&&s==="r+")return s="w+",bM.default.open(e.file,s,a);if(c||!u)return o(c);bM.default.fstat(u,(l,p)=>{if(l)return bM.default.close(u,()=>o(l));n(u,p.size,(d,f)=>{if(d)return o(d);let m=new MJr(e.file,{fd:u,start:f});r.pipe(m),m.on("error",o),m.on("close",i),ekm(r,t)})})};bM.default.open(e.file,s,a)})},$Dm=(e,t)=>{t.forEach(r=>{r.charAt(0)==="@"?VJr({file:FGo.default.resolve(e.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r)}),e.end()},ekm=async(e,t)=>{for(let r of t)r.charAt(0)==="@"?await VJr({file:FGo.default.resolve(String(e.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>e.add(n)}):e.add(r);e.end()},q9t=nWt(YDm,ZDm,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(e,t)=>{if(!TRm(e))throw new TypeError("file is required");if(e.gzip||e.brotli||e.zstd||e.file.endsWith(".br")||e.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!t?.length)throw new TypeError("no paths specified to add/replace")}),Yxv=nWt(q9t.syncFile,q9t.asyncFile,q9t.syncNoFile,q9t.asyncNoFile,(e,t=[])=>{q9t.validate?.(e,t),tkm(e)}),tkm=e=>{let t=e.filter;e.mtimeCache||(e.mtimeCache=new Map),e.filter=t?(r,n)=>t(r,n)&&!((e.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0)):(r,n)=>!((e.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0))}});var co,JJr=h(()=>{"use strict";Wn();co=class e{breadcrumbs=[];context;static STRING=Zt.TypeReference.primitive({v1:"STRING",v2:Zt.PrimitiveTypeV2.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Zt.TypeReference.container(Zt.ContainerType.optional(e.STRING));constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r}}});var NGo,M5u,L5u=h(()=>{"use strict";NGo=class{_map;_path;_lastScalar;_fragments;_count;constructor(){this._map={},this._path=[],this._lastScalar="",this._fragments=[],this._count=0}get map(){return this._map}resolveNode(t,r){if(t.path==="."&&(r="."),!this._map[r]){let{line:n,position:i,lineStart:o}=t;this._map[r]={line:n,position:i,lineStart:o}}t.children&&t.children.length>0&&t.children.forEach(n=>{this.resolveNode(n,(r==="."?"":r)+"."+n.path)})}iterFragments(t,r){for(let n=this._fragments.length-1;n>=0;n--){if(!this._fragments[n].path.startsWith(t)||this._fragments[n].path===t)continue;let i=this._fragments.pop();r(i)}}handleState(t,r){if(t==="close"){let n=r.result,i=r.kind,o=this._path.join(".");if(i==="scalar"){this._path.pop(),this._lastScalar=`${n}`;let{line:s,position:a,lineStart:c}=r;this._path.length===0?this._map["."+n]={line:s,position:a,lineStart:c}:this._fragments.push({path:this._path.join(".")+"."+n,line:s,position:a,lineStart:c})}else if(i==="mapping"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=0;this.iterFragments(o,c=>{a++,!((!c.children||c.children.length===0)&&a%2===1)&&(this._path.length===1?this.resolveNode(c,c.path):(s.children.push({...c,path:c.path.slice(o.length+1)}),s.line=c.line,s.position=c.position,s.lineStart=c.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else if(i==="sequence"){let s={path:o,children:[],line:0,position:0,lineStart:0},a=new Set,c=n.length;this.iterFragments(o,u=>{a.has(u.position)||(c--,a.add(u.position),this._path.length===1?this.resolveNode(u,`${o}.${c}`):(s.children.push({...u,path:c.toString()}),s.line=u.line,s.position=u.position,s.lineStart=u.lineStart))}),s.children&&s.children.length>0&&this._fragments.push(s),this._path.pop()}else this._path.pop()}if(t==="open"){if(this._count===0){let{line:n,position:i,lineStart:o}=r;this._map["."]={line:n,position:i,lineStart:o}}this._path.push(this._lastScalar),this._count++}}listen(){return this.handleState.bind(this)}lookup(t){let r=t instanceof Array?t.map(i=>`${i}`).join("."):`${t}`;r.startsWith(".")||(r="."+r),r.startsWith("..")&&(r=r.slice(1)),r=r.replace(/\[/g,".").replace(/\]/g,"");let n=this._map[r];if(n)return{line:n.line+1,column:n.position-n.lineStart+1,position:n.position}}},M5u=NGo});var _5u,CE,tne,jGo,oWt=h(()=>{"use strict";tr();Ky();_5u=require("fs/promises");cs();L5u();(function(e){e.WARNING="warning",e.ERROR="error"})(CE||(CE={}));tne=class{errors=[];logger;breadcrumbToLineNumberMapper;relativeFilepathToSpec;constructor({logger:t,relativeFilepathToSpec:r}){this.logger=t,this.relativeFilepathToSpec=r,r&&(this.breadcrumbToLineNumberMapper=new jGo({logger:t,relativePathToFile:Ae.of(r)}))}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}dedupe(){let t=[],r=new Set,n=0;for(let i of this.errors){let o=i.path?i.path.join("->"):"",s=`${i.message}|${i.level||CE.WARNING}|${o}`;r.has(s)?n++:(r.add(s),t.push(i))}return this.errors=t,n}getErrorStats(){this.dedupe();let t=0,r=0;for(let n of this.errors)n.level===CE.ERROR?t++:(n.level===CE.WARNING||n.level===void 0)&&r++;return{numErrors:t,numWarnings:r}}async logErrors({logWarnings:t}){this.dedupe();for(let r of this.errors){let n=r.level??CE.WARNING;if(!(n===CE.WARNING&&!t))switch(n){case CE.ERROR:if(this.logger.log(Zn.Debug,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),o=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Zn.Debug,` - at location (${o})`)}break;case CE.WARNING:if(this.logger.log(Zn.Warn,r.message),r.path&&r.path.length>0){let i=await this.breadcrumbToLineNumberMapper?.getSourceLocation(r.path),o=i?`${this.relativeFilepathToSpec}:${i.line}:${i.column}`:r.path.join(" -> ");this.logger.log(Zn.Warn,` - at location (${o})`)}r.resolution&&this.logger.log(Zn.Warn,` - resolution: ${r.resolution}`);break}}}},jGo=class{logger;relativePathToFile;map=new M5u;initialized=!1;constructor({relativePathToFile:t,logger:r}){this.relativePathToFile=t,this.logger=r}async initialize(){if(!this.initialized)try{let t=await(0,_5u.readFile)(this.relativePathToFile,"utf-8");Cr.load(t,{listener:this.map.listen()}),this.initialized=!0}catch(t){this.logger.log(Zn.Warn,`Failed to initialize line number mapping for ${this.relativePathToFile}: ${JSON.stringify(t)}`)}}async getSourceLocation(t){return this.initialized||await this.initialize(),this.map.lookup(t)}}});function nkm(e){return"deprecated"in e&&e.deprecated===!0}async function ikm(e){let t=await fetch(e);if(t.ok)try{let r=await t.text();try{return JSON.parse(r)}catch{return Cr.load(r)}}catch{return}}var S0,U5u=h(()=>{"use strict";b8();ct();Wn();cs();qi();oWt();rs();S0=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;authOverrides;environmentOverrides;globalHeaderOverrides;enableUniqueErrorsPerEndpoint;generateV1Examples;documentBaseDir;externalDocuments=new Map;discriminatedVariantsInProgress=new Set;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=Ww({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs,this.authOverrides=t.authOverrides,this.environmentOverrides=t.environmentOverrides,this.globalHeaderOverrides=t.globalHeaderOverrides,this.enableUniqueErrorsPerEndpoint=t.enableUniqueErrorsPerEndpoint,this.generateV1Examples=t.generateV1Examples,this.documentBaseDir=t.documentBaseDir}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=e.getPropertyNameIndices(t),n=t.filter((o,s)=>r.has(s)?!0:!(/^\d+$/.test(o)||e.BREADCRUMBS_TO_IGNORE.includes(o)||s===0&&o==="components"||s===1&&o==="schemas"||t[0]==="paths"&&(s===0||s===1&&["get","post","put","delete","patch"].includes(o)||s===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&o==="parameters"))),i=ti(n.join("_"));return BH(i)}static getPropertyNameIndices(t){let r=new Set;for(let[n,i]of t.entries())i==="properties"&&!r.has(n)&&n+1<t.length&&r.add(n+1);return r}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],n=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:n?[...r,n]:r,packagePath:r,file:n}}resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n}){let i=this.spec,o=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(s=>s.replace(/~1/g,"/"));for(let s of o){if(typeof i!="object"||i==null)return n||this.errorCollector.collect({level:CE.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1};i=i[s]}return i==null?(n||this.errorCollector.collect({level:CE.ERROR,message:this.getErrorMessageForMissingRef({reference:t}),path:r}),{resolved:!1}):{resolved:!0,value:i}}getErrorMessageForMissingRef({reference:t}){let r=t.$ref.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/");return r.length>=3&&r[0]==="components"&&r[1]==="schemas"?`Schema ${r[2]} does not exist`:`${t.$ref} does not exist`}async resolveMaybeExternalReference(t){let r=this.spec,n,i=!1,o=null,s;if(this.isExternalReference(t.$ref)){i=!0;let u=t.$ref.split("#"),l=u[0];if(n=u[1],!l)return{resolved:!1};if(s=l,o=await this.loadExternalDocument(l),r=o,r==null)return{resolved:!1};if(!n)return{resolved:!0,value:r}}let a=n??t.$ref;if(a==null||typeof a!="string")return{resolved:!1};let c=a.replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(u=>u.replace(/~1/g,"/"));for(let u of c){if(typeof r!="object"||r==null)return{resolved:!1};r=r[u]}if(r==null)return{resolved:!1};if(i&&typeof r=="object"&&r!==null){let u=new Set;u.add(t.$ref),r=await this.resolveNestedExternalReferences(r,o,u,s)}return{resolved:!0,value:r}}async loadExternalDocument(t){let r=this.externalDocuments.get(t);r==null&&(r=ikm(t),this.externalDocuments.set(t,r));try{let n=await r;return n==null&&this.forgetExternalDocument(t,r),structuredClone(n)}catch(n){throw this.forgetExternalDocument(t,r),n}}forgetExternalDocument(t,r){this.externalDocuments.get(t)===r&&this.externalDocuments.delete(t)}async resolveNestedExternalReferences(t,r,n,i){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let s=[];for(let a of t)s.push(await this.resolveNestedExternalReferences(a,r,n,i));return s}if(this.isReferenceObject(t)){let s=t.$ref;if(this.isExternalReference(s)){if(n.has(s))return t;n.add(s);let a=await this.resolveMaybeExternalReference({$ref:s});if(n.delete(s),a.resolved)return a.value}else{let a=`${i}${s}`;if(n.has(a))return t;n.add(a);let c=r,u=s.substring(2).split("/").map(fI);for(let l of u){if(typeof c!="object"||c===null)return t;c=c[l]}if(c!=null){let l=await this.resolveNestedExternalReferences(c,r,n,i);return n.delete(s),l}n.delete(s)}return t}let o={};for(let[s,a]of Object.entries(t))typeof a=="object"&&a!==null?o[s]=await this.resolveNestedExternalReferences(a,r,n,i):o[s]=a;return o}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let n=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?n.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),n}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:n}){if(t==null)return[];let i=[];if(t.example!=null){let o=this.generateUniqueName({prefix:n??`${r.join("_")}_example`,existingNames:[]});i.push([o,{value:t.example}])}return t.examples!=null&&i.push(...Object.entries(t.examples)),i}resolveMaybeReference({schemaOrReference:t,breadcrumbs:r,skipErrorCollector:n}){if(this.isReferenceObject(t)){let i=this.resolveReference({reference:t,breadcrumbs:r,skipErrorCollector:n});return i.resolved?i.value:void 0}return t}resolveExampleRecursively({example:t,breadcrumbs:r,maxDepth:n=10}){let i=t,o=0;for(;this.isReferenceObject(i);){if(o>=n){this.errorCollector.collect({message:`Maximum reference depth (${n}) exceeded while resolving example reference`,path:r});return}let s=this.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!s.resolved)return;i=s.value,o++}return i}resolveExample(t){if(!this.isReferenceObject(t))return t;let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.returnExampleValue(t);let r=this.resolveReference({reference:t});return r.resolved?this.returnExampleValue(r.value):void 0}returnExampleValue(t){return this.isExampleWithValue(t)?t.value:t}getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let o=this.resolveReference({reference:r});if(!o.resolved)return;r=o.value}let{readOnly:n,writeOnly:i}=this.getReadOnlyWriteOnlyFromSchema(r);if(!(n&&i)){if(n)return Zt.ObjectPropertyAccess.ReadOnly;if(i)return Zt.ObjectPropertyAccess.WriteOnly}}getReadOnlyWriteOnlyFromSchema(t){if(t.allOf&&t.allOf.length>0){let r=!0,n=!0;for(let i of t.allOf){let o=i;if(this.isReferenceObject(i)){let a=this.resolveReference({reference:i});if(!a.resolved)continue;o=a.value}let s=this.getReadOnlyWriteOnlyFromSchema(o);r=r&&s.readOnly,n=n&&s.writeOnly}return{readOnly:r,writeOnly:n}}else return{readOnly:!!t.readOnly,writeOnly:!!t.writeOnly}}getAudiences({operation:t,breadcrumbs:r}){let i=new qC.AudienceExtension({operation:t,breadcrumbs:r,context:this}).convert();if(i!=null)return i.audiences}getAvailability({node:t,breadcrumbs:r}){let n=new Set;for(;this.isReferenceObject(t);){let i=this.getDeclaredAvailability({node:t,breadcrumbs:r});if(i!=null)return i;if(n.has(t.$ref))return;n.add(t.$ref);let o=this.resolveReference({reference:t});if(!o.resolved)return;t=o.value}return this.getDeclaredAvailability({node:t,breadcrumbs:r})}getDeclaredAvailability({node:t,breadcrumbs:r}){let i=new qC.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(i!=null)return{status:i,message:void 0};if(nkm(t))return{status:yh.Deprecated,message:void 0}}getNamespacedSchemaId(t){if(this.namespace==null)return t;let r=`${this.namespace}:`;return t.startsWith(r)?t:`${r}${t}`}getRawSchemaId(t){if(this.namespace==null)return t;let r=`${this.namespace}:`;return t.startsWith(r)?t.slice(r.length):t}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return this.getNamespacedSchemaId(r[1])}getRawSchemaNameFromReference(t){let r=t.$ref.match(/\/schemas\/([^/]+)/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t,r){return en.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t),typeId:this.getNamespacedSchemaId(t),displayName:r,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type==="named")return{typeId:t.typeId,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:t.name,displayName:t.displayName}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){let n=this.getNamespacedSchemaId(t);return Object.fromEntries(Object.entries(r).filter(([i])=>i!==n))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let n=0;for(;r.includes(`${t}_${n}`);)n++;return`${t}_${n}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return typeof t=="string"&&vg(t)}isReferenceObjectWithIdentifier(t){return this.isReferenceObject(t)&&("title"in t||"name"in t||"messageId"in t||"summary"in t)}isExampleWithSummary(t){return typeof t=="object"&&t!=null&&"summary"in t&&typeof t.summary=="string"&&t.summary.length>0}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(Fr(t))return t}getGroup({groupParts:t,namespace:r}){let n=[];return r!=null&&n.push(r),n.push(...t??[]),n}isObjectSchemaType(t){return t.type==="object"||t.properties!=null}}});var os,tk=h(()=>{"use strict";os=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t,r){if(typeof t!="object"||t==null)return;let n=t[this.key];if(n!=null)return n;if(r!=null)return t[r]}}});var nlt,zGo=h(()=>{"use strict";tk();nlt=class extends os{operation;key="x-fern-audiences";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{audiences:r}}}});var YJr,V5u=h(()=>{"use strict";Wn();tk();YJr=class extends os{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return yh.InDevelopment;case"PRE_RELEASE":return yh.PreRelease;case"GENERAL_AVAILABILITY":case"GENERALLY_AVAILABLE":case"GA":case"STABLE":return yh.GeneralAvailability;case"DEPRECATED":return yh.Deprecated;case"ALPHA":return yh.Alpha;case"BETA":return yh.Beta;case"PREVIEW":return yh.Preview;case"LEGACY":return yh.Legacy;default:return}}}});var ilt,QGo=h(()=>{"use strict";tk();ilt=class extends os{node;key="x-fern-discriminated";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null&&typeof t=="boolean")return t}}});var olt,MGo=h(()=>{"use strict";tk();olt=class extends os{node;key="x-fern-discriminator-context";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t==="data"||t==="protocol")return t}}});var okm,skm,G5u,q5u=h(()=>{"use strict";cn();okm=De.object({snake:De.string().optional(),camel:De.string().optional(),screamingSnake:De.string().optional(),pascal:De.string().optional()}),skm=De.object({description:De.string().optional(),name:De.string().optional(),casing:okm.optional()}),G5u=De.record(skm)});var slt,LGo=h(()=>{"use strict";tk();q5u();slt=class extends os{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=G5u.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}}});var yVe,W5u=h(()=>{"use strict";tk();yVe=class extends os{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}}});var XJr,H5u=h(()=>{"use strict";tk();XJr=class extends os{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:n}){super({breadcrumbs:t,context:n}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}}});var ZJr,K5u=h(()=>{"use strict";tk();ZJr=class extends os{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(n=>typeof n=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}}});var $Jr,J5u=h(()=>{"use strict";tk();$Jr=class extends os{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}}});var eYr,Y5u=h(()=>{"use strict";tk();eYr=class extends os{operation;key="x-fern-server-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation,"x-name");if(!(t==null||typeof t!="string"))return t}}});var tYr,X5u=h(()=>{"use strict";tk();tYr=class extends os{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}}});var rYr,Z5u=h(()=>{"use strict";tk();rYr=class extends os{schema;key="x-fern-type-name";constructor({breadcrumbs:t,schema:r,context:n}){super({breadcrumbs:t,context:n}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(typeof t=="string")return t}}});function akm({isText:e,isAttribute:t}){return e?lQ.Text:t?lQ.Attribute:lQ.Element}function t8u(e){return typeof e=="object"&&e!=null}function nYr(e,t){if(!(typeof e!="object"||e==null))return e[t]}function _Go(...e){return e.find(t=>t!=null)}var $5u,e8u,alt,clt,iYr=h(()=>{"use strict";Wn();tk();$5u="x-fern-xml-text",e8u="x-fern-xml-list-separator",alt=class extends os{schema;fallbackName;key="xml";constructor({breadcrumbs:t,schema:r,fallbackName:n,context:i}){super({breadcrumbs:t,context:i}),this.schema=r,this.fallbackName=n}convert(){let t=this.getExtensionValue(this.schema);if(t8u(t))return{name:typeof t.name=="string"?t.name:this.fallbackName,namespace:typeof t.namespace=="string"?t.namespace:void 0,prefix:typeof t.prefix=="string"?t.prefix:void 0}}},clt=class extends os{propertySchema;resolvedPropertySchema;key="xml";constructor({breadcrumbs:t,propertySchema:r,resolvedPropertySchema:n,context:i}){super({breadcrumbs:t,context:i}),this.propertySchema=r,this.resolvedPropertySchema=n}convert(){let t=this.propertySchema,r=this.resolvedPropertySchema,n=_Go(this.getExtensionValue(t),this.getExtensionValue(r)),i=_Go(nYr(t,$5u),nYr(r,$5u)),o=_Go(nYr(t,e8u),nYr(r,e8u)),s=t8u(n)?n:{};return{kind:akm({isText:i===!0,isAttribute:s.attribute===!0}),name:typeof s.name=="string"?s.name:void 0,wrapped:typeof s.wrapped=="boolean"?s.wrapped:void 0,listSeparator:typeof o=="string"?o:void 0}}}});var qC={};$(qC,{AudienceExtension:()=>nlt,FernAvailabilityExtension:()=>YJr,FernDiscriminatedExtension:()=>ilt,FernDiscriminatorContextExtension:()=>olt,FernEnumExtension:()=>slt,FernIgnoreExtension:()=>yVe,FernOptionalExtension:()=>XJr,FernTypeExtension:()=>tYr,FernTypeNameExtension:()=>rYr,SdkGroupNameExtension:()=>ZJr,SdkMethodNameExtension:()=>$Jr,ServerFromOperationNameExtension:()=>eYr,XmlPropertyExtension:()=>clt,XmlSchemaExtension:()=>alt});var UGo=h(()=>{"use strict";zGo();V5u();QGo();MGo();LGo();W5u();H5u();K5u();J5u();Y5u();X5u();Z5u();iYr()});function n8u(e){let t=new Map,r=(i,o)=>{if(t.has(i))return t.get(i);let s=e[i];if(s==null||o.has(i))return;o.add(i);let a=n(s,o);return o.delete(i),t.set(i,a),a},n=(i,o)=>{let s=a=>Tw.named({name:i.name,shape:a});switch(i.shape.type){case"object":return s(yD.Object);case"enum":return s(yD.Enum);case"union":return s(yD.Union);case"undiscriminatedUnion":return s(yD.UndiscriminatedUnion);case"alias":{let{resolvedType:a}=i.shape,c=r8u(a);return c!=null?r(c,o):a}default:return}};for(let[i,o]of Object.entries(e)){if(o.shape.type!=="alias"||r8u(o.shape.resolvedType)==null)continue;let s=r(i,new Set);s!=null&&(e[i]={...o,shape:mc.alias({aliasOf:o.shape.aliasOf,resolvedType:s})})}}function r8u(e){if(e.type!=="named")return;let t=e;return e.shape==null&&typeof t.typeId=="string"?t.typeId:void 0}var i8u=h(()=>{"use strict";Wn()});var PJ,o8u=h(()=>{"use strict";Wn();hc();qi();JJr();UGo();i8u();PJ=class extends co{ir;audiences;irGraph;constructor({breadcrumbs:t=[],context:r,audiences:n}){super({breadcrumbs:t,context:r}),this.audiences=n,this.irGraph=new CUe(n),this.ir={auth:{docs:void 0,requirement:Zt.AuthSchemesRequirement.All,schemes:[]},selfHosted:!1,types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:Zt.ErrorDiscriminationStrategy.statusCode(),variables:[],globalParameters:void 0,serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:this.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,idempotencyKeyGeneration:void 0,webhookSignatureVerification:void 0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}},audiences:void 0,generationMetadata:void 0,apiPlayground:void 0,casingsConfig:void 0,specVersion:void 0}}removeXFernIgnores({document:t,breadcrumbs:r=[]}){return Array.isArray(t)?t.filter((n,i)=>!new yVe({breadcrumbs:[...r,String(i)],operation:n,context:this.context}).convert()).map((n,i)=>this.removeXFernIgnores({document:n,breadcrumbs:[...r,String(i)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([n,i])=>!new yVe({breadcrumbs:[...r,n],operation:i,context:this.context}).convert()).map(([n,i])=>[n,this.removeXFernIgnores({document:i,breadcrumbs:[...r,n]})])):t}finalizeIr(){let t=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.response?.body?.type==="streaming")),r=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.pagination!=null)),n=Object.values(this.ir.services).some(a=>a.endpoints.some(c=>c.response?.body?.type==="fileDownload"));this.ir.sdkConfig={...this.ir.sdkConfig,hasStreamingEndpoints:t,hasPaginatedEndpoints:r,hasFileDownloadEndpoints:n},iqt(this.ir,{onWarning:a=>this.context.logger.warn(a)}),n8u(this.ir.types);let i={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})},audiences:this.audiences.type==="select"?this.audiences.audiences:void 0};this.irGraph.hasNoAudiences()||(i=this.filterIrForAudiences(i)),$Gt({ir:i});let o=this.context.exampleGenerationArgs,s=MLo({ir:i,exampleGeneration:o,logger:this.context.logger});if(this.context.generateV1Examples){let a=tqt({ir:i,exampleGeneration:o});return{...i,...a,...s}}return{...i,...s}}filterIrForAudiences(t){return{...nqt(t,this.irGraph.build()),sdkConfig:t.sdkConfig,subpackages:t.subpackages,rootPackage:t.rootPackage}}async resolveAllExternalRefs({spec:t}){let r=[t];for(let n=0;n<r.length;n++){let i=r[n];i!=null&&(Array.isArray(i)?await this.resolveExternalRefsInArray(i,r):typeof i=="object"&&await this.resolveExternalRefsInObject(i,r))}return t}async resolveExternalRefsInArray(t,r){for(let n=0;n<t.length;n++)t[n]=await this.resolveReferenceChain(t[n],r)}async resolveExternalRefsInObject(t,r){for(let[n,i]of Object.entries(t))t[n]=await this.resolveReferenceChain(i,r)}async resolveReferenceChain(t,r){let n=t;if(!this.context.isReferenceObject(n))return r.push(n),t;for(;this.context.isReferenceObject(n);){let i=this.context.isExternalReference(n.$ref),o=await this.context.resolveMaybeExternalReference(n);if(o.resolved){if(n=o.value,i)return n}else return t}return t}shouldAddServerToCollectedServers({server:t,currentServers:r,specType:n="openapi"}){return n==="openapi"?!r.some(i=>i.url===t.url&&"x-fern-server-name"in i&&"x-fern-server-name"in t&&i["x-fern-server-name"]===t["x-fern-server-name"]):!r.some(i=>i.url===t.url&&"name"in i&&"name"in t&&i.name===t.name)}addEndpointToIr({endpoint:t,audiences:r,endpointGroup:n,endpointGroupDisplayName:i,endpointGroupDescription:o,serviceName:s,inlinedRequestPropertiesByAudience:a,queryParametersByAudience:c}){let u=this.context.getGroup({groupParts:n,namespace:this.context.namespace}),l=this.getOrCreatePackage({group:n});l!==this.ir.rootPackage&&l.docs==null&&o!=null&&(l.docs=o);let p=[...u].map(m=>this.context.casingsGenerator.generateName(m)),d=p[p.length-1];l.service==null&&(l.service=s??`service_${u.map(m=>ti(m)).join("/")}`),this.ir.services[l.service]==null&&(this.ir.services[l.service]=this.createNewService({allParts:p,finalpart:d,endpointGroupDisplayName:i})),this.ir.services[l.service]?.endpoints.push(t);let f=this.ir.services[l.service];f!=null&&(this.irGraph.addEndpoint(f,t),this.irGraph.markEndpointForAudience(f.name,[t],r),a!=null&&Object.keys(a).length>0&&this.irGraph.markInlinedRequestPropertiesForAudiences(t.id,a),c!=null&&Object.keys(c).length>0&&this.irGraph.markQueryParametersForAudiences(t.id,c))}addWebhookToIr({webhook:t,operationId:r,audiences:n,group:i,inlinedPayloadPropertiesByAudience:o}){let s=i?.join(".")??r,a=this.getOrCreatePackage({group:i});this.ir.webhookGroups[s]==null&&(this.ir.webhookGroups[s]=[]),this.ir.webhookGroups[s].push(t),a.webhooks=s;let c=this.context.createFernFilepath();this.irGraph.addWebhook(c,t),n!=null&&this.irGraph.markWebhookForAudiences(c,t,n),t.id!=null&&o!=null&&Object.keys(o).length>0&&this.irGraph.markInlinedWebhookPayloadPropertiesForAudiences(t.id,o)}addWebsocketChannelToIr({websocketChannel:t,channelPath:r,audiences:n,websocketGroup:i}){let o=ti(i?.join(".")),s=ti(r),a=this.context.namespace?`${ti(this.context.namespace)}/`:"",c=o?`channel_${a}${o}`:`channel_${a}${s}`,u=i?this.getOrCreatePackage({group:i}):this.getOrCreatePackage({group:[s]});this.ir.websocketChannels={...this.ir.websocketChannels,[c]:t},c!==""?u.websocket==null&&(u.websocket=c):this.ir.rootPackage.websocket="";let l=this.context.createFernFilepath();this.irGraph.addChannel(l,c,t),n!=null&&this.irGraph.markChannelForAudiences(l,c,n)}addAuthToIR(t){this.ir.auth=t}addErrorsToIr(t){this.ir.errors=t;for(let r of Object.values(t))this.irGraph.addError(r)}addGlobalHeadersToIr(t){this.ir.headers=t}addEnvironmentsToIr({environmentConfig:t,audiences:r}){if(this.ir.environments=t,t==null)return;let n=t.environments.environments,i=r==null||n.every(o=>o.audiences==null);for(let o of n)this.irGraph.markEnvironmentForAudiences(o,r?.[o.id]??[],i)}addTypeToRootPackage(t){this.ir.rootPackage.types.push(t)}addSchemaOutputToIr(t,r){let{convertedSchema:n,inlinedTypes:i}=r,o=this.context.getNamespacedSchemaId(t),a=Object.keys(i).some(c=>c===o)?`${o}Wrapper`:o;this.addTypeToPackage(a),this.addTypesToIr({...i,[a]:n})}addTypeToPackage(t){let r=this.context.getGroup({groupParts:[],namespace:this.context.namespace});this.getOrCreatePackage({group:r}).types.push(t)}addTypesToIr(t){Object.assign(this.ir.types,Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n.typeDeclaration])));for(let r of Object.values(t))this.irGraph.addType({declaredTypeName:r.typeDeclaration.name,descendantTypeIds:r.typeDeclaration.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:r.propertiesByAudience,descendantFilepaths:new Set}),this.irGraph.markTypeForAudiences(r.typeDeclaration.name,r.audiences)}updateEndpointsWithDefaultUrl(t){if(t!=null)for(let r of Object.values(this.ir.services))for(let n of r.endpoints)n.baseUrl==null&&(n.baseUrl=t)}createNewService({allParts:t,finalpart:r,endpointGroupDisplayName:n}){return{name:{fernFilepath:{allParts:t,packagePath:t.slice(0,-1),file:r}},displayName:n,basePath:sb(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0,audiences:void 0}}createPackage(t={}){return{fernFilepath:this.context.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,hasWebSocketInTree:void 0,navigationConfig:void 0}}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...(t??[]).map(i=>ti(i))),r.length==0)return this.ir.rootPackage;let n=this.ir.rootPackage;for(let i=0;i<r.length;i++){let o=r[i]??"",a=`subpackage_${r.slice(0,i+1).join("/")}`;this.ir.subpackages[a]==null&&(this.ir.subpackages[a]={name:this.context.casingsGenerator.generateName(o),displayName:void 0,...this.createPackage({name:o})});let c=this.ir.subpackages[a];n.subpackages.includes(a)||n.subpackages.push(a),n=c}return n}}});function bVe(e){return typeof e=="object"&&e!==null&&!("$ref"in e)}function lkm(e){if(!bVe(e))return!1;if("nullable"in e&&e.nullable===!0)return!0;let t=r=>Array.isArray(r)&&r.some(n=>bVe(n)&&n.type==="null");return t(e.anyOf)||t(e.oneOf)}function pkm(e){return e.type==="array"||e.properties||e.oneOf||e.anyOf||e.allOf||e.additionalProperties?!1:!!(e.type==="string"||e.type==="number"||e.type==="integer"||e.type==="boolean"||e.const!==void 0||Array.isArray(e.enum)&&e.enum.length>0)}function a8u(e){if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0]}var ckm,s8u,ukm,Yw,lwe=h(()=>{"use strict";ct();rs();ckm=/^literal<\s*(?:"(.*)"|(true|false))\s*>$/,s8u=new WeakMap,ukm=new Set(["type","properties","required","allOf","description","title","deprecated","readOnly","writeOnly","xml","externalDocs","discriminator"]);Yw=class e extends co{MAX_DEPTH=12;EXAMPLE_STRING=Jo.STRING;EXAMPLE_NUMBER=Jo.DOUBLE;EXAMPLE_BOOLEAN=Jo.BOOLEAN;EXAMPLE_INTEGER=Jo.INT;EXAMPLE_DATE=Jo.DATE;EXAMPLE_DATE_TIME=Jo.DATE_TIME;schema;example;depth;exampleGenerationStrategy;generateOptionalProperties;seenRefs;sharedState;constructor({breadcrumbs:t,context:r,schema:n,example:i,depth:o=0,exampleGenerationStrategy:s,generateOptionalProperties:a=!1,seenRefs:c=new Set}){super({breadcrumbs:t,context:r}),this.example=i,this.schema=n,this.depth=o,this.exampleGenerationStrategy=s,this.generateOptionalProperties=a,this.seenRefs=c;let u=s8u.get(r);u!=null?this.sharedState=u:(this.sharedState={mergedAllOfProperties:new WeakMap,mergeOnlyAllOfSchemas:new WeakMap},s8u.set(r,this.sharedState))}convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:typeof this.example<"u"?this.example:{},errors:[]};if(this.context.isReferenceObject(this.schema)){let n=this.schema.$ref;if(this.seenRefs.has(n))return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}}let t=this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(t!=null&&this.context.isReferenceObject(t))return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(t==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]};if(typeof t!="object")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Schema should be an object: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]};if("nullable"in t&&t.nullable===!0&&this.example===null)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.maybeConvertLiteralFernType(t);return r??(Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?this.convertNumber():t.type=="string"?this.convertString():t.type=="integer"?this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):t.type=="object"||t.properties!=null||t.allOf!=null?this.convertObject({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]})}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertBoolean(){let t=typeof this.example=="boolean";if(t)return{isValid:t,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.default:this.schema.default,n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs})?.const:this.schema.const;return typeof r=="boolean"||typeof n=="boolean"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n??r,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;if(r)return{isValid:r,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let n=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return n!==void 0&&t.enum?.includes(n)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:r,coerced:!1,usedProvidedExample:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};let t=Number(this.example);if(!isNaN(t))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.default;return typeof n=="number"?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.adjustNumberToConstraints(this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,r),errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}adjustNumberToConstraints(t,r){if(r==null)return this.context.logger.debug("[ExampleConverter.adjustNumberToConstraints] Schema object is null, returning original number","number:",t.toString()),t;let{minimum:n,maximum:i,exclusiveMinimum:o,exclusiveMaximum:s}=r,a;o!=null?typeof o=="boolean"?a=n!=null?n+Math.max(Number.EPSILON,Math.abs(n)*1e-10):void 0:a=o+Math.max(Number.EPSILON,Math.abs(o)*1e-10):n!=null&&(a=n);let c;return s!=null?typeof s=="boolean"?c=i!=null?i-Math.max(Number.EPSILON,Math.abs(i)*Number.EPSILON):void 0:c=s-Math.max(Number.EPSILON,Math.abs(s)*Number.EPSILON):i!=null&&(c=i),a!==void 0&&c!==void 0?(t<a||t>c)&&(t=a+(c-a)/2):a!==void 0&&t<a?t=a+Math.abs(a*.1):c!==void 0&&t>c&&(t=c-Math.abs(c*.1)),Number(Number(t).toPrecision(3))}convertString(){if(typeof this.example=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null)return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:String(this.example),errors:[]};let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;if(typeof t=="string")return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]};let r=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):this.schema,n=r?.format==="date"?this.EXAMPLE_DATE:r?.format==="date-time"?this.EXAMPLE_DATE_TIME:this.EXAMPLE_STRING;return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??n,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:this.example,errors:[]};if(typeof this.example=="string"){let r=Number(this.example);if(!isNaN(r)&&Number.isInteger(r))return{isValid:!0,coerced:!0,usedProvidedExample:!0,validExample:r,errors:[]}}let t=this.context.isReferenceObject(this.schema)?this.context.resolveMaybeReference({schemaOrReference:this.schema,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0})?.default:this.schema.default;return typeof t=="number"&&Number.isInteger(t)?{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:t,errors:[]}:{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=this.example==null,n=this.example??t.example,o=(Array.isArray(n)?n:[n]).map(c=>new e({breadcrumbs:[...this.breadcrumbs,"items"],context:this.context,schema:t.items,example:c,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),s=o.every(c=>c?.isValid??!1)&&!r,a=!r&&o.some(c=>c.usedProvidedExample);return{isValid:s,coerced:!1,usedProvidedExample:a,validExample:o.map(c=>c.validExample),errors:s?[]:o.flatMap(c=>c.errors)}}convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null&&t.allOf==null)return{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,n=this.example===void 0&&this.canGenerateFromMergedAllOf(t),{mergedProperties:i,mergedRequired:o}=this.mergeAllOfProperties(t,new Set,0,n),s=Object.entries(i).map(([y,I])=>{if(typeof I!="object")return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if(this.isDeprecatedProperty(I)&&!this.isRequiredProperty({key:y,resolvedSchema:t}))return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&"writeOnly"in I&&I.writeOnly===!0)return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("readOnly"in I&&I.readOnly===!0&&this.exampleGenerationStrategy==="request")return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};if("writeOnly"in I&&I.writeOnly===!0&&this.exampleGenerationStrategy==="response")return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}};let x=lkm(I),v=!(y in r)||!x&&r[y]==null||x&&r[y]===void 0,S=!o.includes(y);if(v&&S){if(this.example===void 0&&this.generateOptionalProperties){let B=this.maybeResolveSchemaExample(I),R=new e({breadcrumbs:[...this.breadcrumbs,y],context:this.context,schema:I,example:B,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()});return{key:y,result:R.convert()}}return{key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:void 0,errors:[]}}}else{let B=r[y],R=B!==void 0?B:this.maybeResolveSchemaExample(I),O=new e({breadcrumbs:[...this.breadcrumbs,y],context:this.context,schema:I,example:R,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();return{key:y,result:O}}}),a=n?[]:(t.allOf??[]).map((y,I)=>{let x=this.context.resolveMaybeReference({schemaOrReference:y,breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],skipErrorCollector:!0});return x&&this.isConstraintOnlySchema(x)?{isValid:!0,coerced:!1,usedProvidedExample:this.example!==void 0,validExample:this.example,errors:[]}:new e({breadcrumbs:[...this.breadcrumbs,`allOf[${I}]`],context:this.context,schema:{...t,...y,allOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()}),c=this.example!==void 0&&(s.some(({result:y})=>y.usedProvidedExample)||a.some(y=>y.usedProvidedExample)),u=Object.fromEntries(s.map(({key:y,result:I})=>[y,I.validExample]).filter(([y,I])=>I!==void 0));for(let y of a)if(typeof y.validExample=="object"&&y.validExample!==null){let I=y.validExample,x=Object.fromEntries(Object.entries(I).filter(([v,S])=>S!==void 0));for(let[v,S]of Object.entries(x))(!(v in u)||u[v]==null)&&(u[v]=S)}let l=[],p=this.collectAllPropertyKeys(t),d=Object.keys(r).filter(y=>!p.has(y)),f=this.schemaHasPatternProperties(t),m=f?d:[],g=f?[]:d;if(m.forEach(y=>{l.push({key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[y],errors:[]}})}),g.length>0)if(t.additionalProperties===!1)g.forEach(y=>{let I=[...this.breadcrumbs,y].join("."),x={message:`Found unexpected property '${y}' in example. This property does not exist in the schema${I?` at path: ${I}`:""}`,path:[...this.breadcrumbs,y]};l.push({key:y,result:{isValid:!1,coerced:!1,usedProvidedExample:!0,validExample:void 0,errors:[x]}})});else if(t.additionalProperties===!0||t.additionalProperties===void 0)g.forEach(y=>{l.push({key:y,result:{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:r[y],errors:[]}})});else{let y=t.additionalProperties;g.forEach(I=>{let v=new e({breadcrumbs:[...this.breadcrumbs,I],context:this.context,schema:y,example:r[I],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();l.push({key:I,result:v})})}for(let{key:y,result:I}of l)I.validExample!==void 0&&u[y]===void 0&&(u[y]=I.validExample);let A=s.every(y=>y.result.isValid)&&a.every(y=>y.isValid)&&l.every(({result:y})=>y.isValid);if(Object.keys(u).length===0){let y=a.find(I=>I.validExample!==void 0&&(typeof I.validExample!="object"||I.validExample===null));y&&(u=y.validExample)}return{isValid:A,coerced:!1,usedProvidedExample:c,validExample:u,errors:[...s.flatMap(({result:y})=>y.errors),...a.flatMap(y=>y.errors),...l.flatMap(({result:y})=>y.errors)]}}convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};if(t.type.length===1)return new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();let r=t.type.map((a,c)=>new e({breadcrumbs:[...this.breadcrumbs,`type[${c}]`],context:this.context,schema:{...t,type:a},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert()),n=r.some(a=>a?.isValid??!1),o=r.find(a=>a.isValid)?.validExample??r[0]?.validExample??null,s=r.some(a=>a.usedProvidedExample);return{isValid:n,coerced:!1,usedProvidedExample:s,validExample:o,errors:n?[]:r.flatMap(a=>a?.errors??[])}}convertUnion({resolvedSchema:t,unionType:r}){let n=r==="oneOf"?t.oneOf:t.anyOf;if(!(r in t)||n==null)return{isValid:!1,coerced:!1,usedProvidedExample:!1,validExample:null,errors:[]};let i=this.example!==void 0?this.example:this.maybeResolveSchemaExample(t);if(this.example===void 0){let d=[];for(let m of n){if(!m)continue;let g=this.context.resolveMaybeReference({schemaOrReference:m,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});g&&d.push(g)}if(d.length>0&&d.every(m=>pkm(m))){let m=d.findIndex(g=>a8u(g)!==void 0);if(m!==-1){let g=n[m],A=d[m];if(g&&A){let y=a8u(A),x=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${m}]`],context:this.context,schema:r==="oneOf"?{...t,...g,oneOf:void 0}:g,example:y,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(x.isValid)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:x.validExample,errors:[]}}}}}let o=[],s=null,a=null;for(let d=0;d<n.length;d++){let f=n[d];if(!f)continue;let m=r==="oneOf"?{...t,...f,oneOf:void 0}:f,g=i!==void 0?i:this.maybeResolveSchemaExample(m),y=new e({breadcrumbs:[...this.breadcrumbs,`${r}[${d}]`],context:this.context,schema:m,example:g,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties,exampleGenerationStrategy:this.exampleGenerationStrategy,seenRefs:this.getMaybeUpdatedSeenRefs()}).convert();if(y.isValid&&!y.coerced&&y.usedProvidedExample)return{isValid:!0,coerced:!1,usedProvidedExample:!0,validExample:y.validExample,errors:[]};if(y.isValid&&!y.coerced&&this.example===void 0)return{isValid:!0,coerced:!1,usedProvidedExample:y.usedProvidedExample,validExample:y.validExample,errors:[]};o.push(y),y.isValid&&y.usedProvidedExample&&a===null&&(a=y),y.isValid&&s===null&&(s=y)}let c=a??s,u=c!==null,l=c?.validExample??o[0]?.validExample,p=c?.usedProvidedExample??!1;return{isValid:u,coerced:!1,usedProvidedExample:p,validExample:l,errors:u?[]:o.flatMap(d=>d.errors)}}convertOneOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"oneOf"})}convertAnyOf({resolvedSchema:t}){return this.convertUnion({resolvedSchema:t,unionType:"anyOf"})}getMaybeUpdatedSeenRefs(){let t=new Set(this.seenRefs);return this.context.isReferenceObject(this.schema)&&t.add(this.schema.$ref),t}maybeResolveSchemaExample(t){if("example"in t)return t.example;if("examples"in t){let n=t.examples;if(Array.isArray(n)&&n.length>0)return n[0];if(n!=null&&typeof n=="object")return Object.values(n)[0]}let r=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(r!=null){if("example"in r)return r.example;if("examples"in r){let n=r.examples;return Array.isArray(n)&&n.length>0?n[0]:Object.values(n??{})[0]}}}maybeConvertLiteralFernType(t){let r=t["x-fern-type"];if(typeof r!="string")return;let n=r.match(ckm);if(n!=null){if(n[1]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[1],errors:[]};if(n[2]!=null)return{isValid:!0,coerced:!1,usedProvidedExample:!1,validExample:n[2]==="true",errors:[]}}}mergeAllOfProperties(t,r=new Set,n=0,i=!1){if(i){let p=this.sharedState.mergedAllOfProperties.get(t)?.get(n);if(p!=null)return p}let o=t.properties??{},s=t.required??[];if(n>this.MAX_DEPTH||t.allOf==null||t.allOf.length===0){let p={mergedProperties:o,mergedRequired:s};return i&&this.cacheMergedAllOfProperties(t,n,p),p}let a={},c=new Set(s);for(let p of t.allOf){let d=this.context.resolveMaybeReference({schemaOrReference:p,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(d==null)continue;let f=this.context.isReferenceObject(p)?p.$ref:void 0;if(!(f!=null&&r.has(f))){if(d.allOf!=null&&d.allOf.length>0){let m=new Set(r);f!=null&&m.add(f);let g=this.mergeAllOfProperties(d,m,n+1,i);for(let A of g.mergedRequired)c.add(A);for(let[A,y]of Object.entries(g.mergedProperties))if(typeof y=="object"&&y!==null){let I=a[A];I!=null&&bVe(I)&&bVe(y)?a[A]={...I,...y}:a[A]=y}continue}if(d.required!=null)for(let m of d.required)c.add(m);if(d.properties!=null){for(let[m,g]of Object.entries(d.properties))if(typeof g=="object"&&g!==null){let A=a[m];A!=null&&bVe(A)&&bVe(g)?a[m]={...A,...g}:a[m]=g}}}}let u={...o};for(let[p,d]of Object.entries(u)){let f=a[p];if(f==null||!bVe(d))continue;let m="$ref"in f?this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0}):f;m!=null&&(u[p]={...m,...d})}for(let[p,d]of Object.entries(a))p in u||(u[p]=d);let l={mergedProperties:u,mergedRequired:[...c]};return i&&this.cacheMergedAllOfProperties(t,n,l),l}cacheMergedAllOfProperties(t,r,n){let i=this.sharedState.mergedAllOfProperties.get(t);i!=null?i.set(r,n):this.sharedState.mergedAllOfProperties.set(t,new Map([[r,n]]))}canGenerateFromMergedAllOf(t,r=new WeakSet){if(t.allOf==null||t.allOf.length===0||!this.isMergeOnlyObjectSchema(t))return!1;let n=this.sharedState.mergeOnlyAllOfSchemas.get(t);if(n!=null)return n;if(r.has(t))return!1;r.add(t);let i=t.allOf.every(o=>{let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return s==null||!this.isMergeOnlyObjectSchema(s)?!1:s.allOf==null||s.allOf.length===0?!0:this.canGenerateFromMergedAllOf(s,r)});return r.delete(t),this.sharedState.mergeOnlyAllOfSchemas.set(t,i),i}isMergeOnlyObjectSchema(t){return t.type!=null&&t.type!=="object"||t.type==null&&t.properties==null&&t.allOf==null?!1:Object.keys(t).every(r=>ukm.has(r))}isConstraintOnlySchema(t){if(typeof t!="object"||t===null||t.type!==void 0||t.properties!==void 0||t.allOf!==void 0||t.oneOf!==void 0||t.anyOf!==void 0||"items"in t||t.additionalProperties!==void 0||t.enum!==void 0||t.const!==void 0)return!1;let r=new Set(["required","description","title","deprecated","readOnly","writeOnly","nullable","example","examples","default","minLength","maxLength","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minItems","maxItems","uniqueItems","pattern","format"]),n=Object.keys(t);return n.length>0&&n.every(i=>r.has(i))}isDeprecatedProperty(t){return t!=null&&"availability"in t&&t.availability==="deprecated"}isRequiredProperty({key:t,resolvedSchema:r}){return r.required?.includes(t)??!1}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}for(let i of[...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}return n}schemaHasPatternProperties(t,r=new Set){let n=t.patternProperties;if(n&&typeof n=="object"&&Object.keys(n).length>0)return!0;for(let i of[...t.allOf??[],...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)&&(r.add(s),this.schemaHasPatternProperties(o,r)))return!0}}return!1}}});function c8u(e){return SC({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return en.primitive({v1:"BASE_64",v2:xi.base64({})});case"BOOLEAN":return en.primitive({v1:"BOOLEAN",v2:xi.boolean({default:void 0})});case"DATE":return en.primitive({v1:"DATE",v2:xi.date({})});case"DATE_TIME":return en.primitive({v1:"DATE_TIME",v2:xi.dateTime({})});case"DATE_TIME_RFC_2822":return en.primitive({v1:"DATE_TIME_RFC_2822",v2:xi.dateTimeRfc2822({})});case"FLOAT":return en.primitive({v1:"FLOAT",v2:xi.float({default:void 0,validation:void 0})});case"DOUBLE":return en.primitive({v1:"DOUBLE",v2:xi.double({default:void 0,validation:void 0})});case"UINT":return en.primitive({v1:"UINT",v2:xi.uint({default:void 0,validation:void 0})});case"UINT_64":return en.primitive({v1:"UINT_64",v2:xi.uint64({default:void 0,validation:void 0})});case"INTEGER":return en.primitive({v1:"INTEGER",v2:xi.integer({default:void 0,validation:void 0})});case"LONG":return en.primitive({v1:"LONG",v2:xi.long({default:void 0,validation:void 0})});case"STRING":return en.primitive({v1:"STRING",v2:xi.string({default:void 0,validation:void 0})});case"UUID":return en.primitive({v1:"UUID",v2:xi.uuid({})});case"BIG_INTEGER":return en.primitive({v1:"BIG_INTEGER",v2:xi.bigInteger({default:void 0})});default:return}},unknown:()=>en.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return en.container(Ts.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return en.container(Ts.list(t))},optional:t=>{if(t!=null)return en.container(Ts.optional(t))},nullable:t=>{if(t!=null)return en.container(Ts.nullable(t))},set:t=>{if(t!=null)return en.container(Ts.set(t))},literal:t=>en.container(Ts.literal(t._visit({string:r=>cE.string(r),boolean:r=>cE.boolean(r),_other:()=>{throw new T({message:"Unexpected literal type",code:T.Code.InternalError})}}))),named:()=>{}}})}var u8u=h(()=>{"use strict";Io();Wn();Dt()});var pwe,oYr=h(()=>{"use strict";Wn();hc();rs();pwe=class extends co{schema;maybeFernEnum;forwardCompatible;constructor({context:t,breadcrumbs:r,schema:n,maybeFernEnum:i,forwardCompatible:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.maybeFernEnum=i,this.forwardCompatible=o??!1}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(i=>typeof i=="string"||typeof i=="number").map(i=>{let o=i.toString(),s=this.maybeFernEnum?.[o],a=s?.name??o;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:a,wireValue:o}),docs:s?.description,availability:void 0,casing:s?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let n=this.context.getAsString(this.schema.default);return{type:mc.enum({default:n!=null?r.find(i=>ur(i.name)===n):void 0,values:r,forwardCompatible:this.forwardCompatible||void 0})}}}});var sYr,l8u=h(()=>{"use strict";Wn();rs();ult();EVe();sYr=class extends co{schemaOrReferenceOrBoolean;constructor({context:t,breadcrumbs:r,schemaOrReferenceOrBoolean:n}){super({context:t,breadcrumbs:r}),this.schemaOrReferenceOrBoolean=n}convert(){let t=this.tryConvertUnknownMap();if(t!=null)return t;let r=this.tryConvertTypedMap();if(r!=null)return r}tryConvertUnknownMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean"){let t=en.container(Ts.map({keyType:co.STRING,valueType:en.unknown()}));return{type:mc.alias({aliasOf:t,resolvedType:t}),referencedTypes:new Set,inlinedTypes:{}}}}tryConvertTypedMap(){if(typeof this.schemaOrReferenceOrBoolean=="boolean")return;let r=new rO({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schemaOrReferenceOrBoolean}).convert();if(r!=null){let n=en.container(Ts.map({keyType:co.STRING,valueType:r.type})),i=new Set;for(let o of r.schema?.typeDeclaration.referencedTypes??[])i.add(o);for(let o of Object.keys(r.inlinedTypes))i.add(o);return F4(r.type,i),{type:mc.alias({aliasOf:n,resolvedType:n}),referencedTypes:i,inlinedTypes:r.inlinedTypes}}}}});function d8u(e,t,r){let n=m8u(t,r),i={};for(let o of n)i=VGo(i,o);return Akm(i,e),i}function m8u(e,t,r){let n=r??new Set,i=[];for(let o of e)if(Array.isArray(o.allOf)&&o.allOf.length>0){let{allOf:s,...a}=o,c=[];for(let u of s)if("$ref"in u){if(t==null)continue;let l=u.$ref;if(n.has(l))continue;n.add(l);let p=t(u);p!=null&&c.push(p)}else c.push(u);i.push(...m8u(c,t,n)),Object.keys(a).length>0&&i.push(a)}else i.push(o);return i}function VGo(e,t){let r={...e};for(let[n,i]of Object.entries(t)){if(i===void 0||hkm.includes(n))continue;let o=r[n];if(n==="required"){let s=Array.isArray(o)?o:[],a=Array.isArray(i)?i:[];r[n]=[...new Set([...s,...a])];continue}if(n==="properties"){r[n]=gkm(o??{},i);continue}if(n==="items"){Fr(o)&&Fr(i)?r[n]=VGo(o,i):r[n]=i;continue}if(p8u.includes(n)){Fr(o)&&Fr(i)?r[n]=h8u(o,i):r[n]=i;continue}if(f8u.includes(n)){r[n]=!!o||!!i;continue}if(dkm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.max(o,i):r[n]=i;continue}if(mkm.includes(n)){typeof o=="number"&&typeof i=="number"?r[n]=Math.min(o,i):r[n]=i;continue}r[n]=i}return r}function gkm(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];Fr(o)&&Fr(i)?r[n]=VGo(o,i):r[n]=i}return r}function h8u(e,t){let r={...e};for(let[n,i]of Object.entries(t)){let o=r[n];Fr(o)&&Fr(i)?r[n]=h8u(o,i):r[n]=i}return r}function Akm(e,t){for(let r of fkm){let n=t[r];n!=null&&(e[r]=n)}for(let r of p8u){let n=t[r];n!=null&&(e[r]=n)}for(let r of f8u)t[r]===!0&&(e[r]=!0)}var fkm,p8u,f8u,dkm,mkm,hkm,g8u=h(()=>{"use strict";ct();fkm=["description","title","format","type","discriminator","xml","externalDocs","extensions"],p8u=["example","default"],f8u=["deprecated","readOnly","writeOnly","uniqueItems","nullable"],dkm=["minimum","exclusiveMinimum","minLength","minItems","minProperties"],mkm=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],hkm=["allOf","oneOf","anyOf"]});var llt,GGo=h(()=>{"use strict";ct();Wn();hc();iYr();rs();ult();llt=class extends co{schema;xmlEncoding;constructor({context:t,breadcrumbs:r,schema:n,id:i}){super({context:t,breadcrumbs:r}),this.schema=n,this.xmlEncoding=new alt({breadcrumbs:this.breadcrumbs,schema:n,fallbackName:i,context:t}).convert()}convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:mc.object({properties:[],extends:[],extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:{},inlinedTypes:{},referencedTypes:new Set,xmlEncoding:this.xmlEncoding};let{convertedProperties:r,inlinedTypesFromProperties:n,referencedTypes:i,propertiesByAudience:o}=IVe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null}),s=[],a=i,c=this.schema.required!=null&&this.schema.required.length>0,u=n,l=o,p={};for(let d of this.schema.allOf??[])if(this.context.isReferenceObject(d)){let f=this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs});if(f?.properties!=null)for(let[m,g]of Object.entries(f.properties))!this.context.isReferenceObject(g)&&p[m]==null&&(p[m]=g)}for(let[d,f]of(this.schema.allOf??[]).entries()){let m=[...this.breadcrumbs,"allOf",d.toString()],g,A=!1;if(this.context.isReferenceObject(f)){let R=this.context.resolveMaybeReference({schemaOrReference:f,breadcrumbs:m});if(R==null){this.context.logger.debug?.(`[ObjectSchemaConverter] allOf[${d}] reference could not be resolved. Skipping: ${JSON.stringify(f)}`);continue}if(g=R,typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0),!c||Object.keys(g.properties??{}).every(D=>!this.schema.required?.includes(D))){this.addTypeReferenceToExtends({reference:f,breadcrumbs:m,extends_:s,referencedTypes:a});continue}}else g=f,A=!0;typeof g.additionalProperties=="boolean"&&g.additionalProperties&&(t=!0);let y=g.oneOf??g.anyOf;if(y!=null&&g.type==null&&g.properties==null){let R=new Set(r.map(D=>ur(D.name)));for(let[D,O]of y.entries()){let z=[...m,g.oneOf!=null?"oneOf":"anyOf",D.toString()],Y=this.context.isReferenceObject(O)?this.context.resolveMaybeReference({schemaOrReference:O,breadcrumbs:z}):O;if(Y==null)continue;let te={};for(let[Re,ce]of Object.entries(Y.properties??{}))!this.context.isReferenceObject(ce)&&"not"in ce||(te[Re]=ce);let ee=Object.keys(te).filter(Re=>!R.has(Re));if(ee.length===0)continue;let se={};for(let Re of ee){let ce=te[Re];ce!=null&&(se[Re]=ce,R.add(Re))}let{convertedProperties:le,inlinedTypesFromProperties:oe,referencedTypes:me,propertiesByAudience:Se}=IVe({properties:se,required:[],breadcrumbs:z,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...le),u={...u,...oe},l={...l,...Se},me.forEach(Re=>{a.add(Re)})}continue}let I=g.properties??{};if(A){I={};for(let[R,D]of Object.entries(g.properties??{})){let O=p[R];O!=null&&!this.context.isReferenceObject(D)?I[R]={...O,...D}:I[R]=D}}let{convertedProperties:x,inlinedTypesFromProperties:v,referencedTypes:S,propertiesByAudience:B}=IVe({properties:I,required:[...this.schema.required??[],...g.required??[],...mfe(g)],breadcrumbs:m,context:this.context,errorCollector:this.context.errorCollector,withinXmlElement:this.xmlEncoding!=null});r.push(...x),u={...u,...v},l={...l,...B},S.forEach(R=>{a.add(R)})}for(let d of Object.keys(u))a.add(d);return{type:mc.object({properties:r,extends:s.map(d=>this.context.typeReferenceToDeclaredTypeName(d)).filter(ga),extendedProperties:[],extraProperties:t,deferredUnionBaseProperties:void 0}),propertiesByAudience:l,referencedTypes:a,inlinedTypes:u,xmlEncoding:this.xmlEncoding}}addTypeReferenceToExtends({reference:t,breadcrumbs:r,extends_:n,referencedTypes:i}){let o=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:r});o.ok&&n.push(o.reference);let s=this.context.getTypeIdFromSchemaReference(t);s!=null&&i.add(s)}}});function ykm(e){return e.type==="union"&&e.types.length===0}function bkm({schema:e,discriminantProperty:t}){let r=e.properties?.[t];if(r==null||"$ref"in r)return;let n=r.const;if(typeof n=="string")return n;if(r.enum?.length===1&&typeof r.enum[0]=="string")return r.enum[0]}var vVe,qGo=h(()=>{"use strict";Wn();QGo();MGo();LGo();rs();ult();oYr();aYr();EVe();vVe=class extends co{schema;id;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlinedTypes:o}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i}convert(){if(this.shouldConvertAsNullableSchemaOrReference())return this.convertAsNullableSchemaOrReference();if(new ilt({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!1)return this.convertAsUndiscriminatedUnion();if(this.schema.discriminator!=null){let n=this.convertAsDiscriminatedUnion();return n!=null&&!ykm(n.type)?n:this.convertAsUndiscriminatedUnion()??n}if(this.context.settings.inferForwardCompatible){let n=this.convertAsOpenEndedEnum();if(n!=null)return n}return this.convertAsUndiscriminatedUnion()}convertAsOpenEndedEnum(){let t=this.schema.oneOf??this.schema.anyOf;if(t==null||t.length!==2)return;let r,n=!1;for(let c of t){let u;if(this.context.isReferenceObject(c)){let l=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});l.resolved&&(u=l.value)}else u=c;u!=null&&(u.enum!=null&&u.enum.length>1&&(u.type==="string"||u.type==null)?r=u:u.type==="string"&&u.enum==null&&(n=!0))}if(r==null||!n)return;let o=new slt({breadcrumbs:this.breadcrumbs,schema:r,context:this.context}).convert(),a=new pwe({context:this.context,breadcrumbs:this.breadcrumbs,schema:r,maybeFernEnum:o,forwardCompatible:!0}).convert();if(a!=null)return{...a,referencedTypes:new Set,inlinedTypes:{}}}getEnclosingComponentRef(){let[t,r,n]=this.breadcrumbs;return t==="components"&&r==="schemas"&&n!=null?`#/components/schemas/${n}`:void 0}filterDiscriminantFromSchema(t,r){if(t.properties==null||!(r in t.properties))return t;let{[r]:n,...i}=t.properties,o=t.required?.filter(s=>s!==r);return{...t,properties:i,required:o}}getVariants(t){let r=this.schema.discriminator?.mapping;if(r!=null){let o=[];for(let[s,a]of Object.entries(r)){let c=this.context.getTypeIdFromSchemaReference({$ref:a});c!=null&&o.push({discriminant:s,typeId:c,ref:a,schema:this.resolveVariantSchema({$ref:a}),breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",s]})}return o}let n=this.schema.oneOf??this.schema.anyOf??[],i=[];for(let[o,s]of n.entries()){let a=this.resolveVariantSchema(s),c=a!=null?bkm({schema:a,discriminantProperty:t}):void 0;if(!this.context.isReferenceObject(s)){if(c==null)return[];i.push({discriminant:c,typeId:this.context.convertBreadcrumbsToName([`${this.id}_${o}`]),schema:a,breadcrumbs:[...this.breadcrumbs,`oneOf[${o}]`]});continue}let u=s.$ref,l=u.split("/").pop(),p=this.context.getTypeIdFromSchemaReference(s),d=c??l;if(p==null||d==null)return[];i.push({discriminant:d,typeId:p,ref:u,schema:a,breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",d]})}return i}resolveVariantSchema(t){if(!this.context.isReferenceObject(t))return t;let r=this.context.resolveReference({reference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});return r.resolved?r.value:void 0}convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=this.schema.discriminator.propertyName,r=[],n=new Set,i={};for(let{discriminant:l,typeId:p,ref:d,schema:f,breadcrumbs:m}of this.getVariants(t)){let g=d!=null?{$ref:d}:f,A=p!=null&&this.context.discriminatedVariantsInProgress.has(p),y=d!=null&&d===this.getEnclosingComponentRef(),I=f?.properties!=null&&t in f.properties&&!((A||y)&&d!=null);if(I&&f!=null&&(g=this.filterDiscriminantFromSchema(f,t)),g==null)continue;let x=new rO({context:this.context,schemaOrReference:g,schemaIdOverride:p??void 0,breadcrumbs:m});p!=null&&n.add(p);let v=I&&p!=null&&!A;v&&this.context.discriminatedVariantsInProgress.add(p);let S;try{S=x.convert()}finally{v&&this.context.discriminatedVariantsInProgress.delete(p)}if(S?.type!=null&&p!=null){for(let Y of Object.keys(S?.inlinedTypes??{}))n.add(Y);for(let Y of S.schema?.typeDeclaration.referencedTypes??[])n.add(Y);let B=this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),R=d?.split("/").pop()??p,D=f?.title,O=f?.description,z=D??l??R;S.schema?.typeDeclaration!=null&&D!=null&&(S.schema.typeDeclaration.name.displayName=D),r.push({docs:O,discriminantValue:B,availability:S.availability,displayName:z,shape:iT.samePropertiesAsObject({typeId:p,name:this.context.casingsGenerator.generateName(R),fernFilepath:{allParts:[],packagePath:[],file:void 0},displayName:z})}),i={...i,...S.inlinedTypes}}}let{convertedProperties:o,referencedTypes:s,inlinedTypesFromProperties:a}=IVe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});n=new Set([...n,...s]);let c=[];for(let[l,p]of(this.schema.allOf??[]).entries()){let d=[...this.breadcrumbs,"allOf",l.toString()];if(this.context.isReferenceObject(p)){let f=this.context.convertReferenceToTypeReference({reference:p,breadcrumbs:d});if(f.ok){let g=this.context.typeReferenceToDeclaredTypeName(f.reference);g!=null&&c.push(g)}let m=this.context.getTypeIdFromSchemaReference(p);m!=null&&n.add(m);continue}}for(let l of Object.keys({...i,...a}))n.add(l);let u=new olt({context:this.context,breadcrumbs:[...this.breadcrumbs,"discriminator"],node:this.schema.discriminator});return{type:mc.union({baseProperties:o,inheritedBaseProperties:[],discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:c,types:r,default:void 0,discriminatorContext:u.convert()}),referencedTypes:n,inlinedTypes:{...i,...a}}}convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r=new Set,n={};for(let[a,c]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){if(this.context.isReferenceObject(c)){let g;if(this.context.isReferenceObjectWithIdentifier(c))g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:c.summary??c.title??c.name??c.messageId,displayNameOverrideSource:"reference_identifier"});else{let y=this.getDiscriminatorKeyForRef(c);y!=null?g=this.context.convertReferenceToTypeReference({reference:c,displayNameOverride:y,displayNameOverrideSource:"discriminator_key"}):g=this.context.convertReferenceToTypeReference({reference:c,breadcrumbs:this.breadcrumbs})}if(g.ok){let y=this.context.resolveReference({reference:c,breadcrumbs:this.breadcrumbs}),I=y.resolved?y.value.description:void 0;t.push({type:g.reference,docs:I})}let A=this.context.getTypeIdFromSchemaReference(c);A!=null&&r.add(A);continue}let l=Object.keys(this.schema.properties??{}).length>0?void 0:this.extendSubSchema(c),p=this.context.convertBreadcrumbsToName([`${this.id}_${a}`]),d=c.title,m=new fwe({context:this.context,id:p,nameOverride:d,breadcrumbs:[...this.breadcrumbs,`oneOf[${a}]`],schema:l??c}).convert();if(m!=null){let g=m.convertedSchema.typeDeclaration.shape;if(g.type==="alias"&&this.typeReferenceIsWrappedPrimitive(g.aliasOf))t.push({type:g.aliasOf,docs:c.description});else if(g.type==="object"&&g.properties.length===0&&g.extends.length===0)t.push({type:en.container(Ts.map({keyType:co.STRING,valueType:en.unknown()})),docs:c.description});else{t.push({type:this.context.createNamedTypeReference(p,d),docs:c.description});let A=this.context.getNamespacedSchemaId(p);n={...n,...m.inlinedTypes,[A]:m.convertedSchema},r.add(A);for(let y of Object.keys(m.inlinedTypes))r.add(y)}m.convertedSchema.typeDeclaration.referencedTypes.forEach(A=>{r.add(A)})}}let{convertedProperties:i,referencedTypes:o,inlinedTypesFromProperties:s}=IVe({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});for(let a of Object.keys(s))r.add(a);for(let a of o)r.add(a);return{type:mc.undiscriminatedUnion({members:t,baseProperties:i.length>0?i:void 0}),referencedTypes:r,inlinedTypes:{...n,...s}}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>t&&typeof t=="object"&&"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let n=t.filter(i=>!(typeof i=="object"&&i!==null&&"type"in i&&i.type==="null"));if(n.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types`,path:this.breadcrumbs});return}return n.length===1?{...this.schema,[r]:void 0,...n[0]}:{...this.schema,[r]:n}}convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let n=new rO({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(n==null)return;let i=this.wrapInNullable(n.type);return{type:mc.alias({aliasOf:i,resolvedType:i}),referencedTypes:n.schema?.typeDeclaration.referencedTypes??new Set,inlinedTypes:n.inlinedTypes}}typeReferenceIsWrappedPrimitive(t){switch(t.type){case"container":return this.containerTypeIsWrappedPrimitive(t.container);case"named":return!1;case"primitive":return!0;case"unknown":return!0;default:return!1}}containerTypeIsWrappedPrimitive(t){switch(t.type){case"list":return this.typeReferenceIsWrappedPrimitive(t.list);case"map":return this.typeReferenceIsWrappedPrimitive(t.keyType)&&this.typeReferenceIsWrappedPrimitive(t.valueType);case"nullable":return this.typeReferenceIsWrappedPrimitive(t.nullable);case"optional":return this.typeReferenceIsWrappedPrimitive(t.optional);case"set":return this.typeReferenceIsWrappedPrimitive(t.set);case"literal":return!0;default:return!1}}wrapInNullable(t){return en.container(Ts.nullable(t))}mergeIntoObjectSchema(t,r){return{...t,properties:{...r,...t.properties??{}}}}extendSubSchema(t){if(Object.entries(this.schema.properties??{}).length===0)return t;if(t.type==="object")return this.mergeIntoObjectSchema(t,this.schema.properties??{});this.context.isObjectSchemaType(t)||this.context.errorCollector.collect({message:"Received additional object properties for oneOf/anyOf that are not objects",path:this.breadcrumbs})}getDiscriminatorKeyForRef(t){return Object.entries(this.schema.discriminator?.mapping??{}).find(([r,n])=>n===t.$ref)?.[0]}}});var plt,WGo=h(()=>{"use strict";Wn();rs();plt=class extends co{schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);if(t!=null)return en.container(Ts.literal(cE.string(t)));if(this.schema.format==="date-time-rfc-2822")return en.primitive({v1:As.DateTimeRfc2822,v2:xi.dateTimeRfc2822({})});if(this.context.settings.typeDatesAsStrings===!1){if(this.schema.format==="date")return en.primitive({v1:As.Date,v2:xi.date({})});if(this.schema.format==="date-time")return en.primitive({v1:As.DateTime,v2:xi.dateTime({})})}return en.primitive({v1:"STRING",v2:xi.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":switch(this.schema.format){case"double":return en.primitive({v1:"DOUBLE",v2:xi.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return en.primitive({v1:"FLOAT",v2:xi.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return en.primitive({v1:"INTEGER",v2:xi.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return en.primitive({v1:"LONG",v2:xi.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return en.primitive({v1:"UINT",v2:xi.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return en.primitive({v1:"UINT_64",v2:xi.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return en.primitive({v1:"DOUBLE",v2:xi.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"integer":switch(this.schema.format){case"double":return en.primitive({v1:"DOUBLE",v2:xi.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return en.primitive({v1:"FLOAT",v2:xi.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return en.primitive({v1:"INTEGER",v2:xi.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return en.primitive({v1:"LONG",v2:xi.long({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint32":return en.primitive({v1:"UINT",v2:xi.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return en.primitive({v1:"UINT_64",v2:xi.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return en.primitive({v1:"INTEGER",v2:xi.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?en.container(Ts.literal(cE.boolean(t))):en.primitive({v1:"BOOLEAN",v2:xi.boolean({default:this.context.getAsBoolean(this.schema.default)})})}default:return}}getNumberValidation(t){let r=t.minimum,n=t.maximum,i,o;return typeof t.exclusiveMinimum=="boolean"?i=t.exclusiveMinimum:typeof t.exclusiveMinimum=="number"&&(r=t.exclusiveMinimum,i=!0),typeof t.exclusiveMaximum=="boolean"?o=t.exclusiveMaximum:typeof t.exclusiveMaximum=="number"&&(n=t.exclusiveMaximum,o=!0),{max:n,min:r,exclusiveMax:o,exclusiveMin:i,multipleOf:t.multipleOf}}getStringValidation(t){let r=t.format??(t.contentMediaType==="application/octet-stream"?"binary":void 0);return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:r}}}});function Ikm(e){let t=mfe(e);return t.length===0?e:{...e,required:[...new Set([...e.required??[],...t])]}}var Ekm,fwe,aYr=h(()=>{"use strict";ct();Wn();rs();ult();u8u();lwe();HGo();oYr();l8u();g8u();GGo();qGo();WGo();Ekm=["description","example","title","default","deprecated","readOnly","writeOnly","xml","externalDocs","extensions"],fwe=class e extends co{static MAX_DISTRIBUTED_VARIANTS=64;schema;id;inlined;audiences;nameOverride;visitedRefs;constructor({context:t,breadcrumbs:r,schema:n,id:i,inlined:o=!1,nameOverride:s,visitedRefs:a}){super({context:t,breadcrumbs:r}),this.schema=n,this.id=i,this.inlined=o,this.nameOverride=s,this.visitedRefs=a??new Set,this.audiences=this.context.getAudiences({operation:this.schema,breadcrumbs:this.breadcrumbs})??[]}convert(){let t=this.tryConvertFernTypeDeclaration();if(t!=null)return t;let r=this.tryConvertReferenceSchema();if(r!=null)return r;let n=this.tryConvertEnumSchema();if(n!=null)return n;let i=this.tryDistributeAllOfOverOneOf();if(i!=null)return i;let o=this.tryConvertSingularAllOfSchema();if(o!=null)return o;let s=this.tryConvertPrimitiveSchema();if(s!=null)return s;let a=this.tryConvertArraySchema();if(a!=null)return a;let c=this.tryConvertTypeArraySchema();if(c!=null)return c;let u=this.tryConvertSiblingAnyOfConstraint();if(u!=null)return u;let l=this.tryConvertSiblingOneOfConstraint();if(l!=null)return l;let p=this.tryConvertOneOfAnyOfSchema();if(p!=null)return p;let d=this.tryConvertMapSchema();if(d!=null)return d;let f=this.tryConvertDiscriminatorMappingSchema();if(f!=null)return f;let m=this.tryConvertObjectAllOfSchema();if(m!=null)return m;let g=this.tryConvertUntypedSchema();if(g!=null)return g;this.context.errorCollector.collect({message:`Failed to convert schema object: ${JSON.stringify(this.schema,null,2)}`,path:this.breadcrumbs})}tryConvertReferenceSchema(){if(!this.context.isReferenceObject(this.schema))return;let t=this.schema;if(this.visitedRefs.has(t.$ref)||t.$ref===`#/components/schemas/${this.id}`)return;let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(!r.ok)return;let n=new Set;return F4(r.reference,n),{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:mc.alias({aliasOf:r.reference,resolvedType:r.reference}),referencedTypes:n}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes??{}}}tryConvertEnumSchema(){if(!this.schema.enum?.length)return;let r=new qC.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),i=new pwe({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:r}).convert();if(i!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:i.type,referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertSingularAllOfSchema(){if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&this.schema.allOf?.length===1&&this.schema.allOf[0]!=null){let r=this.schema.allOf[0];if(this.context.isReferenceObject(r)){let i=r.$ref;if(this.visitedRefs.has(i))return}let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:this.breadcrumbs});if(n!=null){let i=this.context.isReferenceObject(r)?new Set([...this.visitedRefs,r.$ref]):this.visitedRefs,s=new e({context:this.context,breadcrumbs:[...this.breadcrumbs,"allOf","0"],schema:n,id:this.id,inlined:this.inlined,visitedRefs:i}).convert();if(s?.convertedSchema.typeDeclaration?.shape.type!=="object"){if(s!=null){let a=s.convertedSchema.typeDeclaration;this.schema.description!=null&&a.docs==null&&(a.docs=this.schema.description);let c=this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs});c!=null&&a.availability==null&&(a.availability=c)}return s}}}if(this.schemaOnlyHasAllowedKeys(["allOf","type","title"])&&Array.isArray(this.schema.allOf)&&this.schema.allOf.length>=1){let r=new Set,n=[],i=!1;for(let c of this.schema.allOf??[]){let u;if(this.context.isReferenceObject(c)){let p=c.$ref;if(this.visitedRefs.has(p)){i=!0;break}if(r.has(p))continue;r.add(p);let d=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(d==null)return;u=d}else u=c;let l=u.oneOf??u.anyOf;if(!this.context.isReferenceObject(c)&&l!=null&&u.type==null&&u.properties==null){let p={};for(let d of l){let f=this.context.isReferenceObject(d)?this.context.resolveMaybeReference({schemaOrReference:d,breadcrumbs:this.breadcrumbs}):d;if(f!=null)for(let[m,g]of Object.entries(f.properties??{}))!this.context.isReferenceObject(g)&&"not"in g||m in p||(p[m]=g)}Object.keys(p).length>0&&n.push({properties:p});continue}n.push(Ikm(u))}if(i)return;let o=d8u(this.schema,n,c=>{let u=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:this.breadcrumbs});if(!(u!=null&&this.context.isReferenceObject(u)))return u}),s=new Set([...this.visitedRefs,...r]);return new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:o,id:this.id,inlined:this.inlined,visitedRefs:s}).convert()}}tryDistributeAllOfOverOneOf(){if(!this.context.settings.preserveOneOfInAllOf)return;let t=this.schema.allOf;if(!Array.isArray(t)||t.length===0||this.schema.oneOf!=null||this.schema.anyOf!=null)return;let r=this.getDistributableUnions(t),n=r[0];if(n==null)return;let i=r.reduce((c,u)=>c*u.variants.length,1);if(i>e.MAX_DISTRIBUTED_VARIANTS){this.context.logger.warn(`Not distributing allOf over its ${r.length} unions at ${this.breadcrumbs.join(".")}: it would produce ${i} variants (max ${e.MAX_DISTRIBUTED_VARIANTS}).`);return}let o=t.filter((c,u)=>u!==n.index);(this.schema.properties!=null||this.schema.required!=null)&&o.push({type:"object",properties:this.schema.properties,required:this.schema.required});let s={...this.schema};return delete s.allOf,delete s.properties,delete s.required,new e({context:this.context,breadcrumbs:this.breadcrumbs,schema:{...s,oneOf:n.variants.map(c=>{let u=this.getVariantTitle(c);return{...u!=null?{title:u}:{},allOf:[c,...o]}})},id:this.id,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}getVariantTitle(t){return this.context.isReferenceObject(t)?this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs})?.title??t.$ref.split("/").pop():t.title}getDistributableUnions(t){let r=[];for(let[n,i]of t.entries()){let o=this.context.isReferenceObject(i)?this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs}):i;if(o==null||o.properties!=null||o.type!=null&&o.type!=="object"||o.discriminator!=null)continue;let s=o.oneOf??o.anyOf;s==null||s.length===0||r.push({index:n,variants:s})}return r}tryConvertPrimitiveSchema(){let r=new plt({context:this.context,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:mc.alias({aliasOf:r,resolvedType:r}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertArraySchema(){if(this.schema.type==="array"){let r=new flt({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:mc.alias({aliasOf:r.typeReference,resolvedType:r.typeReference}),referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertTypeArraySchema(){if(Array.isArray(this.schema.type)&&this.schema.type.length>0)return this.schema.type.length===1?this.schema.type=this.schema.type[0]:(this.schema.oneOf=this.schema.type.map(t=>({type:t})),this.schema.type=void 0),this.convert()}tryConvertSiblingAnyOfConstraint(){if(!this.context.settings.anyOfSiblingPropertiesAsObject||!$Me(this.schema))return;this.context.logger.debug(`Treating the anyOf at ${this.breadcrumbs.join(".")} as an "at least one of" constraint over its sibling properties rather than a union, and converting the schema as an object.`);let{anyOf:t,...r}=this.schema;return new e({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:r,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}tryConvertSiblingOneOfConstraint(){if(!eLe(this.schema)||new qC.FernDiscriminatedExtension({context:this.context,breadcrumbs:this.breadcrumbs,node:this.schema}).convert()===!0)return;this.context.logger.debug(`Treating the oneOf at ${this.breadcrumbs.join(".")} as an "exactly one of" constraint over its sibling properties rather than a union, and converting the schema as an object.`);let r=mfe(this.schema),{oneOf:n,...i}=this.schema;return r.length>0&&(i.required=[...new Set([...i.required??[],...r])]),new e({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:i,inlined:this.inlined,nameOverride:this.nameOverride,visitedRefs:this.visitedRefs}).convert()}tryConvertOneOfAnyOfSchema(){if(this.schema.oneOf!=null||this.schema.anyOf!=null){let r=new vVe({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertMapSchema(){if((typeof this.schema.additionalProperties=="object"||typeof this.schema.additionalProperties=="boolean")&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){if(typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties===!1)return;let r=new sYr({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReferenceOrBoolean:this.schema.additionalProperties}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:r.inlinedTypes}}}tryConvertDiscriminatorMappingSchema(){if(this.schema.discriminator?.mapping!=null&&Object.keys(this.schema.discriminator.mapping).length>0&&this.schema.oneOf==null&&this.schema.anyOf==null){let t={...this.schema,oneOf:Object.values(this.schema.discriminator.mapping).map(i=>({$ref:i}))},n=new vVe({id:this.id,context:this.context,breadcrumbs:this.breadcrumbs,schema:t,inlinedTypes:{}}).convert();if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:n.type,referencedTypes:n.referencedTypes}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:n.inlinedTypes}}}tryConvertObjectAllOfSchema(){if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let r=new llt({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,id:this.id}).convert();if(r!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:r.type,referencedTypes:r.referencedTypes,encoding:r.xmlEncoding!=null?{json:void 0,proto:void 0,xml:r.xmlEncoding}:void 0}),audiences:this.audiences,propertiesByAudience:r.propertiesByAudience},inlinedTypes:r.inlinedTypes}}}tryConvertUntypedSchema(){if(this.isUntypedSchema())return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:mc.alias({aliasOf:en.unknown(),resolvedType:en.unknown()}),referencedTypes:new Set}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}tryConvertFernTypeDeclaration(){let r=new qC.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r==null)return;let n=c8u(r);if(n!=null)return{convertedSchema:{typeDeclaration:this.createTypeDeclaration({shape:mc.alias({aliasOf:n,resolvedType:n}),referencedTypes:new Set,omitV2Examples:!0}),audiences:this.audiences,propertiesByAudience:{}},inlinedTypes:{}}}createTypeDeclaration({shape:t,referencedTypes:r,omitV2Examples:n,encoding:i}){return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:i,availability:this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:r,source:void 0,inline:this.inlined,v2Examples:n?void 0:this.convertSchemaExamples()}}convertDeclaredTypeName(){let t=this.context.getRawSchemaId(this.id);return{typeId:this.context.getNamespacedSchemaId(this.id),fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(t),displayName:this.nameOverride}}schemaOnlyHasAllowedKeys(t){let r=[...Ekm,...t];return Object.keys(this.schema).every(i=>r.includes(i))}isUntypedSchema(){return!!(this.schema&&typeof this.schema=="object"&&!("oneOf"in this.schema)&&!("anyOf"in this.schema)&&!("allOf"in this.schema)&&!("items"in this.schema)&&!("properties"in this.schema))}convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let n=this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:n},t}return t.userSpecifiedExamples=this.convertUserSpecifiedExamples(r),t}convertUserSpecifiedExamples(t){let r={};for(let[n,i]of t.entries()){let o=this.context.resolveExample(i),s=`${this.id}_example_${n}`,a=this.generateOrValidateExample({example:o,exampleName:s});r[s]=a}return r}generateOrValidateExample({example:t}){let r=new Yw({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n}=r.convert();return n}}});function Ckm(e){return Object.keys(e).every(t=>vkm.has(t))}var rO,vkm,EVe=h(()=>{"use strict";Wn();rs();aYr();rO=class extends co{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:n,schemaIdOverride:i,wrapAsOptional:o=!1,wrapAsNullable:s=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=n,this.schemaIdOverride=i,this.wrapAsOptional=o,this.wrapAsNullable=s}convert(){let t=this.maybeConvertReferenceObject({schemaOrReference:this.schemaOrReference});if(t!=null)return t;let r=this.maybeConvertSingularAllOfReferenceObject();return r??this.convertSchemaObject({schema:this.schemaOrReference})}maybeConvertReferenceObject({schemaOrReference:t}){if(this.context.isReferenceObject(t)){let r=this.context.convertReferenceToTypeReference({reference:t,breadcrumbs:this.breadcrumbs});if(r.ok)return{type:this.wrapTypeReference(r.reference),inlinedTypes:r.inlinedTypes??{},availability:this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs})}}}maybeConvertSingularAllOfReferenceObject(){if(this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null)return;if(this.schemaOrReference.allOf.length===1){let i=this.schemaOrReference.allOf[0];if(this.context.isReferenceObject(i)){let o=this.context.convertReferenceToTypeReference({reference:i,breadcrumbs:this.breadcrumbs});if(o.ok)return{type:this.wrapTypeReference(o.reference),inlinedTypes:o.inlinedTypes??{},availability:this.getAvailabilityOfSelfOrReference(i)}}return}let t=this.schemaOrReference.allOf.filter(i=>this.context.isReferenceObject(i)),r=this.schemaOrReference.allOf.filter(i=>typeof i=="object"&&i!==null&&!this.context.isReferenceObject(i)),n=t.length===1?t[0]:void 0;if(n!=null&&r.every(i=>Ckm(i))){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(i!=null&&i.type!=="object"&&!i.properties&&!i.allOf&&!i.oneOf&&!i.anyOf&&!i.format){let o=this.context.convertReferenceToTypeReference({reference:n,breadcrumbs:this.breadcrumbs});if(o.ok)return{type:this.wrapTypeReference(o.reference),inlinedTypes:o.inlinedTypes??{},availability:this.getAvailabilityOfSelfOrReference(n)}}}}getAvailabilityOfSelfOrReference(t){for(let r of[...this.getSelfAndInlineAllOfElements(),t]){let n=this.context.getAvailability({node:r,breadcrumbs:this.breadcrumbs});if(n!=null)return n}}getSelfAndInlineAllOfElements(){return this.context.isReferenceObject(this.schemaOrReference)||this.schemaOrReference.allOf==null?[this.schemaOrReference]:[this.schemaOrReference,...this.schemaOrReference.allOf.filter(t=>!this.context.isReferenceObject(t))]}convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),n=this.context.getNamespacedSchemaId(r),i=new fwe({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),o=this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),s=i.convert();if(s!=null){let a=s.convertedSchema.typeDeclaration.shape;return a.type==="alias"?{type:this.wrapTypeReference(a.aliasOf),schema:s.convertedSchema,inlinedTypes:s.inlinedTypes,availability:o}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:s.convertedSchema,inlinedTypes:{...s.inlinedTypes,[n]:s.convertedSchema},availability:o}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return en.container(Ts.optional(t))}wrapInNullable(t){return en.container(Ts.nullable(t))}},vkm=new Set(["description","title","deprecated","readOnly","writeOnly","xml","externalDocs","x-fern-type-name"])});function IVe({properties:e,required:t,breadcrumbs:r,context:n,errorCollector:i,withinXmlElement:o=!1}){let s=[],a={},c={},u=new Set;for(let[l,p]of Object.entries(e??{})){let d=[...r,"properties",l];if(typeof p!="object"){i.collect({message:`Schema property ${l} should be an object`,path:d});continue}let f=Skm(r,p,n)??n.convertBreadcrumbsToName(d),m="nullable"in p?p.nullable:!1,A=new rO({context:n,breadcrumbs:d,schemaOrReference:p,schemaIdOverride:f,wrapAsOptional:!t.includes(l),wrapAsNullable:m}).convert();if(A!=null){let y=n.resolveMaybeReference({schemaOrReference:p,breadcrumbs:d,skipErrorCollector:!0});s.push({name:n.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),valueType:A.type,docs:p.description??A.schema?.typeDeclaration.docs,availability:A.availability,propertyAccess:n.getPropertyAccess(p),defaultValue:y?.default,xml:o?new clt({breadcrumbs:d,propertySchema:p,resolvedPropertySchema:y??void 0,context:n}).convert():void 0,v2Examples:A.schema?.typeDeclaration?.v2Examples??xkm({propertySchema:p,breadcrumbs:d,context:n,propertyId:f})}),a={...a,...A.inlinedTypes},A.schema?.typeDeclaration.referencedTypes!=null&&A.schema.typeDeclaration.referencedTypes.forEach(I=>{u.add(I)}),F4(A.type,u);for(let I of A.schema?.audiences??[])c[I]==null&&(c[I]=new Set),c[I].add(l)}}for(let l of Object.keys(a))u.add(l);return{convertedProperties:s,propertiesByAudience:c,inlinedTypesFromProperties:a,referencedTypes:u}}function xkm({propertySchema:e,breadcrumbs:t,context:r,propertyId:n}){let i=r.resolveMaybeReference({schemaOrReference:e,breadcrumbs:t,skipErrorCollector:!0}),o=r.getExamplesFromSchema({schema:i??void 0,breadcrumbs:t});if(o.length>0){let u={};for(let[l,p]of o.entries()){let d=r.resolveExample(p),f=`${n}_example_${l}`,m=new Yw({breadcrumbs:t,context:r,schema:e,example:d}),{validExample:g}=m.convert();u[f]=g}return{userSpecifiedExamples:u,autogeneratedExamples:{}}}let s=`${n}_example_autogenerated`,a=new Yw({breadcrumbs:t,context:r,schema:e,example:void 0,generateOptionalProperties:!0}),{validExample:c}=a.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{[s]:c}}}function Skm(e,t,r){return r.isReferenceObject(t)?void 0:new qC.FernTypeNameExtension({breadcrumbs:e,schema:t,context:r}).convert()}function F4(e,t){switch(e.type){case"named":t.add(e.typeId);return;case"primitive":case"unknown":return;case"container":wkm(e.container,t);return}}function wkm(e,t){switch(e.type){case"list":F4(e.list,t);return;case"set":F4(e.set,t);return;case"optional":F4(e.optional,t);return;case"nullable":F4(e.nullable,t);return;case"map":F4(e.keyType,t),F4(e.valueType,t);return;case"literal":return}}var ult=h(()=>{"use strict";lwe();EVe();iYr();rs()});var flt,HGo=h(()=>{"use strict";Wn();rs();ult();EVe();flt=class e extends co{static LIST_UNKNOWN=en.container(Ts.list(en.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:n}){super({context:t,breadcrumbs:r}),this.schema=n}convert(){if(this.schema.items!=null){Array.isArray(this.schema.items)&&(this.schema.items={oneOf:this.schema.items});let r=new rO({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();if(r!=null){let n=new Set;for(let i of r.schema?.typeDeclaration.referencedTypes??[])n.add(i);return r.inlinedTypes!=null&&Object.values(r.inlinedTypes).forEach(i=>{i.typeDeclaration.referencedTypes.forEach(o=>{n.add(o)})}),F4(r.type,n),{typeReference:en.container(Ts.list(r.type)),referencedTypes:n,inlinedTypes:r.inlinedTypes}}}return{typeReference:e.LIST_UNKNOWN,referencedTypes:new Set,inlinedTypes:{}}}}});var KGo={};$(KGo,{ArraySchemaConverter:()=>flt,EnumSchemaConverter:()=>pwe,ObjectSchemaConverter:()=>llt,OneOfSchemaConverter:()=>vVe,PrimitiveSchemaConverter:()=>plt,SchemaConverter:()=>fwe,SchemaOrReferenceConverter:()=>rO});var JGo=h(()=>{"use strict";HGo();oYr();GGo();qGo();WGo();aYr();EVe()});var cYr,A8u=h(()=>{"use strict";qi();rs();lwe();JGo();cYr=class extends co{group;method;constructor({context:t,breadcrumbs:r,group:n,method:i}){super({context:t,breadcrumbs:r}),this.group=n,this.method=i}parseMediaTypeObject({mediaTypeObject:t,resolveSchema:r,contentType:n,schemaId:i}){if(t.schema==null)return;if(r){let c=this.context.resolveMaybeReference({schemaOrReference:t.schema,breadcrumbs:[...this.breadcrumbs,"content",n]});if(c==null)return;t.schema=c}let s=new rO({context:this.context,breadcrumbs:[...this.breadcrumbs,"content",n,"schema"],schemaOrReference:t.schema,schemaIdOverride:i}).convert();if(s==null)return;let a=t.examples!=null?Object.fromEntries(Object.entries(t.examples).map(([c,u])=>{if(this.context.isReferenceObject(u)){let l=this.context.resolveReference({reference:u,breadcrumbs:[...this.breadcrumbs,"content",n,"examples"],skipErrorCollector:!0});return l.resolved?[c,l.value.value??l.value]:null}return[c,u.value??u]}).filter(c=>c!=null)):void 0;return{...s,examples:a}}parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:r}){let i=new rO({context:this.context,breadcrumbs:[...this.breadcrumbs],schemaOrReference:t,schemaIdOverride:r}).convert();if(i!=null)return{...i,examples:void 0}}getIdForExample({key:t,example:r,usedExampleNames:n}){if(this.context.isExampleWithSummary(r)){let i=r.summary;if(!n.has(i))return i;let o=`${i} (${t})`;return n.has(o)?t:o}return t}convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r,exampleGenerationStrategy:n}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=t?.schema,s=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),a=new Set;for(let[c,u]of s){let l=this.context.resolveExampleWithValue(u),p=this.context.resolveExampleRecursively({example:u,breadcrumbs:this.breadcrumbs}),d=this.getIdForExample({key:c,example:p,usedExampleNames:a});a.add(d),l!=null&&(o!=null?i.userSpecifiedExamples[d]=this.generateOrValidateExample({schema:o,example:l,exampleGenerationStrategy:n,exampleName:d}):i.userSpecifiedExamples[d]=l)}if(o!=null&&Object.keys(i.userSpecifiedExamples).length===0){let c=this.getExamplesFromSchemaOrReference(o);c.length>1&&c.forEach((u,l)=>{let p=`Example ${l+1}`;i.userSpecifiedExamples[p]=this.generateOrValidateExample({schema:o,example:u,exampleGenerationStrategy:n,exampleName:p})})}if(Object.keys(i.userSpecifiedExamples).length===0&&o!=null){let c=ti(`${[...this.group,this.method].join("_")}_example`);i.autogeneratedExamples[c]=this.generateOrValidateExample({schema:o,example:void 0,ignoreErrors:!0,generateOptionalProperties:r,exampleGenerationStrategy:n,exampleName:c})}return i}getExamplesFromSchemaOrReference(t){let r=new Set,n=t;for(;this.context.isReferenceObject(n);){if(r.has(n.$ref))return[];r.add(n.$ref);let i=this.context.resolveReference({reference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(!i.resolved)return[];n=i.value}return this.context.getExamplesFromSchema({schema:n,breadcrumbs:this.breadcrumbs})}generateOrValidateExample({schema:t,example:r,generateOptionalProperties:n,exampleGenerationStrategy:i}){let o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(o==null)return;let s=this.context.getExamplesFromSchema({schema:o,breadcrumbs:this.breadcrumbs}),a=new Yw({breadcrumbs:this.breadcrumbs,context:this.context,schema:o,example:r??s[0],generateOptionalProperties:n??!1,exampleGenerationStrategy:i}),{validExample:c}=a.convert();return c}}});var uYr,y8u=h(()=>{"use strict";rs();lwe();uYr=class extends co{parameter;constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r}),this.parameter=n}convertToOutput({schema:t,typeReference:r,inlinedTypes:n}){let i=this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs}),o=this.context.resolveMaybeReference({schemaOrReference:t,breadcrumbs:this.breadcrumbs}),s=this.getParameterSchemaWithExampleOverride({schema:o}),a=o?.default,c=this.getParameterDescription({schema:t});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:c,valueType:r??co.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,clientDefault:void 0,defaultValue:a,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),availability:i,explode:this.getExplodeForQueryParameter()},inlinedTypes:n};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:c,valueType:r??co.OPTIONAL_STRING,env:void 0,clientDefault:void 0,defaultValue:a,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),availability:i},inlinedTypes:n};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:c,valueType:r??co.STRING,location:"ENDPOINT",variable:void 0,clientDefault:void 0,v2Examples:this.convertParameterExamples({schema:s??t,originalSchema:t}),explode:this.getExplodeForPathParameter()},inlinedTypes:n};default:return}}getParameterDescription({schema:t}){if(this.parameter.description!=null)return this.parameter.description;if("description"in t&&typeof t.description=="string")return t.description}getParameterSchemaWithExampleOverride({schema:t}){if(t!=null)return t.type==="string"&&t.example==null?{...t,example:this.parameter.name}:t}convertParameterExamples({schema:t,originalSchema:r}){let n={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,o=this.parameter.examples;for(let[s,a]of Object.entries(o??{})){let c=this.context.resolveExampleWithValue(a);c!=null&&(n.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:t,example:c,exampleName:s}))}if(i!=null){let s=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[s]=this.generateOrValidateExample({schema:t,example:i,exampleName:s})}if(Object.keys(n.userSpecifiedExamples).length===0){let s=this.context.getExamplesFromSchema({schema:this.resolveSchemaChain(r),breadcrumbs:this.breadcrumbs});for(let a of s){let c=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(n.userSpecifiedExamples)});n.userSpecifiedExamples[c]=this.generateOrValidateExample({schema:t,example:this.context.resolveExample(a),exampleName:c})}}if(Object.keys(n.userSpecifiedExamples).length===0){let s=`${this.parameter.name}_example`;n.autogeneratedExamples[s]=this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0,exampleName:s})}return n}resolveSchemaChain(t){let r=new Set,n=t;for(;this.context.isReferenceObject(n);){if(r.has(n.$ref))return;r.add(n.$ref);let i=this.context.resolveReference({reference:n,breadcrumbs:this.breadcrumbs,skipErrorCollector:!0});if(!i.resolved)return;n=i.value}return n}generateOrValidateExample({schema:t,example:r}){let n=new Yw({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:r}),{validExample:i}=n.convert();return i}getExplodeForQueryParameter(){let t=this.parameter.style??"form",r=this.parameter.explode;if(r!==void 0)return t==="form"||t==="deepObject"?r===!0?void 0:r:r===!1?void 0:r}getExplodeForPathParameter(){let t=this.parameter.explode;if(t!==void 0)return t===!1?void 0:t}}});var YGo={};$(YGo,{AbstractMediaTypeObjectConverter:()=>cYr,AbstractParameterConverter:()=>uYr});var b8u=h(()=>{"use strict";A8u();y8u()});function dlt({context:e,breadcrumbs:t,headers:r}){let n=[],i={},o=t??[];if(r==null)return{headers:n,inlinedTypes:i};for(let[s,a]of Object.entries(r)){let c=e.resolveMaybeReference({schemaOrReference:a,breadcrumbs:[...o,"headers",s]});if(c==null)continue;let u=Tkm({context:e,header:c}),l=u?.schema,p=c.required===!0,d=y=>p?y:en.container(Ts.optional(y)),f=d(co.STRING),m,g=e.getAvailability({node:c,breadcrumbs:[...o,"headers",s]});if(l!=null)if(m=e.resolveMaybeReference({schemaOrReference:l,breadcrumbs:[...o,"headers",s,"schema"]}),m?.type==="number"||m?.type==="integer")f=d(en.primitive({v1:m.type==="integer"?"INTEGER":"DOUBLE",v2:m.type==="integer"?xi.integer({default:void 0,validation:void 0}):xi.double({default:void 0,validation:void 0})}));else if(m?.type==="boolean")f=d(en.primitive({v1:"BOOLEAN",v2:xi.boolean({default:void 0})}));else{let y=new rO({context:e,breadcrumbs:[...o,"headers",s,"schema"],schemaOrReference:l,wrapAsOptional:!p,schemaIdOverride:e.convertBreadcrumbsToName([...o,"headers",s])}).convert();if(y!=null){f=y.type;for(let[I,x]of Object.entries(y.inlinedTypes))i[I]=x}}let A=Okm({context:e,breadcrumbs:o,header:c,headerName:s,schema:l,mediaTypeObject:u?.mediaTypeObject});n.push({name:e.casingsGenerator.generateNameAndWireValue({name:s,wireValue:s}),docs:c.description,valueType:f,env:void 0,v2Examples:A,availability:g,clientDefault:void 0,defaultValue:m?.default})}return{headers:n,inlinedTypes:i}}function Tkm({context:e,header:t}){if(t.schema!=null)return{schema:t.schema};if(!(!e.settings.respectParameterContent||t.content==null)){for(let[r,n]of Object.entries(t.content))if(n.schema!=null&&of.parse(r)?.isJSON())return{schema:n.schema,mediaTypeObject:n}}}function Okm({context:e,breadcrumbs:t,header:r,headerName:n,schema:i,mediaTypeObject:o}){let s={userSpecifiedExamples:{},autogeneratedExamples:{}},a=r.example,c=r.examples;for(let[u,l]of Object.entries(c??{})){let p=e.resolveExampleWithValue(l);p!=null&&(s.userSpecifiedExamples[u]=sWt({context:e,breadcrumbs:t,schema:i,example:p}))}if(a!=null){let u=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[u]=sWt({context:e,breadcrumbs:t,schema:i,example:a})}if(Object.keys(s.userSpecifiedExamples).length===0&&o!=null)for(let[u,l]of e.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...t,"headers",n,"content"],defaultExampleName:`${n}_example`})){let p=e.resolveExampleWithValue(l);if(p!=null){let d=e.generateUniqueName({prefix:u,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[d]=sWt({context:e,breadcrumbs:t,schema:i,example:p})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let u=e.getExamplesFromSchema({schema:Pkm({context:e,schema:i,breadcrumbs:[...t,"headers",n,"schema"]}),breadcrumbs:[...t,"headers",n,"schema"]});for(let l of u){let p=e.generateUniqueName({prefix:`${n}_example`,existingNames:Object.keys(s.userSpecifiedExamples)});s.userSpecifiedExamples[p]=sWt({context:e,breadcrumbs:t,schema:i,example:e.resolveExample(l)})}}if(Object.keys(s.userSpecifiedExamples).length===0&&i!=null){let u=`${n}_example`;s.autogeneratedExamples[u]=sWt({context:e,breadcrumbs:t,schema:i,example:void 0,ignoreErrors:!0})}return s}function Pkm({context:e,schema:t,breadcrumbs:r}){let n=new Set,i=t;for(;e.isReferenceObject(i);){if(n.has(i.$ref))return;n.add(i.$ref);let o=e.resolveReference({reference:i,breadcrumbs:r,skipErrorCollector:!0});if(!o.resolved)return;i=o.value}return i}function sWt({context:e,breadcrumbs:t,schema:r,example:n,ignoreErrors:i}){if(r==null)return n;let o=new Yw({breadcrumbs:t,context:e,schema:r,example:n}),{validExample:s,errors:a}=o.convert();return i||a.forEach(c=>{e.errorCollector.collect({message:c.message,path:c.path})}),s}var E8u=h(()=>{"use strict";ct();Wn();JJr();lwe();EVe()});var lYr,I8u=h(()=>{"use strict";tk();lYr=class extends os{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:n}){super({breadcrumbs:t,context:n}),this.server=r}convert(){let t=this.getExtensionValue(this.server,"x-name");if(!(t==null||typeof t!="string"))return t}}});var v8u,Bkm,N4,C8u=h(()=>{"use strict";ct();Wn();zGo();I8u();rs();v8u="Base",Bkm="x-fern-default-url",N4=class e extends co{servers;endpointLevelServers;baseUrlEnvVar;constructor({breadcrumbs:t,context:r,servers:n,endpointLevelServers:i,baseUrlEnvVar:o}){super({breadcrumbs:t,context:r}),this.servers=n,this.endpointLevelServers=i,this.baseUrlEnvVar=o}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let n=this.getDefaultBaseUrlName(),i={id:n,name:this.context.casingsGenerator.generateName(n)},o=this.endpointLevelServers.map(c=>{let u=e.getServerName({server:c,context:this.context});return{id:u,name:this.context.casingsGenerator.generateName(u)}}).filter((c,u,l)=>l.findIndex(p=>p.id===c.id)===u),s=[i,...o],a=this.servers.map(c=>{let u=e.getServerName({server:c,context:this.context}),l=this.endpointLevelServers?.map(g=>[e.getServerName({server:g,context:this.context}),this.getServerUrl(g)]),p=e.getServerAudiences({server:c,context:this.context}),{defaultUrls:d,urlTemplates:f,urlVariables:m}=this.buildMultiUrlTemplateFields({defaultBaseUrlId:n,topLevelServer:c,endpointServers:this.endpointLevelServers??[]});return{id:u,name:this.context.casingsGenerator.generateName(u),urls:{[n]:this.getServerUrl(c),...Object.fromEntries(l??[])},docs:c.description,audiences:p,defaultUrls:d,urlTemplates:f,urlVariables:m}});return{value:{defaultEnvironment:a[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:sE.multipleBaseUrls({baseUrls:s,environments:a})},defaultUrl:i.id}}let t=this.extractFernDefaultUrl(),r=this.servers.map(n=>{let i=e.getServerName({server:n,context:this.context}),o=e.getServerAudiences({server:n,context:this.context});return n.variables!=null&&Object.keys(n.variables).length>0&&n.variables!=null?{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(n)),audiences:o,defaultUrl:t,urlTemplate:this.maybeRemoveTrailingSlashIfNotEmpty(n.url),urlVariables:this.convertServerVariables(n.variables),docs:n.description}:{id:i,name:this.context.casingsGenerator.generateName(i),url:this.maybeRemoveTrailingSlashIfNotEmpty(this.getServerUrl(n)),audiences:o,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0,docs:n.description}}).filter(ga);return{value:{defaultEnvironment:r[0]?.id,baseUrlEnvVar:this.baseUrlEnvVar,environments:sE.singleBaseUrl({environments:r})},defaultUrl:r[0]?.id}}convertServerVariables(t){return Object.entries(t).map(([r,n])=>({id:r,name:this.context.casingsGenerator.generateName(r),default:n.default,values:n.enum}))}static getServerExtensionName({server:t,context:r}){return new lYr({breadcrumbs:[],server:t,context:r}).convert()}static getServerAudiences({server:t,context:r}){return new nlt({breadcrumbs:[],operation:t,context:r}).convert()?.audiences}static getServerName({server:t,context:r}){return t.name!=null?t.name:e.getServerExtensionName({server:t,context:r})??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[n,i]of Object.entries(t.variables))i.default!=null&&(r=r.replace(`{${n}}`,encodeURIComponent(i.default)));return r}getDefaultBaseUrlName(){return this.servers==null||this.servers.length===0||this.servers[0]==null?v8u:e.getServerExtensionName({server:this.servers[0],context:this.context})??v8u}maybeRemoveTrailingSlashIfNotEmpty(t){return t.endsWith("/")&&t!=="/"?t.slice(0,-1):t}buildMultiUrlTemplateFields({defaultBaseUrlId:t,topLevelServer:r,endpointServers:n}){let i={},o={},s={},a=!1;if(r.variables!=null&&Object.keys(r.variables).length>0){a=!0;let c=this.extractFernDefaultUrlFromServer(r);c!=null&&(i[t]=c),o[t]=this.maybeRemoveTrailingSlashIfNotEmpty(r.url),s[t]=this.convertServerVariables(r.variables)}for(let c of n){let u=e.getServerName({server:c,context:this.context});if(c.variables!=null&&Object.keys(c.variables).length>0){a=!0;let l=this.extractFernDefaultUrlFromServer(c);l!=null&&(i[u]=l),o[u]=this.maybeRemoveTrailingSlashIfNotEmpty(c.url),s[u]=this.convertServerVariables(c.variables)}}return a?{defaultUrls:Object.keys(i).length>0?i:void 0,urlTemplates:o,urlVariables:s}:{defaultUrls:void 0,urlTemplates:void 0,urlVariables:void 0}}extractFernDefaultUrlFromServer(t){let r=t[Bkm];if(typeof r=="string")return this.maybeRemoveTrailingSlashIfNotEmpty(r)}extractFernDefaultUrl(){if(this.servers!=null)for(let t of this.servers){let r=this.extractFernDefaultUrlFromServer(t);if(r!=null)return r}}}});var Hm={};$(Hm,{AbstractConverters:()=>YGo,ExampleConverter:()=>Yw,SchemaConverters:()=>KGo,ServersConverter:()=>N4,convertResponseHeaders:()=>dlt});var XGo=h(()=>{"use strict";b8u();lwe();E8u();JGo();C8u()});var aWt,x8u=h(()=>{"use strict";lwe();oWt();aWt=class{context;constructor({context:t}){this.context=t}validateExample({example:t,schema:r,breadcrumbs:n,exampleGenerationStrategy:i}){return new Yw({breadcrumbs:n,context:this.context,schema:r,example:t,depth:0,exampleGenerationStrategy:i,generateOptionalProperties:!1}).convert()}validateEndpointExample({exampleToValidate:t}){let r=[],n=[],i=!0,o=!1,s,a=[t.endpointPath,t.method];if(t.requestExample!==void 0&&t.requestSchema!==void 0){let u=this.validateExample({example:t.requestExample,schema:t.requestSchema,breadcrumbs:[...a,"request"],exampleGenerationStrategy:"request"});if(!u.isValid){i=!1;let l=t.exampleSource==="human"?CE.WARNING:CE.ERROR;r.push(...u.errors.map(p=>({...p,level:l,message:`Invalid request example: ${p.message}`})))}u.coerced&&(o=!0,n.push({level:CE.WARNING,message:"Request example was coerced to match schema",path:[...a,"request"]})),s={request:u.validExample}}let c=this.getResponseSchemaForValidation(t);if(t.responseExample!==void 0&&c!==void 0){let u=this.validateExample({example:t.responseExample,schema:c,breadcrumbs:[...a,"response"],exampleGenerationStrategy:"response"});if(!u.isValid){i=!1;let l=t.exampleSource==="human"?CE.WARNING:CE.ERROR;r.push(...u.errors.map(p=>({...p,level:l,message:`Invalid response example: ${p.message}`})))}u.coerced&&(o=!0,n.push({level:CE.WARNING,message:"Response example was coerced to match schema",path:[...a,"response"]})),s={...typeof s=="object"&&s!==null?s:{},response:u.validExample}}return{isValid:i,errors:r,warnings:n,endpointPath:t.endpointPath,method:t.method,exampleSource:t.exampleSource,exampleName:t.exampleName,validExample:s,coerced:o}}getResponseSchemaForValidation(t){let{responseStatusCode:r,responseSchemas:n,responseSchema:i}=t;return n&&Object.keys(n).length>0?r&&n[r]?n[r]:n[200]??n[201]:i}validateAiExamples({aiExamples:t,spec:r}){let n=[],i=[];for(let o of t){let{requestSchema:s,responseSchema:a,responseSchemas:c}=this.getSchemasForEndpoint({spec:r,endpointPath:o.endpointPath,method:o.method}),u={endpointPath:o.endpointPath,method:o.method,exampleSource:"ai",requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a,responseSchemas:c},l=this.validateEndpointExample({exampleToValidate:u}),p=this.hasUnexpectedProperties({requestExample:o.request?.body,responseExample:o.response?.body,requestSchema:s,responseSchema:a}),d=l.errors.length>0||l.warnings.length>0;!l.isValid||d||p?i.push({example:o,validationResult:l}):n.push(o)}return{validExamples:n,invalidExamples:i}}hasUnexpectedProperties({requestExample:t,responseExample:r,requestSchema:n,responseSchema:i}){return!!(t&&n&&this.exampleHasUnexpectedProperties(t,n)||r&&i&&this.exampleHasUnexpectedProperties(r,i))}exampleHasUnexpectedProperties(t,r){if(!t||typeof t!="object"||t===null)return!1;let n=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[],skipErrorCollector:!0});if(!n||!n.properties&&!n.allOf&&!n.oneOf&&!n.anyOf||this.schemaHasPatternProperties(n))return!1;let i=t,o=this.collectAllPropertyKeys(n);return Object.keys(i).some(a=>!o.has(a))}collectAllPropertyKeys(t,r=new Set){let n=new Set;if(t.properties)for(let i of Object.keys(t.properties))n.add(i);for(let i of t.allOf??[]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}for(let i of[...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)){r.add(s);let a=this.collectAllPropertyKeys(o,r);for(let c of a)n.add(c)}}}return n}schemaHasPatternProperties(t,r=new Set){let n=t.patternProperties;if(n&&typeof n=="object"&&Object.keys(n).length>0)return!0;for(let i of[...t.allOf??[],...t.oneOf??[],...t.anyOf??[]]){let o=this.context.resolveMaybeReference({schemaOrReference:i,breadcrumbs:[],skipErrorCollector:!0});if(o){let s=this.context.isReferenceObject(i)?i.$ref:JSON.stringify(o);if(!r.has(s)&&(r.add(s),this.schemaHasPatternProperties(o,r)))return!0}}return!1}validateHumanExamples({spec:t}){let r=[],n=0,i=0,o=0,s=[],a=[];if(!t.paths)return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:!1,hasInvalidAiExamples:!1,invalidHumanExamples:s,invalidAiExamples:a};for(let[c,u]of Object.entries(t.paths)){if(!u)continue;let l=["get","post","put","delete","patch","options","head","trace"];for(let p of l){let d=u[p];if(!d)continue;let f=[],{requestSchema:m,responseSchema:g,responseSchemas:A}=this.getSchemasForOperation({operation:d}),y=this.extractExamplesFromOperation({operation:d,path:c,method:p});for(let I of y){n++;let x={endpointPath:c,method:p,exampleName:I.name,exampleSource:I.source,requestExample:I.request,responseExample:I.response,requestSchema:m,responseSchema:g,responseStatusCode:I.statusCode,responseSchemas:A},v=this.validateEndpointExample({exampleToValidate:x});f.push(v),v.isValid?i++:(o++,I.source==="human"?s.push(v):I.source==="ai"&&a.push(v))}f.length>0&&r.push({endpointPath:c,method:p,results:f,hasInvalidExamples:f.some(I=>!I.isValid),invalidExampleCount:f.filter(I=>!I.isValid).length})}}return{endpoints:r,totalExamples:n,validExamples:i,invalidExamples:o,hasInvalidHumanExamples:s.length>0,hasInvalidAiExamples:a.length>0,invalidHumanExamples:s,invalidAiExamples:a}}getSchemasForEndpoint({spec:t,endpointPath:r,method:n}){let i=t.paths?.[r];if(!i)return{responseSchemas:{}};let o=i[n.toLowerCase()];return!o||typeof o!="object"||!("responses"in o)?{responseSchemas:{}}:this.getSchemasForOperation({operation:o})}getSchemasForOperation({operation:t}){let r,n,i={};if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let s=t.requestBody.content?.["application/json"];s?.schema&&(r=s.schema)}if(t.responses){for(let[o,s]of Object.entries(t.responses)){if(!s||this.context.isReferenceObject(s))continue;let c=s.content?.["application/json"];c?.schema&&(i[o]=c.schema)}n=i[200]??i[201]}return{requestSchema:r,responseSchema:n,responseSchemas:i}}extractExamplesFromOperation({operation:t,path:r,method:n}){let i=[];if(t.requestBody&&!this.context.isReferenceObject(t.requestBody)){let a=t.requestBody.content?.["application/json"];if(a?.example!==void 0&&i.push({name:`${n}_${r}_request_example`,source:"openapi",request:a.example}),a?.examples)for(let[c,u]of Object.entries(a.examples)){let l=this.context.isReferenceObject(u)?this.context.resolveExample(u):u;l&&typeof l=="object"&&"value"in l&&i.push({name:c,source:"human",request:l.value})}}if(t.responses)for(let[s,a]of Object.entries(t.responses)){if(!a||this.context.isReferenceObject(a))continue;let u=a.content?.["application/json"];if(u?.example!==void 0){let l=i.find(p=>p.request!==void 0&&p.response===void 0);l?(l.response=u.example,l.statusCode=s):i.push({name:`${n}_${r}_response_${s}_example`,source:"openapi",response:u.example,statusCode:s})}if(u?.examples)for(let[l,p]of Object.entries(u.examples)){let d=this.context.isReferenceObject(p)?this.context.resolveExample(p):p;if(d&&typeof d=="object"&&"value"in d){let f=i.find(m=>m.name===l);f?(f.response=d.value,f.statusCode=s):i.push({name:l,source:"human",response:d.value,statusCode:s})}}}let o=t["x-fern-examples"];if(Array.isArray(o)){for(let s of o)if(typeof s=="object"&&s!==null){let a=s;i.push({name:a.name,source:"human",request:a.request?.body,response:a.response?.body})}}return i}}});function S8u({tags:e,errorCollector:t}){for(let r of e)if(mlt.test(r.name)){let n=[...r.name].filter(i=>mlt.test(i));t.collect({level:CE.ERROR,message:`Tag name "${r.name}" contains non-ASCII characters: ${n.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR).`,path:["tags",r.name],resolution:`Remove non-ASCII characters from the tag name. For example, rename "${r.name}" to "${r.name.replace(mlt,"").trim()}".`})}}function w8u({description:e,path:t,errorCollector:r}){Rkm.test(e)&&r.collect({level:CE.ERROR,message:'Description contains "---" frontmatter delimiters which will cause YAML parsing failures in the generated docs site. The docs renderer interprets content between "---" delimiters as YAML frontmatter, which will fail if the content is not valid YAML.',path:t,resolution:'Remove the "---" delimiters from the description.'})}function ZGo({spec:e,errorCollector:t}){if(Array.isArray(e.tags)){let n=e.tags.filter(i=>typeof i=="object"&&i!=null&&"name"in i&&typeof i.name=="string");S8u({tags:n,errorCollector:t})}let r=["get","post","put","delete","patch","options","head","trace"];if(e.paths!=null&&typeof e.paths=="object"){let n=new Set;for(let[i,o]of Object.entries(e.paths)){if(o==null||typeof o!="object")continue;let s=o;for(let a of r){let c=s[a];if(c==null||typeof c!="object")continue;let u=c;if(typeof u.description=="string"&&w8u({description:u.description,path:["paths",i,a,"description"],errorCollector:t}),Array.isArray(u.tags)&&!Array.isArray(e.tags)){for(let l of u.tags)if(typeof l=="string"&&!n.has(l)&&mlt.test(l)){n.add(l);let p=[...l].filter(d=>mlt.test(d));t.collect({level:CE.ERROR,message:`Tag name "${l}" contains non-ASCII characters: ${p.join(", ")}. Non-ASCII characters in tag names will be included in URL paths and HTTP headers, which only support ASCII characters. This will cause runtime errors (ERR_INVALID_CHAR).`,path:["paths",i,a,"tags"],resolution:`Remove non-ASCII characters from the tag name. For example, rename "${l}" to "${l.replace(mlt,"").trim()}".`})}}}}}}var mlt,Rkm,T8u=h(()=>{"use strict";oWt();mlt=new RegExp("[^\\x00-\\x7F]"),Rkm=/(?:^|\n)\s*---\s*(?:\n|$)/});var pYr,Dkm,O8u=h(()=>{"use strict";pYr={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},Dkm=new Set(Object.values(pYr))});function $Go(e){if(e!=null)return e.map(t=>Object.fromEntries(Object.entries(t).map(([r,n])=>[r,n??[]])))}var P8u=h(()=>{"use strict"});var rs=h(()=>{"use strict";JJr();U5u();tk();o8u();XGo();XGo();oWt();x8u();UGo();T8u();O8u();P8u()});var kkm,Fkm,B8u,R8u=h(()=>{"use strict";cn();kkm=De.object({type:De.string(),channelId:De.string().optional(),messageId:De.string(),value:De.any()}),Fkm=De.object({summary:De.string().optional(),description:De.string().optional(),"query-parameters":De.record(De.string()).optional(),headers:De.record(De.string()).optional(),messages:De.array(kkm)}),B8u=De.array(Fkm)});var fYr,D8u=h(()=>{"use strict";rs();R8u();fYr=class extends os{channel;baseDir;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:n,baseDir:i}){super({breadcrumbs:t??[],context:n}),this.channel=r,this.baseDir=i}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=B8u.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(n=>({summary:n.summary,description:n.description,queryParameters:n["query-parameters"],headers:n.headers,messages:n.messages.map(i=>({type:i.type,channelId:i.channelId,messageId:i.messageId,value:i.value}))}))}}});var hlt,eqo=h(()=>{"use strict";rs();D8u();hlt=class extends co{channel;channelPath;inlinedTypes={};websocketGroup;constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}){super({context:t,breadcrumbs:r}),this.websocketGroup=n,this.channel=i,this.channelPath=o}convertExamples({fullPath:t,baseUrl:r,asyncApiVersion:n}){let o=new fYr({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel,baseDir:this.context.documentBaseDir}).convert();return o==null?{}:Object.fromEntries(o.map((s,a)=>[a.toString(),{channel:{method:"GET",path:t},baseUrl:t,environment:r,auth:void 0,pathParameters:{},queryParameters:s.queryParameters,headers:s.headers,messages:s.messages.map(c=>({type:n==="v2"?c.type:c.messageId,body:c.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}}});var Nkm,BJ,cWt=h(()=>{"use strict";Wn();rs();Nkm="x-fern-server-name",BJ=class e extends co{servers;constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r}),this.servers=n}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[n,i]of Object.entries(this.servers)){let o=e.getServerName(n,i),s=this.buildSingleBaseUrlEnvironment(this.context,o,i);t.push(s),r==null&&(r=s.id)}return{defaultEnvironment:r,baseUrlEnvVar:void 0,environments:sE.singleBaseUrl({environments:t})}}static getServerName(t,r){if(r!=null&&typeof r=="object"){let n=r[Nkm];if(typeof n=="string"&&n.length>0)return n}return t}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}}});var dwe,tqo=h(()=>{"use strict";rs();dwe=class extends Hm.AbstractConverters.AbstractParameterConverter{parameterNamePrefix;constructor({context:t,breadcrumbs:r,parameter:n,parameterNamePrefix:i}){super({context:t,breadcrumbs:r,parameter:n}),this.parameterNamePrefix=i}convert(){let t,r={},i=new qC.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required===!1,o=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example??this.parameter.name,examples:Object.values(this.parameter.examples??{}),deprecated:this.parameter.deprecated,required:void 0},a=new Hm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameterNamePrefix?`${this.parameterNamePrefix}_${this.parameter.name}`:this.parameter.name,schemaOrReference:o,wrapAsOptional:i}).convert();return a!=null&&(t=a.type,r=a.inlinedTypes??{}),this.convertToOutput({schema:o,typeReference:t,inlinedTypes:r})}}});var dYr,k8u=h(()=>{"use strict";rs();dYr=class extends os{channel;key="x-fern-address";constructor({breadcrumbs:t,channel:r,context:n}){super({breadcrumbs:t,context:n}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(!(t==null||typeof t!="string"))return t}}});var mwe,rqo=h(()=>{"use strict";rs();mwe=class extends os{node;key="x-fern-display-name";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(!(t==null||typeof t!="string"))return t}}});var hwe,nqo=h(()=>{"use strict";rs();hwe=class extends os{node;key="x-fern-explorer";constructor({breadcrumbs:t,node:r,context:n}){super({breadcrumbs:t,context:n}),this.node=r}convert(){let t=this.getExtensionValue(this.node);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}}});var mYr,F8u=h(()=>{"use strict";rs();mYr=class extends os{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(!(t==null||typeof t!="string"))return t}}});var hYr,N8u=h(()=>{"use strict";Wn();hc();rs();qi();eqo();cWt();tqo();k8u();rqo();nqo();F8u();hYr=class extends hlt{inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}){super({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o})}convert(){let t=[],r=[],n=[],o=new mwe({breadcrumbs:this.breadcrumbs,node:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".");this.channel.parameters&&this.convertPathParameters({context:this.context,pathParameters:t}),this.channel.bindings?.ws!=null&&(this.convertHeaders({context:this.context,headers:n}),this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let s;this.channel.subscribe!=null&&(s=this.convertMessage({context:this.context,operation:this.channel.subscribe,origin:"server"}));let a;this.channel.publish!=null&&(a=this.convertMessage({context:this.context,operation:this.channel.publish,origin:"client"}));let c=[];s!=null&&c.push(s),a!=null&&c.push(a);let l=new dYr({breadcrumbs:this.breadcrumbs,channel:this.channel,context:this.context}).convert(),p=this.transformToValidPath(l??this.channelPath),d=this.resolveServerName(this.channel.servers?.[0])??this.resolveServerName(Object.keys(this.context.spec.servers??{})[0]),f=sb(p),m=ti(this.channelPath),g=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],A=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,y=new hwe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),x=new hwe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??y;return{channel:{name:this.context.casingsGenerator.generateName(m),displayName:o,connectMethodName:void 0,baseUrl:d,path:f,auth:A,headers:n,queryParameters:r,pathParameters:t,messages:c,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:p,baseUrl:d,asyncApiVersion:"v2"})},apiPlayground:x},audiences:g,inlinedTypes:this.inlinedTypes}}hasServerSecurity(){let t=this.context.spec.servers??{};if(this.channel.servers&&this.channel.servers.length>0){for(let r of this.channel.servers){let n=t[r];if(n?.security&&n.security.length>0)return!0}return!1}for(let r of Object.values(t)){let n=r;if(n.security&&n.security.length>0)return!0}return!1}convertMessage({context:t,operation:r,origin:n}){let i,o=n==="server"?"subscribe":"publish",s=[...this.breadcrumbs,o],a=t.resolveMaybeReference({schemaOrReference:r.message,breadcrumbs:s});a!=null&&(r.message=a);let c=dLe(ti(`${this.channelPath}_${o}`)).replace(/ /g,"");if("oneOf"in r.message){let l=new Hm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:r.message,schemaIdOverride:c}).convert();l!=null&&l.schema!=null&&(i=l.schema,this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes})}else if(t.isMessageWithPayload(r.message)){let u=t.resolveMaybeReference({schemaOrReference:r.message.payload,breadcrumbs:s});if(u!=null){let p=new Hm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:s,schemaOrReference:u,schemaIdOverride:c}).convert();p!=null&&p.schema!=null&&(i=p.schema,this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes})}}if(i!=null){let u=i,l=en.named({fernFilepath:t.createFernFilepath(),name:u.typeDeclaration.name.name,typeId:u.typeDeclaration.name.typeId,displayName:void 0,default:void 0,inline:!1}),p=dB.reference({bodyType:l,docs:r.description}),d=n==="server"?"subscribe":"publish",m=new mwe({breadcrumbs:[...this.breadcrumbs,d],node:r,context:this.context}).convert()??d;return{type:d,displayName:m,origin:n,body:p,availability:t.getAvailability({node:r,breadcrumbs:this.breadcrumbs}),docs:r.description,methodName:this.getOperationMethodName(r)}}}convertPathParameters({context:t,pathParameters:r}){for(let[n,i]of Object.entries(this.channel.parameters??{})){let o=t.resolveMaybeReference({schemaOrReference:i,breadcrumbs:this.breadcrumbs});if(o==null)continue;let a=new dwe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...o,name:n,in:"path",description:o.description,required:o.required??!0},parameterNamePrefix:this.channelPath}).convert();a!=null&&(this.inlinedTypes={...this.inlinedTypes,...a.inlinedTypes},a.type==="path"&&r.push(a.parameter))}}convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let n=this.channel.bindings.ws.headers.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let c=new dwe({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"header",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0},parameterNamePrefix:this.channelPath}).convert();c!=null&&c.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}resolveServerName(t){if(t==null)return;let r=this.context.spec.servers;if(r!=null&&t in r){let n=r[t];return BJ.getServerName(t,n)}return t}getOperationMethodName(t){return new mYr({breadcrumbs:this.breadcrumbs,operation:t,context:this.context}).convert()}convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let n=this.channel.bindings.ws.query.required??[];for(let[i,o]of Object.entries(this.channel.bindings.ws.query.properties??{})){let s=t.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,i]});if(s==null)continue;let c=new dwe({context:this.context,breadcrumbs:[...this.breadcrumbs,i],parameter:{name:i,in:"query",required:n.includes(i),schema:s,description:"description"in s?s.description:void 0,deprecated:s.deprecated??!1},parameterNamePrefix:this.channelPath}).convert();c!=null&&c.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...c.inlinedTypes},r.push(c.parameter))}}}}});var gYr,j8u=h(()=>{"use strict";cWt();gYr=class extends BJ{constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r,servers:n})}buildSingleBaseUrlEnvironment(t,r,n){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(n.protocol,n.url),docs:void 0,audiences:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}}});var iqo,z8u,oqo,AYr,Q8u=h(()=>{"use strict";Wn();hc();Dt();eqo();cWt();tqo();rqo();nqo();iqo="$message.",z8u="#/channels/",oqo="#/servers/",AYr=class extends hlt{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o,operations:s}){super({context:t,breadcrumbs:r,websocketGroup:n,channel:i,channelPath:o}),this.operations=s}convert(){let t=[],r=[],n=[],o=new mwe({breadcrumbs:this.breadcrumbs,node:this.channel,context:this.context}).convert()??this.websocketGroup?.join(".")??this.channelPath;this.channel.parameters&&this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:n,channelPath:this.channelPath});let s=Object.entries(this.operations).reduce((A,[y,I])=>{try{this.getChannelPathFromOperation(I)===this.channelPath&&(A[y]=I)}catch{}return A},{}),a=[];for(let[A,y]of Object.entries(s)){let x=new mwe({breadcrumbs:[...this.breadcrumbs,A],node:y,context:this.context}).convert()??A;for(let v of y.messages){let S=this.context.convertReferenceToTypeReference({reference:v});if(S.ok){let B=this.resolveMessageDocs(v)??y.description,R=dB.reference({bodyType:S.reference,docs:B});a.push({type:A,displayName:x,origin:y.action==="send"?"client":"server",body:R,availability:this.context.getAvailability({node:y,breadcrumbs:this.breadcrumbs}),docs:B,methodName:void 0})}}}let c=this.resolveChannelServersFromReference(this.channel.servers??[])??this.resolveFirstServerName(),u=this.transformToValidPath(this.channel.address??this.channelPath),l=sb(u),p=this.context.getAudiences({operation:this.channel,breadcrumbs:this.breadcrumbs})??[],d=this.hasServerSecurity()||this.context.authOverrides?.auth!=null,f=new hwe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.context.spec}).convert(),g=new hwe({context:this.context,breadcrumbs:this.breadcrumbs,node:this.channel}).convert()??f;return{channel:{name:this.context.casingsGenerator.generateName(o),displayName:o,connectMethodName:void 0,baseUrl:c,path:l,auth:d,headers:n,queryParameters:r,pathParameters:t,messages:a,availability:this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({fullPath:u,baseUrl:c,asyncApiVersion:"v3"})},apiPlayground:g},audiences:p,inlinedTypes:this.inlinedTypes}}hasServerSecurity(){let r=this.context.spec.servers??{};if(this.channel.servers&&this.channel.servers.length>0){for(let n of this.channel.servers){let i=n.$ref.replace(oqo,""),o=r[i];if(o?.security&&o.security.length>0)return!0}return!1}for(let n of Object.values(r))if(n.security&&n.security.length>0)return!0;return!1}convertChannelParameters({pathParameters:t,queryParameters:r,headers:n,channelPath:i}){for(let o of Object.values(this.channel.parameters??{})){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:[...this.breadcrumbs,"parameters"]});if(s==null)continue;let a=this.convertChannelParameterLocation(s.location);if(a==null)continue;let{type:c,parameterKey:u}=a,p=new dwe({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...s,name:u,in:c},parameterNamePrefix:this.channelPath}).convert();if(p!=null)switch(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},p.type){case"path":t.push(p.parameter);break;case"query":r.push(p.parameter);break;case"header":n.push(p.parameter);break}}}convertChannelParameterLocation(t){try{let[r,n]=t.split("#/");if(r==null||n==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(iqo)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${iqo} prefix`,path:this.breadcrumbs});return}let i=r.substring(iqo.length);if(i!=="header"&&i!=="path"&&i!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${i}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return i==="payload"?{type:"query",parameterKey:n}:{type:i,parameterKey:n}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveMessageDocs(t){let r=t,n=new Set;for(;this.context.isReferenceObject(r);){if(n.has(r.$ref))return;n.add(r.$ref);let i=this.context.resolveReference({reference:r,breadcrumbs:this.breadcrumbs});if(!i.resolved)return;r=i.value}return r.description??r.summary}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(oqo)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let n=r.$ref.substring(oqo.length);if(n==null){this.context.errorCollector.collect({message:`Failed to find server with name ${n}`,path:this.breadcrumbs});return}let i=this.context.spec.servers;if(i!=null&&n in i){let o=i[n];return BJ.getServerName(n,o)}return n}resolveFirstServerName(){let t=this.context.spec.servers;if(t==null)return;let r=Object.keys(t)[0];if(r==null)return;let n=t[r];return BJ.getServerName(r,n)}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(z8u))throw new T({message:`Failed to resolve channel path from operation ${t.channel.$ref}`,code:T.Code.ReferenceError});return t.channel.$ref.substring(z8u.length)}}});var yYr,M8u=h(()=>{"use strict";cWt();yYr=class extends BJ{constructor({context:t,breadcrumbs:r,servers:n}){super({context:t,breadcrumbs:r,servers:n})}buildSingleBaseUrlEnvironment(t,r,n){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(n.protocol,n.host),docs:void 0,audiences:void 0,defaultUrl:void 0,urlTemplate:void 0,urlVariables:void 0}}}});var uWt,L8u=h(()=>{"use strict";Wn();hc();rs();N8u();j8u();Q8u();M8u();uWt=class extends PJ{constructor({context:t,breadcrumbs:r,audiences:n}){super({context:t,breadcrumbs:r,audiences:n})}async convert(){return this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.isAsyncAPIV3(this.context)?this.convertChannelMessages():this.convertComponentMessages(),this.convertSchemas(),this.convertServers(),this.convertSecuritySchemes(),this.convertChannels(),this.finalizeIr()}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}convertChannelMessages(){let t=this.context.spec;for(let[r,n]of Object.entries(t.channels??{}))for(let[i,o]of Object.entries(n.messages??{})){if(!this.context.isMessageWithPayload(o)&&!this.context.isReferenceObject(o))continue;let s=["channels",r,"messages",i],a=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:s});if(!this.context.isMessageWithPayload(a))continue;let c=this.context.resolveMaybeReference({schemaOrReference:a.payload,breadcrumbs:s});if(c==null)continue;let u=`${r}_${i}`;this.convertSchema({id:u,breadcrumbs:s,schema:c})}}convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let n=["components","messages",t],i=this.context.resolveMaybeReference({schemaOrReference:r.payload,breadcrumbs:n});i!=null&&this.convertSchema({id:t,breadcrumbs:n,schema:i})}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{}))this.convertSchema({id:t,breadcrumbs:["components","schemas",t],schema:r})}convertSchema({id:t,breadcrumbs:r,schema:n}){let o=new Hm.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:r,schema:n}).convert();o!=null&&this.addSchemaOutputToIr(t,o)}convertServers(){let t;if(this.isAsyncAPIV3(this.context)){let r=this.context.spec.servers;t=new yYr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}else{let r=this.context.spec.servers;t=new gYr({context:this.context,breadcrumbs:["servers"],servers:r}).convert()}this.addEnvironmentsToIr({environmentConfig:t})}convertSecuritySchemes(){if(this.context.authOverrides){let r=JGt({rawApiFileSchema:this.context.authOverrides,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:r.requirement,schemes:r.schemes,docs:r.docs});return}let t=this.convertAsyncApiSecuritySchemes();t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertAsyncApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let o=this.convertSecurityScheme({securityScheme:i,schemeId:r});o!=null&&t.push(o)}return t}convertSecurityScheme({securityScheme:t,schemeId:r}){switch(t.type){case"http":{if(t.scheme?.toLowerCase()==="bearer")return Hp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});if(t.scheme?.toLowerCase()==="basic")return Hp.basic({key:r,username:this.context.casingsGenerator.generateName("username"),password:this.context.casingsGenerator.generateName("password"),usernameEnvVar:void 0,passwordEnvVar:void 0,usernameOmit:!1,passwordOmit:!1,usernamePlaceholder:void 0,passwordPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"apiKey":{if(t.in==="header")return Hp.header({key:r,name:{name:this.context.casingsGenerator.generateName("apiKey"),wireValue:t.name},valueType:co.OPTIONAL_STRING,prefix:void 0,headerEnvVar:void 0,headerPlaceholder:void 0,docs:t.description,playgroundDocs:void 0});break}case"oauth2":return Hp.bearer({key:r,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:t.description,playgroundDocs:void 0})}}convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let i=new qC.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups,o;if(this.isAsyncAPIV3(this.context)){let a=this.context.spec.operations??{};o=new AYr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t,operations:a}).convert()}else o=new hYr({context:this.context,breadcrumbs:["channels",t],websocketGroup:i,channel:r,channelPath:t}).convert();o!=null&&(this.addWebsocketChannelToIr({websocketChannel:o.channel,channelPath:t,audiences:o.audiences,websocketGroup:i}),this.addTypesToIr(o.inlinedTypes))}}}});var lWt,_8u=h(()=>{"use strict";Wn();rs();lWt=class extends S0{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o,s=t.$ref.match(/^.*\/schemas\/(.+)$/),a=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),c=t.$ref.match(/^.*\/messages\/(.+)$/);if(s&&s[1])return o=s[1],this.convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o});if(a&&a[2]){let u=a[1],l=a[2];return o=`${u}_${l}`,this.convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})}else return c&&c[1]?(o=c[1],this.convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o})):{ok:!1}}convertSchemaReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.title;else if(i==="discriminator_key")a=s.value.title??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.title??c}return{ok:!0,reference:en.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}convertV3MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.name;else if(i==="discriminator_key")a=s.value.name??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.name??c}return{ok:!0,reference:en.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}convertV2MessageReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i,typeId:o}){let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.messageId??s.value.name;else if(i==="discriminator_key")a=s.value.messageId??s.value.name??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.messageId??s.value.name??c}return{ok:!0,reference:en.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var U8u=h(()=>{"use strict";L8u();_8u()});function zkm(e){let t=new Set,r,n=new RegExp(jkm.source,"g");for(;(r=n.exec(e))!=null;)r[1]!=null&&t.add(r[1]);return t}var jkm,bYr,V8u=h(()=>{"use strict";rs();jkm=/\{([^}]+)\}/g,bYr=class extends os{document;key="x-fern-base-path";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t=="string")return this.parseString(t);if(typeof t=="object"&&!Array.isArray(t))return this.parseStructured(t);this.context.errorCollector.collect({message:"Expected `x-fern-base-path` to be a string or object",path:this.breadcrumbs})}}parseString(t){if(this.validatePath(t))return{path:t,parameters:[],pathsIncludeBasePath:!1}}parseStructured(t){let r=t.path;if(typeof r!="string"){this.context.errorCollector.collect({message:"`x-fern-base-path.path` must be a string",path:this.breadcrumbs});return}if(!this.validatePath(r))return;let n=zkm(r),i=t.parameters;if(i!=null&&(typeof i!="object"||Array.isArray(i))){this.context.errorCollector.collect({message:"`x-fern-base-path.parameters` must be an object map",path:[...this.breadcrumbs,"parameters"]});return}let o=i??{};for(let c of Object.keys(o))if(!n.has(c)){this.context.errorCollector.collect({message:`Parameter '${c}' does not appear in the base path '${r}'`,path:[...this.breadcrumbs,"parameters",c]});return}let s=[];for(let c of n){let u=o[c];if(u==null){s.push({name:c,type:"string",default:void 0,docs:void 0});continue}if(typeof u!="object"||Array.isArray(u)){this.context.errorCollector.collect({message:`Parameter '${c}' must be an object`,path:[...this.breadcrumbs,"parameters",c]});return}let l=u,p=typeof l.type=="string"?l.type:"string",d=typeof l.docs=="string"?l.docs:void 0;s.push({name:c,type:p,default:l.default,docs:d})}let a=t["paths-include-base-path"]===!0;return{path:r,parameters:s,pathsIncludeBasePath:a}}validatePath(t){return t.startsWith("/")?!0:(this.context.errorCollector.collect({message:"`x-fern-base-path` path must start with '/'",path:this.breadcrumbs}),!1)}}});var EYr,G8u=h(()=>{"use strict";rs();EYr=class extends os{document;key="x-fern-base-url-env";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="string"||t.length===0){this.context.errorCollector.collect({message:"Expected a non-empty string value for x-fern-base-url-env",path:this.breadcrumbs});return}return t}}}});var IYr,q8u=h(()=>{"use strict";rs();IYr=class extends os{document;key="x-fern-global-headers";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-headers",path:this.breadcrumbs});return}return t}}}});function Qkm(e){let r=e["x-fern-default"]??e.default;if(typeof r=="string"||typeof r=="boolean"||typeof r=="number")return r}var vYr,W8u=h(()=>{"use strict";rs();vYr=class extends os{document;key="x-fern-global-parameters";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t==null)return;if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected non-array value for x-fern-global-parameters",path:this.breadcrumbs});return}let r=[];for(let[n,i]of t.entries()){if(typeof i!="object"||i==null||Array.isArray(i)){this.context.errorCollector.collect({message:`x-fern-global-parameters[${n}] must be an object`,path:[...this.breadcrumbs,`${n}`]});continue}let o=i;if(typeof o.name!="string"){this.context.errorCollector.collect({message:`x-fern-global-parameters[${n}].name is required and must be a string`,path:[...this.breadcrumbs,`${n}`,"name"]});continue}r.push({name:o.name,"parameter-name":typeof o["parameter-name"]=="string"?o["parameter-name"]:void 0,in:typeof o.in=="string"?o.in:void 0,target:typeof o.target=="string"?o.target:void 0,env:typeof o.env=="string"?o.env:void 0,default:Qkm(o),optional:typeof o.optional=="boolean"?o.optional:void 0,apply:typeof o.apply=="string"?o.apply:void 0,type:typeof o.type=="string"?o.type:void 0,docs:typeof o.docs=="string"?o.docs:void 0})}return r.length>0?r:void 0}}});function Mkm(e){if(e!=null){if(typeof e=="string")return Zt.Literal.string(e);if(typeof e=="boolean")return Zt.Literal.boolean(e)}}function H8u({globalHeaderOverrides:e,context:t}){let r=[];for(let[n,i]of Object.entries(e.headers??{}))if(typeof i=="string")r.push({name:t.casingsGenerator.generateNameAndWireValue({name:n,wireValue:n}),valueType:co.STRING,env:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:void 0,clientDefault:void 0,defaultValue:void 0});else{let o=i.name??n;r.push({name:t.casingsGenerator.generateNameAndWireValue({name:o,wireValue:n}),valueType:co.STRING,env:i.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},availability:void 0,docs:i.docs,clientDefault:Mkm(i.default),defaultValue:i.default})}return r}var K8u=h(()=>{"use strict";Wn();rs()});function Lkm(e){if(e!=null){if(typeof e=="string")return Zt.Literal.string(e);if(typeof e=="boolean")return Zt.Literal.boolean(e)}}function J8u({globalHeaders:e,context:t}){return e.map(r=>({name:t.casingsGenerator.generateNameAndWireValue({name:r.name??"",wireValue:r.header}),valueType:r.optional?co.OPTIONAL_STRING:co.STRING,env:r.env,v2Examples:r.optional?void 0:_km({header:r,context:t}),availability:void 0,docs:void 0,clientDefault:Lkm(r["x-fern-default"]),defaultValue:void 0}))}function _km({header:e,context:t}){let r=new Yw({breadcrumbs:[],context:t,schema:{type:"string"},example:e.header}),{validExample:n}=r.convert();return{userSpecifiedExamples:{},autogeneratedExamples:{globalHeaderExample:n}}}var Y8u=h(()=>{"use strict";Wn();rs()});function Ukm(e,t,r,n){if(e!=null){if(typeof e=="boolean"){if(t!=null&&t!=="boolean"){n.errorCollector.collect({message:`Default value is a boolean but type is '${t}'; expected a ${t} value`,path:[...r,"default"]});return}return Zt.Literal.boolean(e)}if(typeof e=="string"){if(t==="boolean"){n.errorCollector.collect({message:"Default value is a string but type is 'boolean'; expected a boolean value",path:[...r,"default"]});return}if(t==="integer"||t==="double"||t==="number"){n.errorCollector.collect({message:`Default value is a string but type is '${t}'; expected a numeric value`,path:[...r,"default"]});return}return Zt.Literal.string(e)}if(typeof e=="number"){if(t==="boolean"){n.errorCollector.collect({message:"Default value is a number but type is 'boolean'; expected a boolean value",path:[...r,"default"]});return}if(t==="string"){n.errorCollector.collect({message:"Default value is a number but type is 'string'; expected a string value",path:[...r,"default"]});return}if(t==="integer"&&!Number.isInteger(e)){n.errorCollector.collect({message:`Default value ${e} is not an integer`,path:[...r,"default"]});return}return Zt.Literal.string(String(e))}n.errorCollector.collect({message:`Default value has unsupported type '${typeof e}'; expected a string, number, or boolean`,path:[...r,"default"]})}}function Vkm(e,t,r){switch(e){case void 0:case"body":return Zt.GlobalParameterLocation.Body;case"query":return Zt.GlobalParameterLocation.Query;case"header":return Zt.GlobalParameterLocation.Header;case"path":return Zt.GlobalParameterLocation.Path;default:return r.errorCollector.collect({message:`Invalid global parameter location '${e}'; expected one of: body, query, header, path`,path:t}),Zt.GlobalParameterLocation.Body}}function Gkm(e,t,r){switch(e){case void 0:return;case"explicit":return Zt.GlobalParameterApplyMode.Explicit;case"auto":return Zt.GlobalParameterApplyMode.Auto;default:r.errorCollector.collect({message:`Invalid global parameter apply mode '${e}'; expected one of: explicit, auto`,path:t});return}}function qkm(e,t){let r=Wkm(e);return t===!0?Zt.TypeReference.container(Zt.ContainerType.optional(r)):r}function Wkm(e){switch(e){case"boolean":return Zt.TypeReference.primitive({v1:"BOOLEAN",v2:Zt.PrimitiveTypeV2.boolean({default:void 0})});case"integer":return Zt.TypeReference.primitive({v1:"INTEGER",v2:Zt.PrimitiveTypeV2.integer({default:void 0,validation:void 0})});case"double":case"number":return Zt.TypeReference.primitive({v1:"DOUBLE",v2:Zt.PrimitiveTypeV2.double({default:void 0,validation:void 0})});default:return co.STRING}}function Hkm(e){return e.target!=null?e.target:e.name}function X8u({globalParameters:e,context:t}){let r=new Map;for(let[n,i]of e.entries()){let o=r.get(i.name);o!=null?t.errorCollector.collect({message:`Duplicate global parameter name '${i.name}' at index ${n} (first seen at index ${o}). Each global parameter must have a unique name.`,path:["x-fern-global-parameters",`${n}`,"name"]}):r.set(i.name,n)}return e.map((n,i)=>({param:n,index:i})).filter(({param:n,index:i})=>r.get(n.name)===i).map(({param:n,index:i})=>{let o=["x-fern-global-parameters",`${i}`],s=Vkm(n.in,[...o,"in"],t),a=n["parameter-name"]??n.name;return{id:n.name,name:t.casingsGenerator.generateNameAndWireValue({name:a,wireValue:n.name}),location:s,target:Hkm(n),valueType:qkm(n.type,n.optional),env:n.env,clientDefault:Ukm(n.default,n.type,o,t),optional:n.optional,apply:Gkm(n.apply,[...o,"apply"],t),docs:n.docs}})}var Z8u=h(()=>{"use strict";Wn();rs()});var CYr,$8u=h(()=>{"use strict";ct();rs();CYr=class extends Hm.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={},n=this.getSchema();if(n!=null){let i=this.context.convertBreadcrumbsToName([...this.breadcrumbs,this.parameter.name]),s=new Hm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,this.parameter.name,"schema"],schemaOrReference:n,wrapAsOptional:this.parameter.required==null||!this.parameter.required,schemaIdOverride:i}).convert();s!=null&&(t=s.type,r=s.inlinedTypes??{})}return this.convertToOutput({schema:n??{type:"string"},typeReference:t,inlinedTypes:r})}getSchema(){if(this.parameter.schema!=null)return this.parameter.schema;if(!(!this.context.settings.respectParameterContent||this.parameter.in!=="header"||this.parameter.content==null)){for(let[t,r]of Object.entries(this.parameter.content))if(r.schema!=null&&of.parse(t)?.isJSON())return r.schema}}}});function Jkm({encoding:e}){if(e){if(e.explode)return"exploded";if(e.style==="form")return"form";if(e.contentType)return Kkm[e.contentType]}}var xYr,Kkm,eGu=h(()=>{"use strict";ct();Wn();hc();rs();xYr=class extends Hm.AbstractConverters.AbstractMediaTypeObjectConverter{contentType;mediaType;description;required;schemaId;streamingExtension;queryParameters;constructor({context:t,breadcrumbs:r,contentType:n,mediaType:i,description:o,required:s,group:a,method:c,streamingExtension:u,queryParameters:l}){super({context:t,breadcrumbs:r,group:a,method:c}),this.contentType=n,this.mediaType=i,this.description=o,this.required=s,this.schemaId=[...this.group,this.method,"Request"].join("_"),this.streamingExtension=u,this.queryParameters=l??[]}get bodyRequired(){return this.required===!1?!1:void 0}convert(){return this.streamingExtension?.type=="streamCondition"?this.convertStreamConditionRequestBody():this.convertNonStreamConditionRequestBody()}convertStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleStreamConditionJsonOrFormContent({contentType:this.contentType})}convertNonStreamConditionRequestBody(){if(this.isOrderedJsonOrFormContentType())return this.handleJsonOrFormContent({contentType:this.contentType});if(of.parse(this.contentType)?.isMultipart())return this.handleMultipartContent({contentType:this.contentType});if(this.isBinaryContentType())return this.handleBinaryContent({contentType:this.contentType})}isOrderedJsonOrFormContentType(){let t=of.parse(this.contentType);return t?t.isJSON()||t.isURLEncoded()||t.isPlainText()||t.isCSV()||t.isHTML()||t.isXML()||t.isDNS()||t.isApplicationText():!1}isBinaryContentType(){let t=of.parse(this.contentType);return t?t.isBinary():!1}handleJsonOrFormContent({contentType:t}){let r=this.mediaType;if(r==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});if(n==null)return this.handleSchemalessJsonContent({contentType:t,mediaTypeObject:r});let i=n.schema?.typeDeclaration.shape;return i?.type==="object"?this.hasBodyQueryParameterOverlap(i.properties)?{requestBody:Od.reference({contentType:t,docs:this.description,requestBodyType:n.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}:{requestBody:Od.inlinedRequestBody({contentType:t,docs:this.description??n.schema?.typeDeclaration.docs,name:this.context.casingsGenerator.generateName(this.schemaId),extendedProperties:i.extendedProperties,extends:i.extends,properties:i.properties,extraProperties:i.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes}),inlinedPropertiesByAudience:n.schema?.propertiesByAudience}:{requestBody:Od.reference({contentType:t,docs:this.description,requestBodyType:n.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n.inlinedTypes??{}}}handleSchemalessJsonContent({contentType:t,mediaTypeObject:r}){if(!(r.example!=null||r.examples!=null&&Object.keys(r.examples).length>0))return;let i={userSpecifiedExamples:{},autogeneratedExamples:{}},o=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:r,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`}),s=new Set;for(let[a,c]of o){let u=this.context.resolveExampleWithValue(c),l=this.context.resolveExampleRecursively({example:c,breadcrumbs:this.breadcrumbs}),p=a;if(this.context.isExampleWithSummary(l)){let d=l.summary;s.has(d)||(p=d)}s.add(p),u!=null&&(i.userSpecifiedExamples[p]=u)}return{requestBody:Od.reference({contentType:t,docs:this.description,requestBodyType:en.unknown(),required:this.bodyRequired,v2Examples:i}),streamRequestBody:void 0,inlinedTypes:{}}}handleMultipartContent({contentType:t}){let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,resolveSchema:!0,contentType:t});if(n==null)return;let i=n.schema?.typeDeclaration.shape;if(i?.type==="object")return{requestBody:Od.fileUpload({contentType:t,docs:this.description,name:this.context.casingsGenerator.generateName(this.schemaId),properties:i.properties.map(o=>{let s=r.encoding?.[ur(o.name)];return this.convertRequestBodyProperty({property:o,contentType:t,encoding:s})}),v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:n.inlinedTypes}),examples:n.examples}}handleBinaryContent({contentType:t}){let r=this.mediaType;if(r==null)return;let n=this.parseMediaTypeObject({mediaTypeObject:r,schemaId:this.schemaId,contentType:t});return{requestBody:Od.bytes({contentType:t,isOptional:this.required===!1,docs:this.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:r,exampleGenerationStrategy:"request"})}),streamRequestBody:void 0,inlinedTypes:n?.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r,encoding:n}){let{isFile:i,isOptional:o,isArray:s}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return i?s?Xx.file(cQ.fileArray({key:t.name,isOptional:o,contentType:r,docs:t.docs})):Xx.file(cQ.file({key:t.name,isOptional:o,contentType:r,docs:t.docs})):Xx.bodyProperty({...t,contentType:n?.contentType??r,style:Jkm({encoding:n}),name:t.name})}handleStreamConditionJsonOrFormContent({contentType:t}){if(this.streamingExtension?.type!=="streamCondition")return;let r=this.mediaType;if(r==null||r.schema==null)return;let n=this.context.resolveMaybeReference({schemaOrReference:r.schema,breadcrumbs:[...this.breadcrumbs,"content",t,"schema"]});if(n==null)return;let i=n.properties?.[this.streamingExtension.streamConditionProperty];if(i!=null&&this.context.isReferenceObject(i)&&(i=void 0),i==null){if(n.oneOf==null&&n.anyOf==null)return;i={type:"boolean"}}let o=this.buildStreamConditionRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!0,contentType:t,mediaTypeObject:r}),s=this.buildStreamConditionRequestBody({streamConditionProperty:i,resolvedMediaTypeSchema:n,isStreaming:!1,contentType:t,mediaTypeObject:r});if(!(o==null||s==null))return{requestBody:s.requestBody,streamRequestBody:o.requestBody,inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:this.schemaId,inlinedTypes:{...o.inlinedTypes,...s.inlinedTypes}})}}buildStreamConditionRequestBody({streamConditionProperty:t,resolvedMediaTypeSchema:r,isStreaming:n,contentType:i,mediaTypeObject:o}){if(this.streamingExtension==null||this.streamingExtension.type!=="streamCondition")return;let s={...r,properties:{...r.properties,[this.streamingExtension.streamConditionProperty]:{...t,type:"boolean",const:n}},required:[...r.required??[],this.streamingExtension.streamConditionProperty]},a={...o,schema:s},c=this.parseMediaTypeObject({mediaTypeObject:a,schemaId:this.schemaId,contentType:i});if(c==null)return;let u=c.schema?.typeDeclaration.shape;return u?.type==="object"?{requestBody:Od.inlinedRequestBody({contentType:i,docs:this.description??c.schema?.typeDeclaration.docs,name:this.context.casingsGenerator.generateName(n?this.streamingExtension?.streamRequestName??`${this.schemaId}_streaming`:this.schemaId),extendedProperties:u.extendedProperties,extends:u.extends,properties:u.properties,extraProperties:u.extraProperties,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes}:{requestBody:Od.reference({contentType:i,docs:this.description,requestBodyType:c.type,required:this.bodyRequired,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:a,exampleGenerationStrategy:"request"})}),inlinedTypes:c.inlinedTypes??{}}}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:n}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:n}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:n}):{isFile:this.context.isFile(t),isOptional:r??!1,isArray:n??!1}}hasBodyQueryParameterOverlap(t){if(this.queryParameters.length===0)return!1;let r=new Set(this.queryParameters.map(n=>ur(n.name).toLowerCase()));return t.some(n=>r.has(ur(n.name).toLowerCase()))}},Kkm={"application/json":"json"}});function Zkm(e){return e?.header!=null}var Ykm,Xkm,glt,sqo=h(()=>{"use strict";ct();Wn();hc();rs();qi();$8u();eGu();Ykm=/{([^}]+)}/g,Xkm=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]),glt=class extends co{operation;method;path;pathItemParameters;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}){super({context:t,breadcrumbs:r}),this.operation=n,this.method=i,this.path=o,this.pathItemParameters=s??[]}convertHttpMethod(){switch(this.method){case"get":return Tm.Get;case"post":return Tm.Post;case"put":return Tm.Put;case"delete":return Tm.Delete;case"patch":return Tm.Patch;case"head":return Tm.Head;default:return}}convertParameters({breadcrumbs:t}){let r=[],n=[],i=[],o=this.mergeParameters(this.pathItemParameters,this.operation.parameters??[]);if(o.length===0)return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i};for(let s of o){let a=this.context.resolveMaybeReference({schemaOrReference:s,breadcrumbs:t});if(a==null)continue;let u=new CYr({context:this.context,breadcrumbs:t,parameter:a}).convert();if(u!=null)switch(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},u.type){case"path":r.push(u.parameter);break;case"query":n.push(u.parameter);break;case"header":{let l=Vr(u.parameter.name),p=ur(u.parameter.name),d=!1,f=this.context.authOverrides?.["auth-schemes"];if(f!=null){for(let g of Object.values(f))if(Zkm(g)&&g.header.toLowerCase()===p.toLowerCase()){d=!0;break}}let m=this.context.globalHeaderNames;if(m!=null){for(let g of m)if(g.toLowerCase()===p.toLowerCase()){d=!0;break}}!Xkm.has(l.toLowerCase())&&!d&&i.push(u.parameter);break}}}return this.checkMissingPathParameters(r),{pathParameters:r,queryParameters:n,headers:i}}mergeParameters(t,r){if(t.length===0)return r;if(r.length===0)return t;let n=new Set;for(let o of r){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs});s!=null&&n.add(`${s.in}:${s.name}`)}return[...t.filter(o=>{let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:this.breadcrumbs});return s==null?!1:!n.has(`${s.in}:${s.name}`)}),...r]}checkMissingPathParameters(t){let n=[...this.path.matchAll(Ykm)].map(i=>i[1]).filter(i=>!t.some(o=>Vr(o.name)===i));for(let i of n){if(i==null)continue;let o=`${i}_example`;t.push({name:this.context.casingsGenerator.generateName(i),valueType:co.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[o]:this.generateStringParameterExample({example:i})}},explode:void 0,clientDefault:void 0})}}convertRequestBody({breadcrumbs:t,group:r,method:n,streamingExtension:i,queryParameters:o}){if(this.operation.requestBody==null)return;let s=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:t});if(s==null)return null;let a=[];for(let[c,u]of Object.entries(s.content)){let p=new xYr({context:this.context,breadcrumbs:t,contentType:c,mediaType:u,description:s.description,required:s.required,group:r??[],method:n,streamingExtension:i,queryParameters:o}).convert();p!=null&&(this.inlinedTypes={...this.inlinedTypes,...p.inlinedTypes},a.push({requestBody:p.requestBody,streamRequestBody:p.streamRequestBody,examples:p.examples,inlinedPropertiesByAudience:p.inlinedPropertiesByAudience}))}return a}computeGroupNameAndLocationFromExtensions(){let r=new qC.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,i=new qC.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:i,method:r}}evaluateMethodNameFromOperation(){let t=this.operation.operationId;return t??(this.operation.summary!=null?ti(this.operation.summary):ti(`${this.method}_${this.path.split("/").join("_")}`))}sanitizeMethodName(t){return t.includes(".")?ti(t):t}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.evaluateMethodNameFromOperation();if(t==null)return{method:this.sanitizeMethodName(r)};let n=this.context.settings.respectOperationIdWordBoundaries,i=RH(t,n),o=RH(r,n);return rE(i,o)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,methodName:r,methodNameTokens:o})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,methodName:n,methodNameTokens:i}){if(r.some((a,c)=>a!==i[c]))return{group:[t],method:this.sanitizeMethodName(n)};let s=i.slice(r.length);return s[0]!=null&&/^\d/.test(s[0])?{group:[t],method:this.sanitizeMethodName(n)}:{group:[t],method:ti(s.join("_"))}}generateStringParameterExample({example:t}){let r=new Hm.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:n}=r.convert();return n}}});var Alt,aqo=h(()=>{"use strict";Wn();sqo();Alt=class extends glt{constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s})}convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=[...this.breadcrumbs,"Payload"],{headers:o,queryParameters:s}=this.convertParameters({breadcrumbs:i}),a=this.convertRequestBody({breadcrumbs:i,group:r,method:n,streamingExtension:void 0,queryParameters:s});if(a==null)return;let c=a[0]?.requestBody;if(c==null)return;let u=c.type==="inlinedRequestBody"?a[0]?.inlinedPropertiesByAudience:void 0,l,p;if(c.type==="inlinedRequestBody")l=oT.inlinedPayload({name:c.name,extends:c.extends,properties:c.properties});else if(c.type==="reference")l=oT.reference({payloadType:c.requestBodyType,docs:c.docs});else if(c.type==="fileUpload")p={name:c.name,properties:c.properties,docs:c.docs,v2Examples:c.v2Examples,contentType:c.contentType},l=oT.inlinedPayload({name:c.name,extends:[],properties:[]});else return;let d=this.convertWebhookResponses();return{audiences:this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],group:r,inlinedPayloadPropertiesByAudience:u,webhook:{id:`${r?.join(".")??""}.${n}`,name:this.context.casingsGenerator.generateName(n),displayName:this.operation.summary,method:t,headers:o,payload:l,signatureVerification:void 0,fileUploadPayload:p,responses:d.length>0?d:void 0,examples:[],availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:{autogeneratedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(c.v2Examples?.autogeneratedExamples??{}),userSpecifiedExamples:this.getWebhookV2ExamplesFromRequestBodyV2Examples(c.v2Examples?.userSpecifiedExamples??{})}},inlinedTypes:this.inlinedTypes}}convertWebhookResponses(){let t=[];if(this.operation.responses==null)return t;for(let[r,n]of Object.entries(this.operation.responses)){let i=/^\d[Xx]{2}$/.test(r),o;if(i)o=parseInt(r.charAt(0))*100;else if(o=parseInt(r),isNaN(o))continue;let a=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"responses",r]})?.description;t.push({statusCode:o,isWildcardStatusCode:i?!0:void 0,body:void 0,docs:a})}return t}getWebhookV2ExamplesFromRequestBodyV2Examples(t){return Object.fromEntries(Object.entries(t).map(([r,n])=>[r,{name:r,payload:n}]))}}});var tGu,rGu=h(()=>{"use strict";tGu=["get","post","put","delete","patch","head"]});var SYr,nGu=h(()=>{"use strict";rs();SYr=class extends os{operation;key="x-fern-global-parameter";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;if(typeof t=="string")return[t];if(!Array.isArray(t)){this.context.errorCollector.collect({message:"Received unexpected value for x-fern-global-parameter; expected a string or array of strings",path:this.breadcrumbs});return}let r=[];for(let[n,i]of t.entries()){if(typeof i!="string"){this.context.errorCollector.collect({message:`x-fern-global-parameter[${n}] must be a string`,path:[...this.breadcrumbs,`${n}`]});continue}r.push(i)}return r.length>0?r:void 0}}});var wYr,iGu=h(()=>{"use strict";rs();wYr=class extends os{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}}});var $km,eFm,tFm,rFm,cqo,oGu=h(()=>{"use strict";cn();$km=De.object({cursor:De.string(),next_cursor:De.string(),results:De.string()}),eFm=De.object({offset:De.string(),results:De.string(),step:De.string().optional(),"has-next-page":De.string().optional()}),tFm=De.object({next_uri:De.string(),results:De.string()}),rFm=De.object({next_path:De.string(),results:De.string()}),cqo=De.union([De.boolean(),$km,eFm,tFm,rFm])});var uqo,gwe,TYr,sGu=h(()=>{"use strict";rs();oGu();uqo="$request.",gwe="$response.",TYr=class extends os{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:n,context:i}){super({breadcrumbs:t,context:i}),this.operation=r,this.document=n}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=cqo.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let n=this.getExtensionValue(this.document);if(n==null)return;if(typeof n=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let i=cqo.safeParse(n);if(!i.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${i.error.message}`,path:this.breadcrumbs});return}if(typeof i.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:i.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:S0.maybeTrimPrefix(r.cursor,uqo),nextCursor:S0.maybeTrimPrefix(r.next_cursor,gwe),results:S0.maybeTrimPrefix(r.results,gwe)};let n=t;if("next_uri"in n)return{type:"uri",nextUri:S0.maybeTrimPrefix(n.next_uri,gwe),results:S0.maybeTrimPrefix(n.results,gwe)};let i=t;if("next_path"in i)return{type:"path",nextPath:S0.maybeTrimPrefix(i.next_path,gwe),results:S0.maybeTrimPrefix(i.results,gwe)};let o=t;return{type:"offset",offset:S0.maybeTrimPrefix(o.offset,uqo),results:S0.maybeTrimPrefix(o.results,gwe),step:o.step!=null?S0.maybeTrimPrefix(o.step,uqo):void 0,hasNextPage:o["has-next-page"]!=null?S0.maybeTrimPrefix(o["has-next-page"],gwe):void 0}}}});function lqo(e){let t=e["x-fern-streaming"];if(t==null||typeof t=="boolean")return;let r=t.resumable;return typeof r=="boolean"?r:void 0}var nFm,iFm,oFm,OYr,aGu=h(()=>{"use strict";rs();cn();nFm="$request.",iFm=De.object({"stream-condition":De.string().optional(),format:De.enum(["sse","json"]).optional(),"stream-description":De.string().optional(),"stream-request-name":De.string().optional(),"response-stream":De.any(),response:De.any(),terminator:De.string().optional(),resumable:De.boolean().optional()}),oFm=De.union([De.boolean(),iFm]),OYr=class extends os{document;operation;key="x-fern-streaming";constructor({breadcrumbs:t,document:r,operation:n,context:i}){super({breadcrumbs:t,context:i}),this.document=r,this.operation=n}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=oFm.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json",terminator:void 0,resumable:!1}:void 0;let n=r.data.resumable??lqo(this.document)??!1;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format,terminator:r.data.terminator,resumable:n};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing stream-condition property without specified format.",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",terminator:r.data.terminator,streamDescription:r.data["stream-description"],streamConditionProperty:S0.maybeTrimPrefix(r.data["stream-condition"],nFm),streamRequestName:r.data["stream-request-name"],responseStream:r.data["response-stream"],response:r.data.response,resumable:n}}}});var PYr,cGu=h(()=>{"use strict";rs();PYr=class extends os{operation;key="x-fern-subtitle";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"Received unexpected non-string value for x-fern-subtitle",path:this.breadcrumbs});return}return t}}}});var BYr,uGu=h(()=>{"use strict";rs();BYr=class extends os{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}}});function sFm(e){return gi(e)&&typeof e.$ref=="string"}function aFm(e,t){if(e!=null){if(typeof e=="string")return e;if(sFm(e)){let r=(0,lGu.resolve)(t??process.cwd(),e.$ref);if((0,DYr.existsSync)(r))try{return(0,DYr.readFileSync)(r,"utf-8")}catch{return}}}}var DYr,lGu,RYr,pGu=h(()=>{"use strict";ct();rs();DYr=require("fs"),lGu=require("path");RYr=class extends os{operation;baseDir;key="x-codeSamples";constructor({context:t,breadcrumbs:r,operation:n,baseDir:i}){super({breadcrumbs:r,context:t}),this.operation=n,this.baseDir=i}convert(){let t=gi(this.operation)?this.operation:{},r=t["x-codeSamples"],n=t["x-code-samples"],i=Array.isArray(r)?r:[],o=Array.isArray(n)?n:[],s=[...i,...o];if(s.length===0)return;let a=[];for(let c of s){if(!gi(c))continue;let u=c,l=u.lang,p=u.label,d=u.source;if(typeof l!="string")continue;let f=aFm(d,this.baseDir);f!=null&&a.push({name:typeof p=="string"?p:l,language:l,code:f,install:void 0,docs:void 0})}if(a.length!==0)return[{"code-samples":a}]}}});function cFm(e){return gi(e)&&typeof e.$ref=="string"}function uFm(e,t){if(e!=null){if(typeof e=="string")return e;if(cFm(e)){let r=(0,fGu.resolve)(t??process.cwd(),e.$ref);if((0,FYr.existsSync)(r))try{return(0,FYr.readFileSync)(r,"utf-8")}catch{return}}}}function lFm(e,t){if(!Array.isArray(e))return[];let r=[];for(let n of e){if(!gi(n))continue;let o=uFm(n.code,t);o!=null&&r.push({...n,code:o})}return r}var FYr,fGu,kYr,dGu=h(()=>{"use strict";ct();Io();rs();FYr=require("fs"),fGu=require("path");kYr=class extends os{operation;baseDir;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:n,baseDir:i}){super({breadcrumbs:r,context:t}),this.operation=n,this.baseDir=i}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).map(o=>{if(!gi(o))return o;let a=o["code-samples"];if(a!=null){let c=lFm(a,this.baseDir);return{...o,"code-samples":c}}return o}).filter(o=>{let s=tm.serialization.ExampleEndpointCallSchema.parse(o);return s.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),s.ok})}}});var pWt,mGu=h(()=>{"use strict";rs();pWt=class extends os{document;key="x-fern-explorer";constructor({breadcrumbs:t,document:r,context:n}){super({breadcrumbs:t,context:n}),this.document=r}convert(){let t=this.getExtensionValue(this.document);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-explorer",path:this.breadcrumbs});return}return t}}}});var fWt,hGu=h(()=>{"use strict";ct();Wn();rs();fWt=class extends Hm.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;convertedResponseHeaders;constructor({context:t,breadcrumbs:r,responseBody:n,group:i,method:o,statusCode:s,streamingExtension:a}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseBody=n,this.statusCode=s,this.streamingExtension=a}convert(){if(parseInt(this.statusCode)===204){this.responseBody.content!=null&&Object.keys(this.responseBody.content).length>0&&this.context.errorCollector.collect({message:"A 204 (No Content) response declares a body, but a 204 response cannot include one. Ignoring the declared body and treating the success response as optional.",path:this.breadcrumbs});return}return this.shouldConvertAsStreaming()?this.convertStreamingResponseBody():this.convertNonStreamingResponseBody()}convertStreamingResponseBody(){if(this.streamingExtension!=null){if(this.streamingExtension.type=="streamCondition"){let t=this.streamingExtension.responseStream,r=this.streamingExtension.response,n=[...this.group,this.method,"Response",this.statusCode].join("_"),i=`${n}_streaming`,o=this.parseMediaTypeSchemaOrReference({schemaOrReference:t,schemaId:i}),s=this.parseMediaTypeSchemaOrReference({schemaOrReference:r,schemaId:n});return this.convertStreamConditionResponse({convertedStreamingSchema:o,convertedNonStreamingSchema:s})}if(this.streamingExtension.type==="stream"){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}),n=this.streamingExtension.format==="sse"?[...r.filter(i=>i.includes("text/event-stream")),...r.filter(i=>!i.includes("text/event-stream"))]:r;for(let i of n){let o=this.responseBody.content?.[i];if(o==null)continue;let s=this.parseMediaTypeObject({mediaTypeObject:o,schemaId:t,contentType:this.streamingExtension.format});if(s!=null)return this.convertStreamingResponse({mediaTypeObject:o,convertedSchema:s})}}}}convertNonStreamingResponseBody(){let t=[...this.group,this.method,"Response",this.statusCode].join("_"),r=Object.keys(this.responseBody.content??{}).filter(o=>o.includes("json"));for(let o of r){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null&&this.shouldReturnJsonResponse(o))return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}let n=Object.keys(this.responseBody.content??{}).filter(o=>!o.includes("json"));for(let o of n){let s=this.responseBody.content?.[o];if(s==null)continue;let a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:o});if(a!=null){if(this.isBinarySchema(a))return this.shouldReturnBytesResponse()?this.returnBytesResponse({mediaTypeObject:s}):this.returnFileDownloadResponse({mediaTypeObject:s});if(this.shouldReturnTextResponse(o))return this.returnTextResponse({mediaTypeObject:s,contentType:o})}}let i=parseInt(this.statusCode);if(!isNaN(i)&&i>=200&&i<300&&i!==204){let o=r.map(c=>this.responseBody.content?.[c]).find(c=>c!=null),s={schema:{type:"object",description:"Empty response body"},...o?.examples!=null&&{examples:o.examples},...o?.example!=null&&{example:o.example}},a=this.parseMediaTypeObject({mediaTypeObject:s,schemaId:t,contentType:"application/json",resolveSchema:!0});if(a!=null)return this.returnJsonResponse({mediaTypeObject:s,convertedSchema:a})}}convertStreamConditionResponse({convertedStreamingSchema:t,convertedNonStreamingSchema:r}){if(t==null||r==null)return;let n=this.responseBody.description;return this.streamingExtension?.type==="streamCondition"&&this.streamingExtension.streamDescription!=null&&(n=this.streamingExtension.streamDescription),{responseBody:_u.json(gI.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:r.schema?.typeDeclaration.v2Examples})),streamResponseBody:_u.streaming(Ev.json({docs:n,payload:t.type,terminator:this.streamingExtension?.terminator,v2Examples:t.schema?.typeDeclaration.v2Examples})),inlinedTypes:{...t.inlinedTypes,...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},headers:this.convertResponseHeaders().headers}}convertStreamingResponse({mediaTypeObject:t,convertedSchema:r}){if(this.streamingExtension==null)return;switch(this.streamingExtension.format){case"json":return{responseBody:_u.streaming(Ev.json({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers};case"sse":return{responseBody:_u.streaming(Ev.sse({docs:this.responseBody.description,payload:r.type,terminator:this.streamingExtension?.terminator,resumable:this.streamingExtension?.resumable,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers};default:return}}returnJsonResponse({mediaTypeObject:t,convertedSchema:r}){return{responseBody:_u.json(gI.response({responseBodyType:r.type,docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})})),streamResponseBody:void 0,inlinedTypes:{...r.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:r.examples,headers:this.convertResponseHeaders().headers}}returnBytesResponse({mediaTypeObject:t}){return{responseBody:_u.bytes({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}returnFileDownloadResponse({mediaTypeObject:t}){return{responseBody:_u.fileDownload({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"})}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}returnTextResponse({mediaTypeObject:t,contentType:r}){return{responseBody:_u.text({docs:this.responseBody.description,v2Examples:this.convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:!0,exampleGenerationStrategy:"response"}),contentType:of.parse(r)?.isPlainText()?void 0:r}),streamResponseBody:void 0,inlinedTypes:this.convertResponseHeaders().inlinedTypes,headers:this.convertResponseHeaders().headers}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}shouldConvertAsStreaming(){return this.streamingExtension!=null}shouldReturnJsonResponse(t){return t.includes("json")}shouldReturnBytesResponse(){return this.context.settings.useBytesForBinaryResponse&&this.streamingExtension==null}shouldReturnTextResponse(t){return of.parse(t)?.isText()??!1}convertResponseHeaders(){return this.convertedResponseHeaders??=dlt({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseBody.headers}),this.convertedResponseHeaders}}});var NYr,gGu=h(()=>{"use strict";ct();Wn();rs();NYr=class extends Hm.AbstractConverters.AbstractMediaTypeObjectConverter{responseError;statusCode;methodName;isWildcardStatusCode;convertedResponseHeaders;constructor({context:t,breadcrumbs:r,responseError:n,group:i,method:o,methodName:s,statusCode:a,isWildcardStatusCode:c}){super({context:t,breadcrumbs:r,group:i,method:o}),this.responseError=n,this.statusCode=a,this.methodName=s,this.isWildcardStatusCode=c}convert(){if(!this.responseError.content){let n=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(n==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}let i=this.getErrorIdFromErrorName(n);return{error:{error:{name:this.context.casingsGenerator.generateName(i),fernFilepath:{allParts:[],packagePath:[],file:void 0},errorId:i},docs:this.responseError.description},errorType:en.unknown(),displayName:n,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:this.convertResponseHeaders().inlinedTypes,examples:{},headers:this.convertResponseHeaders().headers}}let t=Object.keys(this.responseError.content).filter(n=>n.includes("json")),r=this.getErrorNameForStatusCode(this.statusCode,this.isWildcardStatusCode);if(r==null){this.context.logger.warn(`No error name found for status code ${this.statusCode}`);return}for(let n of[...t]){let i=this.responseError.content?.[n];if(i==null)continue;let o=this.parseMediaTypeObject({mediaTypeObject:i,schemaId:BH(`${this.methodName}Request${r}`),contentType:n});if(o==null)continue;let s=this.getErrorIdFromErrorName(r);if(o.schema!=null)return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.schema.typeDeclaration.name.fernFilepath,convertedSchema:o,mediaTypeObject:i});if(o.type.type==="named")return this.constructErrorConverterOutput({errorName:r,errorId:s,fernFilepath:o.type.fernFilepath,convertedSchema:o,mediaTypeObject:i})}}constructErrorConverterOutput({errorName:t,errorId:r,fernFilepath:n,convertedSchema:i,mediaTypeObject:o}){return{error:{error:{name:this.context.casingsGenerator.generateName(r),fernFilepath:n,errorId:r},docs:this.responseError.description},errorType:i.type,displayName:t,statusCode:this.statusCode,isWildcardStatusCode:this.isWildcardStatusCode,inlinedTypes:{...i.inlinedTypes,...this.convertResponseHeaders().inlinedTypes},examples:this.convertErrorExamples({mediaTypeObject:o}),headers:this.convertResponseHeaders().headers}}convertErrorExamples({mediaTypeObject:t}){let r=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_error_example`});if(r.length===0)return;let n=new Set,i={};for(let[o,s]of r){let a=this.context.resolveExampleWithValue(s),c=this.context.resolveExampleRecursively({example:s,breadcrumbs:this.breadcrumbs}),u=this.getIdForErrorExample({key:o,example:c,usedExampleNames:n});n.add(u),a!=null&&(i[u]=a)}return Object.keys(i).length>0?i:void 0}getIdForErrorExample({key:t,example:r,usedExampleNames:n}){if(this.context.isExampleWithSummary(r)){let i=r.summary;if(!n.has(i))return i;let o=`${i} (${t})`;return n.has(o)?t:o}return t}getErrorNameForStatusCode(t,r){if(r){if(t===400)return"ClientRequestError";if(t===500)return"ServerError"}return pYr[t]}getErrorIdFromErrorName(t){return this.context.enableUniqueErrorsPerEndpoint?BH(`${this.methodName}Request${t}`):t}convertResponseHeaders(){return this.convertedResponseHeaders??=dlt({context:this.context,breadcrumbs:this.breadcrumbs,headers:this.responseError.headers}),this.convertedResponseHeaders}}});var jYr,AGu=h(()=>{"use strict";Io();Wn();hc();R5();rs();qi();pGu();dGu();mGu();hGu();gGu();sqo();jYr=class e extends glt{idempotent;subtitle;globalParameterIds;idToAuthScheme;topLevelServers;pathLevelServers;streamingExtension;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s,idempotent:a,subtitle:c,globalParameterIds:u,idToAuthScheme:l,topLevelServers:p,pathLevelServers:d,streamingExtension:f}){super({context:t,breadcrumbs:r,operation:n,method:i,path:o,pathItemParameters:s}),this.idempotent=a,this.subtitle=c,this.globalParameterIds=u,this.idToAuthScheme=l,this.topLevelServers=p,this.pathLevelServers=d,this.streamingExtension=f}convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:n}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),i=this.getGroupDisplayName(r),o=this.getGroupDescription(r),{headers:s,pathParameters:a,queryParameters:c}=this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),u=this.collectQueryParameterAudiences({breadcrumbs:[...this.breadcrumbs,"parameters"]}),l=this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:n,streamingExtension:this.streamingExtension,queryParameters:c}),p=l?.[0]?.requestBody,d=l?.[0]?.streamRequestBody,f=l?.[0]?.inlinedPropertiesByAudience,m={requestBodies:l?.map(ue=>ue.requestBody)},g=this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:n,streamingExtension:this.streamingExtension}),A=g?.response,y=g?.streamResponse,I=g!=null?g.errors:[],x={},v=I.map(ue=>ue.error),S=sb(this.path),B=this.context.perSpecBasePath,R=this.getEndpointBaseUrl(),D=this.getEndpointBaseUrls(),O=this.convertExamples({httpPath:S,httpMethod:t,baseUrl:R});if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0){let ue=this.synthesizeEndpointExamplesFromNativeRequestBody({httpPath:S,httpMethod:t,baseUrl:R});if(ue!=null)for(let[Oe,Ie]of Object.entries(ue))O.examples[Oe]=Ie}if(Object.keys(O.examples).length===0&&Object.keys(O.streamExamples).length===0&&l!=null&&l.length>1){let ue=this.synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:l,httpPath:S,httpMethod:t,baseUrl:R});if(ue!=null)for(let[Oe,Ie]of Object.entries(ue))O.examples[Oe]=Ie}let z=new Set(this.operation.security?.flatMap(ue=>Object.keys(ue))??[]),Y=this.authSchemeToHeaders(Array.from(z));Y.length>0&&s.push(...Y);for(let ue of I){let Oe=ue.error,Ie=ue.errorType,je=Oe.error.errorId,Ge=ue.examples;x[je]={name:Oe.error,displayName:ue.displayName,discriminantValue:{name:Oe.error.name,wireValue:je},type:Ie,statusCode:ue.statusCode,isWildcardStatusCode:ue.isWildcardStatusCode,docs:Oe.docs,examples:[],v2Examples:{userSpecifiedExamples:Ge??{},autogeneratedExamples:{}},headers:ue.headers}}let te=this.context.getAudiences({operation:this.operation,breadcrumbs:this.breadcrumbs})??[],se=new pWt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.context.spec}).convert(),me=new pWt({context:this.context,breadcrumbs:this.breadcrumbs,document:this.operation}).convert()??se,Se={displayName:this.operation.summary,subtitle:this.subtitle,method:t,baseUrl:R,v2BaseUrls:D,path:S,pathParameters:a,queryParameters:c,headers:s.filter((ue,Oe,Ie)=>Oe===Ie.findIndex(je=>ur(je.name)===ur(ue.name))),responseHeaders:g?.responseHeaders,sdkRequest:void 0,errors:v,auth:this.computeEndpointAuth(),security:this.computeEndpointSecurity(),availability:this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:B!=null?sb(B):void 0,fullPath:B!=null?sb(`${B}${this.path}`):S,allPathParameters:a,pagination:void 0,transport:void 0,source:AD.openapi(),audiences:te,retries:void 0,globalParameters:this.globalParameterIds,apiPlayground:me},Re=this.context.namespace!=null?[this.context.namespace]:[],ce=r?.map(ue=>ti(ue));return Re.push(...ce??[]),{audiences:te,group:r,groupDisplayName:i,groupDescription:o,errors:x,endpoint:{...Se,id:`endpoint_${Re.join("/")}.${n}`,name:this.context.casingsGenerator.generateName(n),requestBody:p,v2RequestBodies:m,response:A,docs:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:O.examples},v2Responses:{responses:g?.v2Responses}},streamEndpoint:y!=null&&y.body!=null?{...Se,id:`endpoint_${Re.join("/")}.${n}_stream`,name:this.context.casingsGenerator.generateName(`${n}_stream`),requestBody:d,v2RequestBodies:void 0,response:y,docs:this.streamingExtension?.type==="streamCondition"?this.streamingExtension.streamDescription??this.operation.description:this.operation.description,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:O.streamExamples},v2Responses:{responses:[{statusCode:200,isWildcardStatusCode:void 0,body:y.body,docs:y.docs}]}}:void 0,inlinedTypes:this.inlinedTypes,servers:this.filterOutTopLevelServers(this.operation.servers??this.pathLevelServers??[]),inlinedRequestPropertiesByAudience:f,queryParametersByAudience:u}}collectQueryParameterAudiences({breadcrumbs:t}){let r=this.mergeParameters(this.pathItemParameters,this.operation.parameters??[]);if(r.length===0)return;let n={},i=!1;for(let o of r){let s=this.context.resolveMaybeReference({schemaOrReference:o,breadcrumbs:t,skipErrorCollector:!0});if(s==null||s.in!=="query")continue;let a=this.context.getAudiences({operation:s,breadcrumbs:t})??[];if(a.length!==0){i=!0;for(let c of a)n[c]==null&&(n[c]=new Set),n[c].add(s.name)}}return i?n:void 0}convertResponseBody({breadcrumbs:t,group:r,method:n,streamingExtension:i}){if(this.operation.responses==null)return;let o,s=!1,a=!1;for(let[c,u]of Object.entries(this.operation.responses)){let l=/^[45]XX$/i.test(c),p,d=!1;if(l)p=parseInt(c.charAt(0))*100,d=!0;else{if(p=parseInt(c),isNaN(p)||p<200||p>=300&&p<400)continue;d=p>=400&&p<600}if(o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]}),p>=200&&p<300){let f=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,c]});if(f==null)continue;let g=new fWt({context:this.context,breadcrumbs:[...t,c],responseBody:f,group:r??[],method:n,statusCode:c,streamingExtension:i}).convert();if(g==null){a=!0,o.response==null&&(o.response={statusCode:p,isWildcardStatusCode:l?!0:void 0,body:void 0,docs:f.description});continue}g!=null&&(this.inlinedTypes={...this.inlinedTypes,...g.inlinedTypes},s||(s=!0,o.response={statusCode:p,isWildcardStatusCode:l?!0:void 0,body:g.responseBody,docs:f.description},o.streamResponse={statusCode:p,isWildcardStatusCode:l?!0:void 0,body:g.streamResponseBody,docs:f.description},g.headers!=null&&(o.responseHeaders=g.headers)),o.v2Responses=[...o.v2Responses??[],{statusCode:p,isWildcardStatusCode:l?!0:void 0,body:g.responseBody,docs:f.description}])}if(d){let f=this.context.resolveMaybeReference({schemaOrReference:u,breadcrumbs:[...t,c]});if(f==null)continue;let g=new NYr({context:this.context,breadcrumbs:[...t,c],responseError:f,group:r??[],method:n,methodName:this.evaluateMethodNameFromOperation(),statusCode:p,isWildcardStatusCode:l?!0:void 0}).convert();g!=null&&(this.inlinedTypes={...this.inlinedTypes,...g.inlinedTypes},o.errors.push(g))}}if(this.streamingExtension!=null){o==null&&(o={response:void 0,v2Responses:void 0,streamResponse:void 0,errors:[],examples:{},responseHeaders:[]});let u=new fWt({context:this.context,breadcrumbs:[...t,"stream"],responseBody:{description:""},group:r??[],method:n,statusCode:"stream",streamingExtension:i}).convert();u!=null&&(this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},o.response={statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0},o.streamResponse={statusCode:200,isWildcardStatusCode:void 0,body:u.streamResponseBody,docs:void 0},o.v2Responses=[{statusCode:200,isWildcardStatusCode:void 0,body:u.responseBody,docs:void 0}])}if(a&&s&&o?.response?.body!=null){let c=o.response.body;if(c.type==="json"&&c.value.type==="response"){let u=c.value.responseBodyType;(u.type!=="container"||u.container.type!=="optional")&&(o.response={...o.response,body:_u.json(gI.response({...c.value,responseBodyType:en.container(Ts.optional(u))}))})}}return o}computeEndpointAuth(){return this.operation.security!=null&&this.operation.security.length===0?!1:this.operation.security!=null&&this.operation.security.length>0?!0:this.context.spec.security!=null&&this.context.spec.security.length>0||this.shouldApplyDefaultAuthOverrides()}computeEndpointSecurity(){return this.operation.security!=null&&this.operation.security.length===0?[]:this.context.authOverrides?.auth!=null&&!this.usesEndpointSecurity()?this.getDefaultSecurityFromAuthOverrides():$Go(this.operation.security??this.context.spec.security)}usesEndpointSecurity(){let t=this.context.authOverrides?.auth;return t!=null&&qtt(t)}shouldApplyDefaultAuthOverrides(){if(!this.context.authOverrides?.auth||this.usesEndpointSecurity())return!1;let t=this.context.spec.security!=null&&this.context.spec.security.length>0,r=this.operation.security!=null&&this.operation.security.length>0;return!(t||r)}getDefaultSecurityFromAuthOverrides(){if(!this.context.authOverrides?.auth)return;let t=this.context.authOverrides.auth;if(typeof t=="string"){let r={};return r[t]=[],[r]}if(typeof t=="object"&&"any"in t){let r=t.any;if(Array.isArray(r))return r.map(n=>{let i=typeof n=="string"?n:n.scheme,o={};return o[i]=[],o})}}authSchemeToHeaders(t){let r=[];for(let n of t){let i=this.idToAuthScheme?.[n];if(i==null)continue;let o={valueType:co.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0,clientDefault:void 0,defaultValue:void 0};switch(i.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...o});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},...o});break;case"header":r.push({name:i.name,...o});break}}return r}convertExamples({httpPath:t,httpMethod:r,baseUrl:n}){let o=new kYr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],a=new RYr({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation,baseDir:this.context.documentBaseDir}).convert()??[],u=o.some(l=>Array.isArray(l["code-samples"])&&l["code-samples"].length>0)?o:[...o,...a];return u.length===0?{examples:{},streamExamples:{}}:this.streamingExtension?.type==="streamCondition"?this.convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:u}):{examples:this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:u}),streamExamples:{}}}synthesizeEndpointExamplesFromNativeRequestBody({httpPath:t,httpMethod:r,baseUrl:n}){if(this.operation.requestBody==null)return;let i=this.context.resolveMaybeReference({schemaOrReference:this.operation.requestBody,breadcrumbs:[...this.breadcrumbs,"requestBody"]});if(i==null)return;let o=this.extractNativeResponseExample(),s={};for(let[,a]of Object.entries(i.content)){if(a.schema!=null)continue;let c=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:a,breadcrumbs:[...this.breadcrumbs,"requestBody"],defaultExampleName:"Example"});for(let[u,l]of c){let p=this.context.resolveExampleWithValue(l);p!=null&&(s[u]={displayName:void 0,contentType:void 0,request:{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:p},response:o,codeSamples:void 0})}}return Object.keys(s).length>0?s:void 0}extractNativeResponseExample(){if(this.operation.responses!=null)for(let[t,r]of Object.entries(this.operation.responses)){let n=parseInt(t);if(isNaN(n)||n<200||n>=300)continue;let i=this.context.resolveMaybeReference({schemaOrReference:r,breadcrumbs:[...this.breadcrumbs,"responses",t]});if(i?.content!=null)for(let[,o]of Object.entries(i.content)){let s=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:o,breadcrumbs:[...this.breadcrumbs,"responses",t],defaultExampleName:"Example"});for(let[,a]of s){let c=this.context.resolveExampleWithValue(a);if(c!=null)return{docs:void 0,statusCode:n,body:Zt.V2HttpEndpointResponseBody.json(c)}}}}}synthesizeEndpointExamplesFromPerContentTypeRequestBodies({convertedRequestBodies:t,httpPath:r,httpMethod:n,baseUrl:i}){let o={},s=this.extractNativeResponseExamplesByContentType();for(let a of t){let c=a.requestBody,u=c.contentType,l=c.v2Examples;if(l==null)continue;let p=l.userSpecifiedExamples;if(Object.keys(p).length===0)continue;let d=u!=null?s.get(u):void 0;for(let[f,m]of Object.entries(p)){let g=t.length>1&&u!=null?`${f} (${u})`:f;o[g]={displayName:t.length>1?g:void 0,contentType:u??void 0,request:{docs:void 0,endpoint:{method:n,path:this.buildExamplePath(r,{})},baseUrl:void 0,environment:i,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:m},response:d??this.extractNativeResponseExample()??void 0,codeSamples:void 0}}}return Object.keys(o).length>0?o:void 0}extractNativeResponseExamplesByContentType(){let t=new Map;if(this.operation.responses==null)return t;for(let[r,n]of Object.entries(this.operation.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:[...this.breadcrumbs,"responses",r]});if(o?.content!=null)for(let[s,a]of Object.entries(o.content)){if(t.has(s))continue;let c=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:a,breadcrumbs:[...this.breadcrumbs,"responses",r],defaultExampleName:"Example"});for(let[,u]of c){let l=this.context.resolveExampleWithValue(u);if(l!=null){t.set(s,{docs:void 0,statusCode:i,body:Zt.V2HttpEndpointResponseBody.json(l)});break}}}}return t}convertStreamConditionExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){let o=i.filter(u=>!(u.response!=null&&"stream"in u.response)),s=i.filter(u=>u.response!=null&&"stream"in u.response),a=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:o}),c=this.convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:s});return{examples:a,streamExamples:c}}convertEndpointExamples({httpPath:t,httpMethod:r,baseUrl:n,fernExamples:i}){return Object.fromEntries(i.map((o,s)=>[this.getExampleName({example:o,exampleIndex:s}),{displayName:void 0,contentType:void 0,request:o.request!=null||o["path-parameters"]!=null||o["query-parameters"]!=null||o.headers!=null?{docs:void 0,endpoint:{method:r,path:this.buildExamplePath(t,o["path-parameters"]??{})},baseUrl:void 0,environment:n,auth:void 0,pathParameters:o["path-parameters"]??{},queryParameters:o["query-parameters"]??{},headers:o.headers??{},requestBody:o.request??void 0}:void 0,response:o.response!=null?{docs:void 0,statusCode:void 0,body:this.getExampleResponseBody({example:o})}:void 0,codeSamples:o["code-samples"]?.map(a=>{let c=("language"in a?a.language:a.sdk)??void 0;return{name:a.name,docs:void 0,language:c,code:a.code}})}]))}getExampleName({example:t,exampleIndex:r}){return t.name??t["code-samples"]?.[0]?.name??`Example_${r}`}getExampleResponseBody({example:t}){if(t.response!=null){if("stream"in t.response)return Zt.V2HttpEndpointResponseBody.stream(t.response.stream);if("body"in t.response)return Zt.V2HttpEndpointResponseBody.json(t.response.body)}}getEndpointBaseUrl(){let r=new qC.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert();if(r!=null)return this.context.logger.debug(`[getEndpointBaseUrl] Endpoint ${this.method.toUpperCase()} ${this.path} specifies a server with "${mn.SERVER_NAME_V2}" extension. Returning server type: ${r}`),r;let n=this.operation.servers?.[0]??this.pathLevelServers?.[0];if(n==null)return;let o=this.topLevelServers?.find(s=>s.url===n.url)??n;return N4.getServerName({server:o,context:this.context})}getEndpointBaseUrls(){if(new qC.ServerFromOperationNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()!=null)return;let n=this.operation.servers??this.pathLevelServers;return n?.map(o=>{let a=this.topLevelServers?.find(c=>c.url===o.url)??o;return N4.getServerName({server:a,context:this.context})})}buildExamplePath(t,r){return t.head+t.parts.map(n=>`${r[n.pathParameter]?.toString()??n.pathParameter}${n.tail}`).join("")}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers?.some(n=>n.url===r.url))}getGroupDisplayName(t){let r=this.operation.tags?.[0],n=t?.[t.length-1];if(r==null||n==null)return;let i=this.context.getDisplayNameForTag(r);if(i.toLowerCase().replaceAll(" ","")===n||this.context.hasExplicitDisplayNameForTag(r)&&ti(r)===ti(n))return i}getGroupDescription(t){let r=this.operation.tags?.[0],n=t?.[t.length-1];if(!(r==null||n==null)&&ti(r)===ti(n))return this.context.getDescriptionForTag(r)}}});var pqo,zYr,yGu=h(()=>{"use strict";rs();pqo=ye(Q4t(),1);rGu();nGu();iGu();sGu();aGu();cGu();uGu();AGu();aqo();zYr=class extends co{pathItem;path;idToAuthScheme;topLevelServers;declaredGlobalParameterIds;constructor({context:t,breadcrumbs:r,pathItem:n,path:i,idToAuthScheme:o,topLevelServers:s,declaredGlobalParameterIds:a}){super({context:t,breadcrumbs:r}),this.pathItem=n,this.path=i,this.idToAuthScheme=o,this.topLevelServers=s,this.declaredGlobalParameterIds=a}convert(){let t=[],r=[],n={};for(let i of tGu){let o=this.pathItem[i];if(o==null)continue;let s=[...this.breadcrumbs,i],a=this.tryParseAsWebhook({operationBreadcrumbs:s,operation:o,method:i,context:this.context});if(a!=null){r.push(a),Object.assign(n,a.inlinedTypes);continue}let u=new OYr({breadcrumbs:s,document:this.context.spec,operation:o,context:this.context}).convert();u==null&&this.operationHasTextEventStreamResponse(o)&&(u={type:"stream",format:"sse",terminator:void 0,resumable:lqo(this.context.spec)??!1});let l=this.tryParseAsHttpEndpoint({operationBreadcrumbs:s,operation:o,method:i,streamingExtension:u});l!=null&&(t.push(l),Object.assign(n,l.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:n}}tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:n,context:i}){return new BYr({breadcrumbs:n,operation:t,context:i}).convert()?new Alt({context:this.context,breadcrumbs:n,operation:t,method:pqo.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters}).convert():void 0}operationHasTextEventStreamResponse(t){if(t.responses==null)return!1;for(let[r,n]of Object.entries(t.responses)){let i=parseInt(r);if(isNaN(i)||i<200||i>=300)continue;let o=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:this.breadcrumbs});if(o?.content==null)continue;let s=Object.keys(o.content);if(s.length===1&&s[0]?.includes("text/event-stream"))return!0}return!1}tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:n,streamingExtension:i}){new TYr({breadcrumbs:n,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let c=new wYr({breadcrumbs:n,operation:t,context:this.context}).convert(),l=new PYr({breadcrumbs:n,operation:t,context:this.context}).convert(),d=new SYr({breadcrumbs:n,operation:t,context:this.context}).convert();if(d!=null&&this.declaredGlobalParameterIds!=null){let m=[];for(let g of d)this.declaredGlobalParameterIds.has(g)?m.push(g):this.context.errorCollector.collect({message:`x-fern-global-parameter references undeclared global parameter '${g}'. Declared parameters: ${[...this.declaredGlobalParameterIds].join(", ")}`,path:[...n,"x-fern-global-parameter"]});d=m.length>0?m:void 0}return new jYr({context:this.context,breadcrumbs:n,operation:t,method:pqo.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,pathItemParameters:this.pathItem.parameters,idempotent:c,subtitle:l,globalParameterIds:d,idToAuthScheme:this.idToAuthScheme,topLevelServers:this.topLevelServers,pathLevelServers:this.pathItem.servers,streamingExtension:i}).convert()}}});var QYr,bGu=h(()=>{"use strict";Wn();rs();QYr=class extends co{securityScheme;schemeId;constructor({context:t,breadcrumbs:r,securityScheme:n,schemeId:i}){super({context:t,breadcrumbs:r}),this.securityScheme=n,this.schemeId=i}getExtension(t){return this.securityScheme[t]}convert(){let t=this.getExtension("x-fern-playground-description");switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme?.toLowerCase()==="bearer"){let r=this.getExtension("x-fern-bearer"),n=r?.name??"token",i=r?.env,o=r?.placeholder;return Hp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName(n),tokenEnvVar:i,tokenPlaceholder:o,docs:this.securityScheme.description,playgroundDocs:t})}if(this.securityScheme.scheme?.toLowerCase()==="basic"){let r=this.getExtension("x-fern-basic"),n=r?.username?.name??"username",i=r?.password?.name??"password",o=r?.username?.env,s=r?.password?.env,a=r?.username?.placeholder,c=r?.password?.placeholder;return Hp.basic({key:this.schemeId,username:this.context.casingsGenerator.generateName(n),password:this.context.casingsGenerator.generateName(i),usernameEnvVar:o,passwordEnvVar:s,usernameOmit:!1,passwordOmit:!1,usernamePlaceholder:a,passwordPlaceholder:c,docs:this.securityScheme.description,playgroundDocs:t})}break}case"apiKey":{if(this.securityScheme.in==="header"){let r=this.getExtension("x-fern-header"),n=r?.name??"apiKey",i=r?.env,o=r?.prefix,s=r?.placeholder;return Hp.header({key:this.schemeId,name:{name:this.context.casingsGenerator.generateName(n),wireValue:this.securityScheme.name},valueType:co.OPTIONAL_STRING,prefix:o,headerEnvVar:i,headerPlaceholder:s,docs:this.securityScheme.description,playgroundDocs:t})}break}case"oauth2":return Hp.bearer({key:this.schemeId,token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,tokenPlaceholder:void 0,docs:this.securityScheme.description,playgroundDocs:t})}}}});function pFm(e){if(e!=null){if(typeof e=="string")return cE.string(e);if(typeof e=="boolean")return cE.boolean(e)}}var EGu,dWt,IGu=h(()=>{"use strict";ct();Io();Wn();hc();R5();rs();EGu=ye(Q4t(),1);V8u();G8u();q8u();W8u();K8u();Y8u();Z8u();aqo();yGu();bGu();dWt=class extends PJ{constructor({breadcrumbs:t,context:r,audiences:n}){super({breadcrumbs:t,context:r,audiences:n})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.context.spec=await this.resolveAllExternalRefs({spec:this.context.spec}),this.context.spec=M4t({document:this.context.spec,options:this.context.settings,logger:this.context.logger}),ZGo({spec:this.context.spec,errorCollector:this.context.errorCollector}),this.overrideOpenApiAuthWithGeneratorsAuth(),this.convertSecuritySchemes(),this.convertGlobalHeaders(),this.convertGlobalParameters(),this.convertBasePath(),this.convertSchemas(),this.convertWebhooks();let{endpointLevelServers:t,errors:r}=this.convertPaths();this.addErrorsToIr(r);let{defaultUrl:n}=this.convertServers({endpointLevelServers:t});this.updateEndpointsWithDefaultUrl(n);let i=this.context.spec.info?.title?.trim();return i&&i!=='""'&&(this.ir.apiDisplayName=i),this.finalizeIr()}convertGlobalHeaders(){if(this.context.globalHeaderOverrides){let n=H8u({globalHeaderOverrides:this.context.globalHeaderOverrides,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n);return}let r=new IYr({breadcrumbs:["x-fern-global-headers"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=J8u({globalHeaders:r,context:this.context});this.addGlobalHeadersToIr(n),this.context.setGlobalHeaders(n)}}convertGlobalParameters(){let r=new vYr({breadcrumbs:["x-fern-global-parameters"],document:this.context.spec,context:this.context}).convert();if(r!=null){let n=X8u({globalParameters:r,context:this.context});if(this.ir.globalParameters=n,this.ir.headers.length>0){let i=new Set(this.ir.headers.map(o=>{let s=o.name;return(typeof s=="string"?s:s.wireValue).toLowerCase()}));for(let o of r){let s=(o.target??o.name).toLowerCase();o.in==="header"&&i.has(s)&&this.context.logger.warn(`Global parameter "${o.name}" (in: header, target: "${o.target??o.name}") overlaps with an x-fern-global-headers entry. The x-fern-global-parameters definition takes precedence.`)}}}}convertBasePath(){let r=new bYr({breadcrumbs:["x-fern-base-path"],document:this.context.spec,context:this.context}).convert();if(r!=null){if(this.context.settings.respectPerSpecBasePath&&r.parameters.length===0){r.pathsIncludeBasePath||(this.context.perSpecBasePath=Hy(r.path));return}this.context.settings.respectPerSpecBasePath&&r.parameters.length>0&&this.context.errorCollector.collect({message:"respect-per-spec-base-path only applies to an x-fern-base-path without path parameters; this base path is used as the API-wide base path instead, which only one spec keeps when multiple specs are merged",path:["x-fern-base-path"]}),this.ir.basePath=sb(r.path);for(let n of r.parameters)n.type!=="string"&&this.context.errorCollector.collect({message:`x-fern-base-path parameter '${n.name}' uses type '${n.type}' which is not yet supported; treating as string`,path:["x-fern-base-path","parameters",n.name]}),this.ir.pathParameters.push({name:this.context.casingsGenerator.generateName(n.name),valueType:co.STRING,docs:n.docs,location:Zt.PathParameterLocation.Root,variable:void 0,clientDefault:pFm(n.default),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}},explode:void 0});if(r.pathsIncludeBasePath){let n=z4t({openApi:this.context.spec,basePath:r.path,rootPathParameterNames:new Set(r.parameters.map(i=>i.name))});for(let i of n)this.context.errorCollector.collect({message:i,path:["x-fern-base-path","paths-include-base-path"]})}}}convertSecuritySchemes(){let t=this.convertOpenApiSecuritySchemes();if(this.context.authOverrides){let r=new Map(t.map(n=>[n.key,n.docs]));this.convertAuthOverrides(r,this.context.authOverrides);return}t.length>0&&this.addAuthToIR({requirement:t.length===1?"ALL":"ANY",schemes:t,docs:void 0})}convertAuthOverrides(t,r){let n={...r,"auth-schemes":Object.fromEntries(Object.entries(r["auth-schemes"]??{}).map(([o,s])=>[o,{...s}]))};for(let[o,s]of Object.entries(n["auth-schemes"]))!s.docs&&t.has(o)&&(s.docs=t.get(o));let i=JGt({rawApiFileSchema:n,casingsGenerator:this.context.casingsGenerator});this.addAuthToIR({requirement:i.requirement,schemes:i.schemes,docs:i.docs})}convertOpenApiSecuritySchemes(){let t=[];for(let[r,n]of Object.entries(this.context.spec.components?.securitySchemes??{})){let i=this.context.resolveMaybeReference({schemaOrReference:n,breadcrumbs:["components","securitySchemes",r]});if(i==null)continue;let s=new QYr({context:this.context,breadcrumbs:["components","securitySchemes",r],securityScheme:i,schemeId:r}).convert();s!=null&&t.push(s)}return t}convertServers({endpointLevelServers:t}){let n=new EYr({breadcrumbs:["x-fern-base-url-env"],document:this.context.spec,context:this.context}).convert();if(this.context.environmentOverrides){let s=YGt({rawApiFileSchema:this.context.environmentOverrides,casingsGenerator:this.context.casingsGenerator});return s!=null&&this.addEnvironmentsToIr({environmentConfig:{...s.environmentsConfig,baseUrlEnvVar:s.environmentsConfig.baseUrlEnvVar??n},audiences:s.audiences}),{defaultUrl:this.context.environmentOverrides["default-url"]}}let o=new N4({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t,baseUrlEnvVar:n}).convert();return this.addEnvironmentsToIr({environmentConfig:o?.value}),{defaultUrl:o?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Hm.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();i!=null&&this.addSchemaOutputToIr(t,i)}}convertWebhooks(){for(let[t,r]of Object.entries(this.context.spec.webhooks??{})){if(r==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});continue}if(!("post"in r)||r.post==null){this.context.errorCollector.collect({message:"Skipping webhook as it is not a POST method",path:this.breadcrumbs});continue}let n=r.post.operationId??t,i=r.post.operationId!=null?r.post:{...r.post,operationId:n},s=new Alt({context:this.context,breadcrumbs:["webhooks",n],operation:i,method:EGu.OpenAPIV3.HttpMethods.POST,path:n}).convert();s!=null&&(this.addWebhookToIr({webhook:s.webhook,operationId:n,audiences:s.audiences,group:s.group,inlinedPayloadPropertiesByAudience:s.inlinedPayloadPropertiesByAudience}),this.addTypesToIr(s.inlinedTypes))}}convertPaths(){let t=[],r={},n=this.ir.globalParameters!=null?new Set(this.ir.globalParameters.map(i=>i.id)):void 0;for(let[i,o]of Object.entries(this.context.spec.paths??{})){if(o==null)continue;let a=new zYr({context:this.context,breadcrumbs:["paths",i],topLevelServers:this.context.spec.servers,pathItem:o,path:i,declaredGlobalParameterIds:n}).convert();if(a!=null){for(let c of a.endpoints){if(c.streamEndpoint!=null&&this.addEndpointToIr({endpoint:c.streamEndpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName,endpointGroupDescription:c.groupDescription,inlinedRequestPropertiesByAudience:c.inlinedRequestPropertiesByAudience,queryParametersByAudience:c.queryParametersByAudience}),this.addEndpointToIr({endpoint:c.endpoint,audiences:c.audiences,endpointGroup:c.group,endpointGroupDisplayName:c.groupDisplayName,endpointGroupDescription:c.groupDescription,inlinedRequestPropertiesByAudience:c.inlinedRequestPropertiesByAudience,queryParametersByAudience:c.queryParametersByAudience}),c.servers)for(let u of c.servers)this.shouldAddServerToCollectedServers({server:u,currentServers:t})&&t.push(u);if(c.errors)for(let[u,l]of Object.entries(c.errors))r[u]=l}for(let c of a.webhooks){let u=this.context.getGroup({groupParts:c.group,namespace:this.context.namespace});this.addWebhookToIr({webhook:c.webhook,operationId:u.join("."),group:u,audiences:c.audiences,inlinedPayloadPropertiesByAudience:c.inlinedPayloadPropertiesByAudience})}this.addTypesToIr(a.inlinedTypes)}}return{endpointLevelServers:t,errors:r}}overrideOpenApiAuthWithGeneratorsAuth(){if(!this.context.authOverrides?.["auth-schemes"])return;let t=this.context.authOverrides.auth;if(t!=null&&qtt(t))return;let r={};for(let n of Object.keys(this.context.authOverrides["auth-schemes"]))r[n]=[];this.context.spec.security=[r],this.removeEndpointSpecificAuth()}removeEndpointSpecificAuth(){if(this.context.spec.paths)for(let t of Object.values(this.context.spec.paths)){if(!t)continue;let r=["get","post","put","patch","delete","options","head","trace"];for(let n of r){let i=t[n];i?.security!=null&&i.security.length>0&&delete i.security}}}}});var MYr,vGu=h(()=>{"use strict";rs();MYr=class extends os{tag;key="x-displayName";constructor({breadcrumbs:t,tag:r,context:n}){super({breadcrumbs:t,context:n}),this.tag=r}convert(){if(typeof this.tag!="object"||this.tag==null)return;let t=this.tag[this.key];if(t!=null){if(typeof t!="string"){this.context.errorCollector.collect({message:"x-displayName extension must be a string",path:this.breadcrumbs});return}if(t.trim().length!==0)return{displayName:t}}}}});var CVe,CGu=h(()=>{"use strict";Wn();hc();rs();vGu();CVe=class extends S0{perSpecBasePath;globalHeaderNames;tagToDisplayName={};tagsWithExplicitDisplayName=new Set;tagToDescription=new Map;tagDescriptionsIndexed=!1;isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=t.$ref.split("/").pop()??o,a=this.resolveReference({reference:t,breadcrumbs:r});if(!a.resolved)return{ok:!1};let c;i==="reference_identifier"?c=n??a.value.title:i==="discriminator_key"?c=a.value.title??n:c=a.value.title??s;let u;if(o.includes("/")){let p=new Hm.SchemaConverters.SchemaConverter({context:this,breadcrumbs:r??[],schema:a.value,id:o}).convert();p!=null&&(u={[o]:p.convertedSchema})}return{ok:!0,reference:en.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(s),typeId:o,default:void 0,inline:!1,displayName:c}),inlinedTypes:u}}setGlobalHeaders(t){this.globalHeaderNames=t.map(r=>ur(r.name))}getDisplayNameForTag(t){if(Object.keys(this.tagToDisplayName).length===0)for(let r of this.spec.tags??[]){let i=new MYr({breadcrumbs:["tags",r.name],tag:r,context:this}).convert()?.displayName;i!=null&&this.tagsWithExplicitDisplayName.add(r.name),this.tagToDisplayName[r.name]=i??r.name}return this.tagToDisplayName[t]??t}hasExplicitDisplayNameForTag(t){return this.getDisplayNameForTag(t),this.tagsWithExplicitDisplayName.has(t)}getDescriptionForTag(t){if(!this.tagDescriptionsIndexed){this.tagDescriptionsIndexed=!0;for(let r of this.spec.tags??[])r.description!=null&&r.description.trim().length>0&&this.tagToDescription.set(r.name,r.description)}return this.tagToDescription.get(t)}}});function dqo({ir:e,authOverrides:t}){if(!t["auth-schemes"]||!e.auth)return e;let r=t["auth-schemes"],n=[];for(let i of e.auth.schemes){if(i.type!=="bearer"){n.push(i);continue}let o=r[i.key];if(o==null){n.push(i);continue}let s=qfe(o,{header:()=>{},basic:()=>{},tokenBearer:()=>{},inferredBearer:()=>{},oauth:a=>dFm({ir:e,key:i.key,oauthScheme:a})});n.push(s??i)}return{...e,auth:{...e.auth,schemes:n}}}function dFm({ir:e,key:t,oauthScheme:r}){if(r.type!=="client-credentials")return;let n=r["get-token"];if(n==null)return;let i=xGu({ir:e,endpointRef:n.endpoint});if(i==null)return;let{endpoint:o,serviceId:s,subpackageId:a}=i,c=n["request-properties"],u=n["response-properties"],l=fqo({ir:e,endpoint:o,wireValue:RJ(c?.["client-id"],"client_id")}),p=fqo({ir:e,endpoint:o,wireValue:RJ(c?.["client-secret"],"client_secret")}),d=ylt({ir:e,endpoint:o,wireValue:RJ(u?.["access-token"],"access_token")});if(!(l==null||p==null||d==null))return Hp.oauth({key:t,docs:r.docs,playgroundDocs:r["playground-docs"],configuration:hD.clientCredentials({clientIdEnvVar:r["client-id-env"],clientSecretEnvVar:r["client-secret-env"],tokenPrefix:r["token-prefix"],tokenHeader:r["token-header"],scopes:r.scopes,tokenEndpoint:{endpointReference:{endpointId:o.id,serviceId:s,subpackageId:a},requestProperties:{clientId:l,clientSecret:p,scopes:void 0,customProperties:gFm({ir:e,endpoint:o,excludeWireValues:[RJ(c?.["client-id"],"client_id"),RJ(c?.["client-secret"],"client_secret")]})},responseProperties:{accessToken:d,expiresIn:ylt({ir:e,endpoint:o,wireValue:RJ(u?.["expires-in"],"expires_in")}),refreshToken:ylt({ir:e,endpoint:o,wireValue:RJ(u?.["refresh-token"],"refresh_token")})}},refreshEndpoint:r["refresh-token"]!=null?mFm({ir:e,refreshTokenConfig:r["refresh-token"]}):void 0})})}function mFm({ir:e,refreshTokenConfig:t}){let r=xGu({ir:e,endpointRef:t.endpoint});if(r==null)return;let{endpoint:n,serviceId:i,subpackageId:o}=r,s=t["request-properties"],a=t["response-properties"],c=fqo({ir:e,endpoint:n,wireValue:RJ(s?.["refresh-token"],"refresh_token")}),u=ylt({ir:e,endpoint:n,wireValue:RJ(a?.["access-token"],"access_token")});if(!(c==null||u==null))return{endpointReference:{endpointId:n.id,serviceId:i,subpackageId:o},requestProperties:{refreshToken:c},responseProperties:{accessToken:u,expiresIn:ylt({ir:e,endpoint:n,wireValue:RJ(a?.["expires-in"],"expires_in")}),refreshToken:ylt({ir:e,endpoint:n,wireValue:RJ(a?.["refresh-token"],"refresh_token")})}}}function xGu({ir:e,endpointRef:t}){let r=t.trim().split(/\s+/);if(r.length!==2)return;let n=fFm[r[0]?.toUpperCase()??""],i=Hy(r[1]);if(!(n==null||i==null))for(let[o,s]of Object.entries(e.services))for(let a of s.endpoints){if(a.method!==n)continue;if(hFm(a.fullPath)===i){let u=Object.entries(e.subpackages).find(([,l])=>l.service===o)?.[0];return{endpoint:a,serviceId:o,subpackageId:u}}}}function hFm(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return Hy(t)}function RJ(e,t){return e==null?t:e.match(/^\$(?:request|response)\.(.+)$/)?.[1]??e}function SGu(e,t){return e.find(r=>ur(r.name)===t)}function mqo(e,t){let r=e.types[t];if(r?.shape.type==="object")return r.shape.properties}function fqo({ir:e,endpoint:t,wireValue:r}){if(t.requestBody==null)return;let n;t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties.map(o=>({...o,xml:void 0})):t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=mqo(e,t.requestBody.requestBodyType.typeId));let i=n!=null?SGu(n,r):void 0;if(i!=null)return{propertyPath:void 0,property:pB.body({...i})}}function gFm({ir:e,endpoint:t,excludeWireValues:r}){if(t.requestBody==null)return;let n;if(t.requestBody.type==="inlinedRequestBody"?n=t.requestBody.properties.map(s=>({...s,xml:void 0})):t.requestBody.type==="reference"&&t.requestBody.requestBodyType.type==="named"&&(n=mqo(e,t.requestBody.requestBodyType.typeId)),n==null)return;let i=new Set(r),o=n.filter(s=>!i.has(ur(s.name))).map(s=>({propertyPath:void 0,property:pB.body({...s})}));return o.length>0?o:void 0}function ylt({ir:e,endpoint:t,wireValue:r}){if(t.response?.body?.type!=="json")return;let n=t.response.body.value.responseBodyType;if(n.type!=="named")return;let i=mqo(e,n.typeId),o=i!=null?SGu(i,r):void 0;if(o!=null)return{propertyPath:void 0,property:o}}var fFm,wGu=h(()=>{"use strict";ct();Io();Wn();hc();fFm={GET:Tm.Get,POST:Tm.Post,PUT:Tm.Put,PATCH:Tm.Patch,DELETE:Tm.Delete}});var hqo=h(()=>{"use strict";IGu();CGu();wGu()});var AFm,yFm,bFm,LYr,TGu=h(()=>{"use strict";ct();rs();cn();AFm=De.object({description:De.string().optional(),required:De.boolean().optional(),deprecated:De.boolean().optional(),allowEmptyValue:De.boolean().optional(),style:De.string().optional(),explode:De.boolean().optional(),allowReserved:De.boolean().optional(),schema:De.any().optional(),example:De.any().optional(),examples:De.record(De.string(),De.any()).optional(),content:De.record(De.string(),De.any()).optional()}),yFm=AFm.extend({name:De.string(),in:De.string()}),bFm=De.array(yFm),LYr=class extends os{operation;key="x-fern-parameters";constructor({breadcrumbs:t,operation:r,context:n}){super({breadcrumbs:t,context:n}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null)try{return bFm.parse(t)}catch(r){this.context.errorCollector.collect({message:`Failed to parse x-fern-parameters extension: ${In(r)}`,path:this.breadcrumbs});return}}}});var _Yr,OGu=h(()=>{"use strict";Wn();hc();rs();_Yr=class extends co{method;pathParameters;queryParameters;headers;topLevelServers;constructor({context:t,breadcrumbs:r,method:n,pathParameters:i=[],queryParameters:o=[],headers:s=[],topLevelServers:a=[]}){super({context:t,breadcrumbs:r}),this.method=n,this.pathParameters=i,this.queryParameters=o,this.headers=s,this.topLevelServers=a}convert(){let t={},r="";for(let u of this.pathParameters)r+=`/{${Vr(u.name)}}`;let n=sb(r),i=[];for(let[u,l]of this.method.params.entries()){let p;if(this.context.isReferenceObject(l)){let g=this.context.resolveReference({reference:l});if(g.resolved)p=g.value;else continue}else p=l;let d=[this.method.name,"Param",p.name].join("_"),m=new Hm.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"Param",p.name],schemaIdOverride:d,context:this.context,schemaOrReference:p.schema,wrapAsOptional:!p.required}).convert();m!=null&&(i.push({docs:p.description,availability:this.context.getAvailability({node:l,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:p.name,wireValue:p.name}),valueType:m.type,defaultValue:p.schema!=null&&typeof p.schema=="object"?p.schema.default:void 0,v2Examples:m.schema?.typeDeclaration.v2Examples,propertyAccess:void 0}),t={...m.inlinedTypes,...t,...m.schema!=null?{[d]:m.schema}:{}})}let o;if(this.method.result!=null){let u=this.context.resolveMaybeReference({schemaOrReference:this.method.result,breadcrumbs:[...this.breadcrumbs,"result"]});if(u!=null){let l=new Hm.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:u.schema}),p=[this.method.name,"Result"].join("_"),d=l.convert();d!=null&&(o={docs:u.description,v2Examples:d.schema?.typeDeclaration.v2Examples,responseBodyType:d.type},t={...d.inlinedTypes,...t,...d.schema!=null?{[p]:d.schema}:{}})}}let s=this.getEndpointBaseUrls(),a=this.context.getAudiences({operation:this.method,breadcrumbs:this.breadcrumbs})??[];return{endpoint:{baseUrl:void 0,v2BaseUrls:s,basePath:void 0,auth:!1,security:void 0,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:this.headers,displayName:this.method.name,subtitle:void 0,pathParameters:this.pathParameters,queryParameters:this.queryParameters,allPathParameters:this.pathParameters,path:n,fullPath:n,requestBody:i.length>0?Od.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:i,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,v2RequestBodies:void 0,sdkRequest:void 0,response:o!=null?{body:_u.json(gI.response(o)),statusCode:void 0,isWildcardStatusCode:void 0,docs:o.docs}:void 0,v2Responses:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples(r)},transport:void 0,availability:void 0,source:AD.openrpc({paramStructure:this.convertParamStructure()}),audiences:a,retries:void 0,globalParameters:void 0,apiPlayground:void 0,responseHeaders:[]},audiences:a,inlinedTypes:t,servers:this.filterOutTopLevelServers(this.method.servers??[])}}convertParamStructure(){let t=this.method.paramStructure;switch(t){case"by-name":return Zt.OpenRpcParamStructure.ByName;case"by-position":return Zt.OpenRpcParamStructure.ByPosition;case"either":return Zt.OpenRpcParamStructure.Either;case void 0:return;default:return}}convertExampleParams(t){return this.method.paramStructure==="by-name"?Object.fromEntries(t.map(r=>[r.name,r.value])):t.map(r=>r.value)}filterOutTopLevelServers(t){return t.filter(r=>!this.topLevelServers.some(n=>n.url===r.url))}getEndpointBaseUrls(){let t=this.method.servers;return t?.map(n=>{if(this.topLevelServers.find(a=>a.name===n.name&&a.url!==n.url)!=null)return n.url;let s=this.topLevelServers.find(a=>a.url===n.url)??n;return N4.getServerName({server:s,context:this.context})})}convertExamples(t){let r={},n={};for(let o of this.pathParameters){let s=Object.values(o.v2Examples?.userSpecifiedExamples??{})[0],a=Object.values(o.v2Examples?.autogeneratedExamples??{})[0],c=s!==void 0?s:a;c!==void 0&&(n[Vr(o.name)]=c)}let i=0;if(this.method.examples&&this.method.examples.length>0){for(let o of this.method.examples??[]){let s;if(this.context.isReferenceObject(o)){let l=this.context.resolveReference({reference:o});if(l.resolved)s=l.value;else continue}else s=o;let a;if(s.result)if(this.context.isReferenceObject(s.result)){let l=this.context.resolveReference({reference:s.result});l.resolved&&(a=l.value)}else a=s.result;let c=s.name??`Example ${i+1}`,u=[];if(s.params&&Array.isArray(s.params)){u=[];for(let l of s.params)if(this.context.isReferenceObject(l)){let p=this.context.resolveReference({reference:l});if(p.resolved)u.push(p.value);else continue}else u.push(l)}r[c]={displayName:void 0,contentType:void 0,request:{docs:void 0,endpoint:{method:"POST",path:t},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:n,queryParameters:{},headers:{},requestBody:this.convertExampleParams(u)},response:{docs:void 0,statusCode:void 0,body:a?.value!==void 0?Zt.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:s.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++i}return r}}});var UYr,PGu=h(()=>{"use strict";rs();UYr=class extends Hm.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:n}){super({context:t,breadcrumbs:r,parameter:n})}convert(){let t,r={};if(this.parameter.schema!=null){let i=new Hm.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();i!=null&&(t=i.type,r=i.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}}});var mWt,BGu=h(()=>{"use strict";rs();TGu();OGu();PGu();mWt=class extends PJ{constructor({context:t,breadcrumbs:r,audiences:n}){super({context:t,breadcrumbs:r,audiences:n})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec}),this.convertSchemas();let{endpointLevelServers:t}=this.convertMethods(),{defaultUrl:r}=this.convertServers({endpointLevelServers:t});return this.updateEndpointsWithDefaultUrl(r),this.finalizeIr()}convertServers({endpointLevelServers:t}){let n=new N4({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();return this.addEnvironmentsToIr({environmentConfig:n?.value}),{defaultUrl:n?.defaultUrl}}convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let i=new Hm.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();i!=null&&this.addSchemaOutputToIr(t,i)}}convertMethods(){let t=[],n=new LYr({context:this.context,breadcrumbs:["methods"],operation:this.context.spec}).convert(),i=[],o=[],s=[];if(n&&n.length>0)for(let[c,u]of n.entries()){let p=new UYr({context:this.context,breadcrumbs:[...this.breadcrumbs,`x-fern-parameters[${c}]`],parameter:u}).convert();if(p!=null)switch(p.type){case"path":{i.push(p.parameter);break}case"query":{o.push(p.parameter);break}case"header":{s.push(p.parameter);break}}}let a=this.context.getGroup({groupParts:[],namespace:this.context.namespace});for(let c of this.context.spec.methods??[]){let u=this.context.resolveMaybeReference({schemaOrReference:c,breadcrumbs:["methods"]});if(u==null)continue;let p=new _Yr({context:this.context,breadcrumbs:["methods"],method:u,pathParameters:i,queryParameters:o,headers:s,topLevelServers:this.context.spec.servers}).convert();if(p!=null&&(this.addEndpointToIr({endpoint:p.endpoint,audiences:p.audiences,endpointGroup:a,serviceName:"service_root"}),this.addTypesToIr(p.inlinedTypes),p.servers))for(let d of p.servers)this.shouldAddServerToCollectedServers({server:d,currentServers:t,specType:"openrpc"})&&t.push(this.maybeDeduplicateServerName(d))}return{endpointLevelServers:t}}maybeDeduplicateServerName(t){return this.context.spec.servers?.find(n=>n.name===t.name&&n.url!==t.url)?{...t,name:t.url}:t}}});var hWt,RGu=h(()=>{"use strict";Wn();rs();hWt=class extends S0{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}convertReferenceToTypeReference({reference:t,breadcrumbs:r,displayNameOverride:n,displayNameOverrideSource:i}){let o=this.getTypeIdFromSchemaReference(t);if(o==null)return{ok:!1};let s=this.resolveReference({reference:t,breadcrumbs:r});if(!s.resolved)return{ok:!1};let a;if(i==="reference_identifier")a=n??s.value.title;else if(i==="discriminator_key")a=s.value.title??n;else{let c=t.$ref.split("/").pop()??o;a=s.value.title??c}return{ok:!0,reference:en.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(o),typeId:o,displayName:a,default:void 0,inline:!1})}}}});var DGu=h(()=>{"use strict";BGu();RGu()});var kGu,FGu=h(()=>{"use strict";kGu=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function EFm(e){return typeof e=="string"&&kGu.test(e)}var gqo,NGu=h(()=>{"use strict";FGu();gqo=EFm});function jGu(e,t=0){return(XB[e[t+0]]+XB[e[t+1]]+XB[e[t+2]]+XB[e[t+3]]+"-"+XB[e[t+4]]+XB[e[t+5]]+"-"+XB[e[t+6]]+XB[e[t+7]]+"-"+XB[e[t+8]]+XB[e[t+9]]+"-"+XB[e[t+10]]+XB[e[t+11]]+XB[e[t+12]]+XB[e[t+13]]+XB[e[t+14]]+XB[e[t+15]]).toLowerCase()}var XB,zGu=h(()=>{"use strict";XB=[];for(let e=0;e<256;++e)XB.push((e+256).toString(16).slice(1))});function Aqo(){return crypto.getRandomValues(IFm)}var IFm,QGu=h(()=>{"use strict";IFm=new Uint8Array(16)});function vFm(e,t,r){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():CFm(e,t,r)}function CFm(e,t,r){e=e||{};let n=e.random??e.rng?.()??Aqo();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return jGu(n)}var Xw,MGu=h(()=>{"use strict";QGu();zGu();Xw=vFm});var xVe=h(()=>{"use strict";MGu();NGu()});async function blt({absoluteFilePathToOverrides:e,data:t,context:r,allowNullKeys:n}){let i=null;try{let o=(await(0,LGu.readFile)(e,"utf8")).toString();try{i=JSON.parse(o)}catch{i=Cr.load(o,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`,void 0,{code:T.Code.ParseError})}return $Z({data:t,overrides:i,allowNullKeys:n})}var LGu,VYr=h(()=>{"use strict";ct();Dt();LGu=require("fs/promises");cs()});async function yqo({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let n=(await(0,_Gu.readFile)(t)).toString(),i;try{i=JSON.parse(n)}catch{i=Cr.load(n)}let o=[];r!=null&&(Array.isArray(r)?o=r:o=[r]);let s=i;for(let a of o)s=await blt({absoluteFilePathToOverrides:a,context:e,data:s});return s}var _Gu,UGu=h(()=>{"use strict";_Gu=require("fs/promises");cs();VYr()});async function bqo({document:e,settings:t}){let r=t?.errorResponses;if(r==null)return{document:e,errorResponses:void 0};let n=typeof r.schema=="string"?await xFm($t.of(r.schema)):r.schema;return{document:pSo({document:e,errorResponses:r,schema:n}),errorResponses:{...r,schema:n}}}async function xFm(e){let t=(await(0,VGu.readFile)(e)).toString(),r=Cr.load(t);if(!Fr(r))throw new T({message:`Expected ${e} to contain an OpenAPI schema object.`,code:T.Code.ConfigError});return r}var VGu,GGu=h(()=>{"use strict";kc();ct();tr();Dt();VGu=require("fs/promises");cs()});var WGu=E((yDv,qGu)=>{"use strict";function SFm(){return typeof process=="object"&&typeof process.nextTick=="function"?process.nextTick:typeof setImmediate=="function"?setImmediate:function(t){setTimeout(t,0)}}qGu.exports=SFm()});var JGu=E((bDv,KGu)=>{"use strict";var HGu=WGu();KGu.exports=function(t,r){if(t){r.then(function(n){HGu(function(){t(null,n)})},function(n){HGu(function(){t(n)})});return}else return r}});var Iqo=E((EDv,XGu)=>{"use strict";var Eqo=class{constructor(t,r){this.cb=t,this.delay=r,this.timers={},this.pausers={}}setDelay(t){t>=0&&(this.delay=t)}pause(t){this.pausers[t]=this.pausers[t]||0,this.pausers[t]++}unpause(t){var r=this.pausers[t]||0;r>0&&r--,this.pausers[t]=r}unpauseAndTime(t){this.unpause(t),this.time(t)}time(t){var r=this,n=this.timers,i=this.timers[t];this.pausers[t]>0||(i&&clearTimeout(i),n[t]=setTimeout(function(){r.cb(t),delete n[t]},r.delay))}},GYr=class extends TypeError{constructor(t,r,n){let i=t.includes(".")?"property":"argument",o=`The "${t}" ${i} ${determiner} ${r}`}};function YGu(e,t,r="Object"){if(e!==void 0&&(e===null||typeof e!="object"||Array.isArray(e))){let n=new GYr(t,r,e);throw Error.captureStackTrace(n,YGu),n}}XGu.exports={ERR_INVALID_ARG_TYPE:GYr,assertIsObject:YGu,DebounceTimers:Eqo}});var equ=E((IDv,$Gu)=>{"use strict";var{assertIsObject:ZGu}=Iqo();function wFm(e){return ZGu(e,"options"),e=Object.assign({},e),e.allowHalfOpen=!0,e.rejectUnauthorized=!1,ZGu(e.settings,"options.settings"),e.settings=Object.assign({},e.settings),e.Http1IncomingMessage=e.Http1IncomingMessage||this.http.IncomingMessage,e.Http1ServerResponse=e.Http1ServerResponse||this.http.ServerResponse,e.Http2ServerRequest=e.Http2ServerRequest||(this.http2||{}).Http2ServerRequest,e.Http2ServerResponse=e.Http2ServerResponse||(this.http2||{}).Http2ServerResponse,e}function TFm(e,t){e=wFm.call(this,e);var r=e.ALPNProtocols=[];return this.http2Support&&r.push("h2"),(e.allowHTTP1==!0||!this.http2Support)&&r.push("http/1.1"),t!==void 0&&e.servername===void 0&&(e.servername=t),e}$Gu.exports={initializeTLSOptions:TFm}});var KYr=E((CDv,iqu)=>{"use strict";var{URL:qYr}=require("url"),{EventEmitter:rqu}=require("events"),WYr=require("util")._extend,{DebounceTimers:OFm,assertIsObject:tqu,ERR_INVALID_ARG_TYPE:vDv}=Iqo(),{initializeTLSOptions:PFm}=equ(),gWt=require("http"),vqo=require("https"),{Stream:BFm}=require("stream");function HYr(e,t){let r=t.prototype;Object.keys(r).forEach(n=>{e.indexOf(n)==-1&&n.indexOf("_")!=0&&typeof r[n]=="function"&&e.push(n)})}var Ehe=[];HYr(Ehe,gWt.ClientRequest);HYr(Ehe,gWt.OutgoingMessage);HYr(Ehe,rqu);HYr(Ehe,BFm);var RFm=["httpVersionMajor","httpVersionMinor","httpVersion"],DFm=["host","connection"],Awe=Symbol("stubs");function AWt(){this.http2Mimic=!0,this[Awe]=[];for(var e=0;e<Ehe.length;e++){let u=Ehe[e];AWt.prototype[u]||(this[u]=function(){return this.genericStubber(u,arguments)}.bind(this))}var t,r,n,i;let o=arguments[0]instanceof yWt;var s,a;if(o){let u=arguments[0];u.method&&(s=u.method),u.protocol&&(a=u.protocol)}if(o?i=arguments[0].args:i=arguments,i[2]!=null?(n=i[0],t=i[1],r=i[2]):i[1]==null?t=i[0]:(t=i[0],r=i[1]),r=r||function(){},typeof t=="string"){if(t=Cqo(new qYr(t)),!t.hostname)throw new Error("Unable to determine the domain name")}else n?t=WYr(Cqo(new qYr(n)),t):t=WYr({},t);a!=a&&(t.protocol=a),t.protocol=="https:"&&!t.port&&t.port!=0&&(t.port=443),!t.port&&t.port!=0&&(t.port=80),s?t.method=s:t.method||(t.method="GET"),t.method=t.method.toUpperCase(),(t.requestManager||this.getGlobalManager(t)).handleClientRequest(this,t,r)}AWt.prototype={getGlobalManager(e){return e.agent?e.agent.protocol=="https:"?bwe.globalManager:Ewe.globalManager:ywe.globalManager},genericStubber(e,t){return this[Awe]?(this[Awe].push([e,t]),!0):this[e](...arguments)},on(e,t){e=="response"&&(t.http2Safe||(e="http1.response",arguments[0]=e)),this._on?this._on(...arguments):this.genericStubber("on",arguments)},once(e,t){e=="response"&&(t.http2Safe||(e="http1.response")),this._once?this._once(...arguments):this.genericStubber("once",arguments)},emitError(e){if(this[Awe])this[Awe].forEach(([t,r])=>{(t==="on"||t==="once")&&r[0]==="error"&&r[1](e)});else return this.emit("error",e)},take(e){for(var t=0;t<Ehe.length;t++){let n=Ehe[t];e[n]&&(this[n]=e[n].bind(e))}this._on=e.on.bind(e),this._once=e.once.bind(e),this.proxyProps(e);for(let n=0;n<this[Awe].length;n++){var r=this[Awe][n];e[r[0]](...r[1])}this[Awe]=null},proxyProps(e){function t(){return e[this]}function r(c){e[this]=c}let n=["on","_on","_once","once","http2Mimic"].concat(Ehe),i=Object.keys(this),o=[].concat(RFm);i.forEach(function(u){n.indexOf(u)==-1&&o.indexOf(u)==-1&&o.push(u)});let s=Object.getOwnPropertyDescriptors(e);for(var a=0;a<o.length;a++){let c=o[a],u=s[c],l;u||(l=!0),u&&(u.writable||u)&&(l=!0),l&&(e[c]=this[c]),Object.defineProperty(this,c,{get:t.bind(c),set:r.bind(c)})}}};var ywe=class e extends rqu{constructor(t){super(),this.httpsAgent=vqo.globalAgent,this.httpAgent=gWt.globalAgent,this.init(t)}log(){}init(t){t=t||{},this.http2Clients={},this.cachedHTTP1Result={},this.setModules(),this.http2Debouncer=new OFm(function(n){this.log("stopping ",n);var i=this.http2Clients[n];i&&this.removeHttp2Client(n,i)}.bind(this),1e3),this.keepH1IdentificationCacheFor=t.keepH1IdentificationCacheFor||3e4,this.http2Debouncer.setDelay(t.keepH2ConnectionFor),t.useHttp?this.enforceProtocol="http:":t.useHttps&&(this.enforceProtocol="https:")}setModules(){this.http=require("http"),this.https=require("https"),this.tls=require("tls"),this.net=require("net"),this.http2Support=!1;try{this.http2=require("http2"),this.http2Support=!0}catch{}}handleClientRequest(t,r,n){let i=this,o=i.getClientKey(r);if(i.hasCachedConnection(o)){let s=i.getHttp2Client(o),a={createConnection(){return s}};process.nextTick(function(){i.makeRequest(t,o,r,n,a)}.bind(i))}else i.holdConnectionToIdentification(o,r,function(a,c){if(a){t.emitError(a);return}i.makeRequest(t,o,r,n,c)}.bind(i))}getClientKey(t){return`${t.protocol||this.enforceProtocol}${t.servername||t.host||t.hostname}:${t.port}`}getHttp2Client(t){return this.http2Clients[t]}setHttp2Client(t,r){let n=this,i=n.http2Clients[t];i&&n.removeHttp2Client(t,i),n.http2Clients[t]=r;function o(){n.removeHttp2Client(t,r)}r.on("close",o),r.on("goaway",o),r.on("error",o),r.on("frameError",o),r.on("timeout",o)}removeHttp2Client(t,r){try{delete this.http2Clients[t],r.closed||r.close()}catch{}r.removeAllListeners("close"),r.removeAllListeners("error"),r.removeAllListeners("frameError"),r.removeAllListeners("timeout")}request(t,r,n){var i=new yWt(arguments);return this.enforceProtocol&&(i.protocol=this.enforceProtocol),new AWt(i)}get(){var t=new yWt(arguments);t.method="GET";var r=this.request(t);return r.end(),r}hasCachedConnection(t){return this.getHttp2Client(t)?!0:this.cachedHTTP1Result[t]+this.keepH1IdentificationCacheFor<Date.now()}makeRequest(t,r,n,i,o){let s=this.getHttp2Client(r);return s?this.makeHttp2Request(r,t,s,Object.assign(o||{},n),i):(n.agent||(n.protocol=="https:"?n.agent=this.httpsAgent:n.agent=this.httpAgent),this.makeHttpRequest(r,t,n,i,o))}holdConnectionToIdentification(t,r,n){let i=`identify-${t}`;if(this._events[i])this.once(i,n);else{this.once(i,function(){});let o=this.identifyConnection(r,function(a,c){if(a)return n(a);var u={createConnection(){return o}};if(c=="h2"&&this.http2Support){var l=this.http2.connect(r,u);this.setHttp2Client(t,l)}else this.cachedHTTP1Result[t]=Date.now();n(null,u),this.emit(i,u)}.bind(this))}}makeHttpRequest(t,r,n,i,o){n instanceof qYr&&(n=Cqo(n));let s=WYr({},n);o&&(s.createConnection=o.createConnection);let c=(s.protocol=="https:"?this.https:this.http).request(s,i);r.take(c),r._on("response",function(l){this.emit("http1.response",l)})}makeHttp2Request(t,r,n,i,o){var s=this.http2Debouncer;s.pause(t);var a=WYr({},i.headers||{});i.method&&(a[":method"]=i.method),i.path&&(a[":path"]=i.path),Object.keys(a).forEach(d=>{DFm.indexOf((d+"").toLowerCase())!=-1&&delete a[d]}),i.headers=a;var c=n.request(a);r.emit("socket",i.createConnection());let u,l=0;c.on("data",function(f){l+=f.length,l>=u&&s.unpauseAndTime(t)}),r.take(c);function p(d){u=parseInt(d["content-length"]),u<0&&this.http2Debouncer.unpauseAndTime(t),e.httpCompatibleResponse(c,i,d),r.emit("http1.response",c),o&&o(c)}p.http2Safe=!0,c.once("response",p.bind(this))}static httpCompatibleResponse(t,r,n){t.httpVersion="2.0",t.rawHeaders=n,t.headers=n,t.statusCode=n[":status"],delete n[":status"]}identifyConnection(t,r){var n=this.connect(t,{allowHTTP1:!0},function(){n.removeListener("error",r),n.alpnProtocol=="h2"?r(null,"h2"):(n.end(),r(null,"h1"))});return n.on("error",r),n}connect(t,r,n){typeof r=="function"&&(n=r,r=void 0),tqu(r,"options"),r=Object.assign({},r),typeof t=="string"&&(t=new qYr(t)),tqu(t,"authority",["string","Object","URL"]);var i=t.protocol||r.protocol||(this.enforceProtocol!="detect"?this.enforceProtocol:null)||"http:",o=""+(t.port!==""?t.port:t.protocol==="http:"?80:443),s=t.hostname||t.host||"localhost",a;if(typeof r.createConnection=="function")a=r.createConnection(t,r);else switch(i){case"http:":a=this.net.connect(o,s,n);break;case"https:":a=this.tls.connect(o,s,PFm.call(this,r,s),n);break;default:throw new Error("Not supprted"+i)}return a}};function Cqo(e){var t={protocol:e.protocol,hostname:e.hostname,hash:e.hash,search:e.search,pathname:e.pathname,path:`${e.pathname}${e.search}`,href:e.href};return e.port!==""&&(t.port=Number(e.port)),(e.username||e.password)&&(t.auth=`${e.username}:${e.password}`),t}var yWt=class e{constructor(t){if(t[0]instanceof e)return t[0];this.args=t,this.method=null,this.protocol=null}},bwe=class extends ywe{constructor(){super(...arguments),this.Agent=vqo.Agent,this.globalAgent=vqo.globalAgent,this.enforceProtocol="https:"}},kFm=new bwe;bwe.globalManager=kFm;bwe.Manager=bwe;var Ewe=class extends ywe{constructor(){super(...arguments),this.Agent=gWt.Agent,this.globalAgent=gWt.globalAgent,this.enforceProtocol="http:"}},FFm=new Ewe;Ewe.globalManager=FFm;Ewe.Manager=Ewe;var nqu=new ywe;nqu.enforceProtocol="detect";ywe.globalManager=nqu;iqu.exports={HttpRequest:Ewe,HttpsRequest:bwe,HTTP2OutgoingMessage:AWt,ClientRequest:AWt,HttpRequestManager:ywe}});var squ=E((xDv,oqu)=>{"use strict";var{HttpRequest:NFm,ClientRequest:jFm}=KYr(),bWt=NFm.globalManager,zFm=bWt.request.bind(bWt),QFm=bWt.get.bind(bWt),MFm=Object.assign({},require("http"));oqu.exports=Object.assign(MFm,{ClientRequest:jFm,globalManager:bWt,request:zFm,get:QFm})});var cqu=E((SDv,aqu)=>{"use strict";var{HttpsRequest:LFm,ClientRequest:_Fm}=KYr(),EWt=LFm.globalManager,UFm=EWt.request.bind(EWt),VFm=EWt.get.bind(EWt),GFm=Object.assign({},require("https"));aqu.exports=Object.assign(GFm,{ClientRequest:_Fm,globalManager:EWt,request:UFm,get:VFm})});var lqu=E((wDv,uqu)=>{"use strict";var{HttpRequestManager:xqo,HTTP2OutgoingMessage:qFm,ClientRequest:WFm}=KYr(),HFm=squ(),KFm=cqu(),IWt=new xqo;xqo.globalManager=IWt;var JFm=IWt.request.bind(IWt),YFm=IWt.get.bind(IWt);uqu.exports={HTTP2OutgoingMessage:qFm,ClientRequest:WFm,globalManager:xqo.globalManager,request:JFm,get:YFm,http:HFm,https:KFm}});var kqo={};$(kqo,{FetchError:()=>rk,Headers:()=>F8,Request:()=>vwe,Response:()=>rne,default:()=>a2m});function rk(e,t,r){Error.call(this,e),this.message=e,this.type=t,r&&(this.code=this.errno=r.code),Error.captureStackTrace(this,this.constructor)}function nO(e){var t=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=r.size;let i=n===void 0?0:n;var o=r.timeout;let s=o===void 0?0:o;e==null?e=null:gqu(e)?e=Buffer.from(e.toString()):e instanceof TVe?e=e[wVe]:Buffer.isBuffer(e)||(Object.prototype.toString.call(e)==="[object ArrayBuffer]"?e=Buffer.from(e):ArrayBuffer.isView(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof DJ.default||(e=Buffer.from(String(e)))),this[vhe]={body:e,disturbed:!1,error:null},this.size=i,this.timeout=s,e instanceof DJ.default&&e.on("error",function(a){let c=a.name==="AbortError"?a:new rk(`Invalid response body while trying to fetch ${t.url}: ${a.message}`,"system",a);t[vhe].error=c})}function Elt(){var e=this;if(this[vhe].disturbed)return nO.Promise.reject(new TypeError(`body used already for: ${this.url}`));if(this[vhe].disturbed=!0,this[vhe].error)return nO.Promise.reject(this[vhe].error);if(this.body===null)return nO.Promise.resolve(Buffer.alloc(0));if(Buffer.isBuffer(this.body))return nO.Promise.resolve(this.body);if(!(this.body instanceof DJ.default))return nO.Promise.resolve(Buffer.alloc(0));let t=[],r=0,n=!1;return new nO.Promise(function(i,o){let s;e.timeout&&(s=setTimeout(function(){n=!0,o(new rk(`Response timeout while trying to fetch ${e.url} (over ${e.timeout}ms)`,"body-timeout"))},e.timeout)),e.body.on("error",function(a){a.name==="AbortError"?(n=!0,o(a)):o(new rk(`Invalid response body while trying to fetch ${e.url}: ${a.message}`,"system",a))}),e.body.on("data",function(a){if(!(n||a===null)){if(e.size&&r+a.length>e.size){n=!0,o(new rk(`content size at ${e.url} over limit: ${e.size}`,"max-size"));return}r+=a.length,t.push(a)}}),e.body.on("end",function(){if(!n){clearTimeout(s);try{i(Buffer.concat(t))}catch(a){o(new rk(`Could not create Buffer from response body for ${e.url}: ${a.message}`,"system",a))}}})})}function XFm(e,t){if(typeof Oqo!="function")throw new Error("The package `encoding` must be installed to use the textConverted() function");let r=t.get("content-type"),n="utf-8",i,o;return r&&(i=/charset=([^;]*)/i.exec(r)),o=e.slice(0,1024).toString(),!i&&o&&(i=/<meta.+?charset=(['"])(.+?)\1/i.exec(o)),!i&&o&&(i=/<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(o),i&&(i=/charset=(.*)/i.exec(i.pop()))),!i&&o&&(i=/<\?xml.+?encoding=(['"])(.+?)\1/i.exec(o)),i&&(n=i.pop(),(n==="gb2312"||n==="gbk")&&(n="gb18030")),Oqo(e,"UTF-8",n).toString()}function gqu(e){return typeof e!="object"||typeof e.append!="function"||typeof e.delete!="function"||typeof e.get!="function"||typeof e.getAll!="function"||typeof e.has!="function"||typeof e.set!="function"?!1:e.constructor.name==="URLSearchParams"||Object.prototype.toString.call(e)==="[object URLSearchParams]"||typeof e.sort=="function"}function Aqu(e){let t,r,n=e.body;if(e.bodyUsed)throw new Error("cannot clone body after it is used");return n instanceof DJ.default&&typeof n.getBoundary!="function"&&(t=new pqu,r=new pqu,n.pipe(t),n.pipe(r),e[vhe].body=t,n=r),n}function yqu(e){return e===null?null:typeof e=="string"?"text/plain;charset=UTF-8":gqu(e)?"application/x-www-form-urlencoded;charset=UTF-8":e instanceof TVe?e.type||null:Buffer.isBuffer(e)||Object.prototype.toString.call(e)==="[object ArrayBuffer]"||ArrayBuffer.isView(e)?null:typeof e.getBoundary=="function"?`multipart/form-data;boundary=${e.getBoundary()}`:e instanceof DJ.default?null:"text/plain;charset=UTF-8"}function bqu(e){let t=e.body;return t===null?0:Buffer.isBuffer(t)?t.length:t&&typeof t.getLengthSync=="function"&&(t._lengthRetrievers&&t._lengthRetrievers.length==0||t.hasKnownLength&&t.hasKnownLength())?t.getLengthSync():null}function ZFm(e,t){let r=t.body;r===null?e.end():Buffer.isBuffer(r)?(e.write(r),e.end()):r.pipe(e)}function vWt(e){if(e=`${e}`,Equ.test(e))throw new TypeError(`${e} is not a legal HTTP header name`)}function fqu(e){if(e=`${e}`,Pqo.test(e))throw new TypeError(`${e} is not a legal HTTP header value`)}function vlt(e,t){t=t.toLowerCase();for(let r in e)if(r.toLowerCase()===t)return r}function Bqo(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"key+value";return Object.keys(e[WC]).sort().map(t==="key"?function(n){return n.toLowerCase()}:t==="value"?function(n){return e[WC][n].join(", ")}:function(n){return[n.toLowerCase(),e[WC][n].join(", ")]})}function wqo(e,t){let r=Object.create(Dqo);return r[Rqo]={target:e,kind:t,index:0},r}function $Fm(e){let t=Object.assign({__proto__:null},e[WC]),r=vlt(e[WC],"Host");return r!==void 0&&(t[r]=t[r][0]),t}function e2m(e){let t=new F8;for(let r of Object.keys(e))if(!Equ.test(r))if(Array.isArray(e[r]))for(let n of e[r])Pqo.test(n)||(t[WC][r]===void 0?t[WC][r]=[n]:t[WC][r].push(n));else Pqo.test(e[r])||(t[WC][r]=[e[r]]);return t}function JYr(e){return typeof e=="object"&&typeof e[Ihe]=="object"}function i2m(e){let t=e&&typeof e=="object"&&Object.getPrototypeOf(e);return!!(t&&t.constructor.name==="AbortSignal")}function o2m(e){let t=e[Ihe].parsedURL,r=new F8(e[Ihe].headers);if(r.has("Accept")||r.set("Accept","*/*"),!t.protocol||!t.hostname)throw new TypeError("Only absolute URLs are supported");if(!/^https?:$/.test(t.protocol))throw new TypeError("Only HTTP(S) protocols are supported");if(e.signal&&e.body instanceof DJ.default.Readable&&!n2m)throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8");let n=null;if(e.body==null&&/^(POST|PUT)$/i.test(e.method)&&(n="0"),e.body!=null){let i=bqu(e);typeof i=="number"&&(n=String(i))}return n&&r.set("Content-Length",n),r.has("User-Agent")||r.set("User-Agent","node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"),e.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip,deflate"),!r.has("Connection")&&!e.agent&&r.set("Connection","close"),Object.assign({},t,{method:e.method,headers:$Fm(r),agent:e.agent})}function CWt(e){Error.call(this,e),this.type="aborted",this.message=e,Error.captureStackTrace(this,this.constructor)}function Iwe(e,t){if(!Iwe.Promise)throw new Error("native promise missing, set fetch.Promise to your favorite alternative");return nO.Promise=Iwe.Promise,new Iwe.Promise(function(r,n){let i=new vwe(e,t),o=o2m(i),s=hqu.default.request,a=i.signal,c=null,u=function(){let g=new CWt("The user aborted a request.");n(g),i.body&&i.body instanceof DJ.default.Readable&&i.body.destroy(g),!(!c||!c.body)&&c.body.emit("error",g)};if(a&&a.aborted){u();return}let l=function(){u(),f()},p=s(o),d;a&&a.addEventListener("abort",l);function f(){p.abort(),a&&a.removeEventListener("abort",l),clearTimeout(d)}i.timeout&&p.once("socket",function(m){d=setTimeout(function(){n(new rk(`network timeout at: ${i.url}`,"request-timeout")),f()},i.timeout)}),p.on("error",function(m){n(new rk(`request to ${i.url} failed, reason: ${m.message}`,"system",m)),f()}),p.on("response",function(m){clearTimeout(d);let g=e2m(m.headers);if(Iwe.isRedirect(m.statusCode)){let v=g.get("Location"),S=v===null?null:s2m(i.url,v);switch(i.redirect){case"error":n(new rk(`redirect mode is set to error: ${i.url}`,"no-redirect")),f();return;case"manual":if(S!==null)try{g.set("Location",S)}catch(R){n(R)}break;case"follow":if(S===null)break;if(i.counter>=i.follow){n(new rk(`maximum redirect reached at: ${i.url}`,"max-redirect")),f();return}let B={headers:new F8(i.headers),follow:i.follow,counter:i.counter+1,agent:i.agent,compress:i.compress,method:i.method,body:i.body,signal:i.signal};if(m.statusCode!==303&&i.body&&bqu(i)===null){n(new rk("Cannot follow redirect with body being a readable stream","unsupported-redirect")),f();return}(m.statusCode===303||(m.statusCode===301||m.statusCode===302)&&i.method==="POST")&&(B.method="GET",B.body=void 0,B.headers.delete("content-length")),r(Iwe(new vwe(S,B))),f();return}}m.once("end",function(){a&&a.removeEventListener("abort",l)});let A=m.pipe(new dqu),y={url:i.url,status:m.statusCode,statusText:m.statusMessage,headers:g,size:i.size,timeout:i.timeout},I=g.get("Content-Encoding");if(!i.compress||i.method==="HEAD"||I===null||m.statusCode===204||m.statusCode===304){c=new rne(A,y),r(c);return}let x={flush:Ilt.default.Z_SYNC_FLUSH,finishFlush:Ilt.default.Z_SYNC_FLUSH};if(I=="gzip"||I=="x-gzip"){A=A.pipe(Ilt.default.createGunzip(x)),c=new rne(A,y),r(c);return}if(I=="deflate"||I=="x-deflate"){m.pipe(new dqu).once("data",function(S){(S[0]&15)===8?A=A.pipe(Ilt.default.createInflate()):A=A.pipe(Ilt.default.createInflateRaw()),c=new rne(A,y),r(c)});return}c=new rne(A,y),r(c)}),ZFm(p,i)})}var DJ,mqu,YYr,hqu,Ilt,wVe,Sqo,TVe,Oqo,vhe,pqu,Equ,Pqo,WC,F8,Rqo,Dqo,SVe,t2m,rne,Ihe,Tqo,r2m,n2m,vwe,dqu,s2m,a2m,Fqo=h(()=>{"use strict";DJ=ye(require("stream"),1),mqu=ye(require("http"),1),YYr=ye(require("url"),1),hqu=ye(lqu(),1),Ilt=ye(require("zlib"),1),wVe=Symbol("buffer"),Sqo=Symbol("type"),TVe=class e{constructor(){this[Sqo]="";let t=arguments[0],r=arguments[1],n=[];if(t){let o=t,s=Number(o.length);for(let a=0;a<s;a++){let c=o[a],u;c instanceof Buffer?u=c:ArrayBuffer.isView(c)?u=Buffer.from(c.buffer,c.byteOffset,c.byteLength):c instanceof ArrayBuffer?u=Buffer.from(c):c instanceof e?u=c[wVe]:u=Buffer.from(typeof c=="string"?c:String(c)),n.push(u)}}this[wVe]=Buffer.concat(n);let i=r&&r.type!==void 0&&String(r.type).toLowerCase();i&&!/[^\u0020-\u007E]/.test(i)&&(this[Sqo]=i)}get size(){return this[wVe].length}get type(){return this[Sqo]}slice(){let t=this.size,r=arguments[0],n=arguments[1],i,o;r===void 0?i=0:r<0?i=Math.max(t+r,0):i=Math.min(r,t),n===void 0?o=t:n<0?o=Math.max(t+n,0):o=Math.min(n,t);let s=Math.max(o-i,0),c=this[wVe].slice(i,i+s),u=new e([],{type:arguments[2]});return u[wVe]=c,u}};Object.defineProperties(TVe.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(TVe.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});rk.prototype=Object.create(Error.prototype);rk.prototype.constructor=rk;rk.prototype.name="FetchError";try{Oqo=require("encoding").convert}catch{}vhe=Symbol("Body internals"),pqu=DJ.default.PassThrough;nO.prototype={get body(){return this[vhe].body},get bodyUsed(){return this[vhe].disturbed},arrayBuffer(){return Elt.call(this).then(function(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)})},blob(){let e=this.headers&&this.headers.get("content-type")||"";return Elt.call(this).then(function(t){return Object.assign(new TVe([],{type:e.toLowerCase()}),{[wVe]:t})})},json(){var e=this;return Elt.call(this).then(function(t){try{return JSON.parse(t.toString())}catch(r){return nO.Promise.reject(new rk(`invalid json response body at ${e.url} reason: ${r.message}`,"invalid-json"))}})},text(){return Elt.call(this).then(function(e){return e.toString()})},buffer(){return Elt.call(this)},textConverted(){var e=this;return Elt.call(this).then(function(t){return XFm(t,e.headers)})}};Object.defineProperties(nO.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});nO.mixIn=function(e){for(let t of Object.getOwnPropertyNames(nO.prototype))if(!(t in e)){let r=Object.getOwnPropertyDescriptor(nO.prototype,t);Object.defineProperty(e,t,r)}};nO.Promise=global.Promise;Equ=/[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/,Pqo=/[^\t\x20-\x7e\x80-\xff]/;WC=Symbol("map"),F8=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;if(this[WC]=Object.create(null),t instanceof e){let r=t.raw(),n=Object.keys(r);for(let i of n)for(let o of r[i])this.append(i,o);return}if(t!=null)if(typeof t=="object"){let r=t[Symbol.iterator];if(r!=null){if(typeof r!="function")throw new TypeError("Header pairs must be iterable");let n=[];for(let i of t){if(typeof i!="object"||typeof i[Symbol.iterator]!="function")throw new TypeError("Each header pair must be iterable");n.push(Array.from(i))}for(let i of n){if(i.length!==2)throw new TypeError("Each header pair must be a name/value tuple");this.append(i[0],i[1])}}else for(let n of Object.keys(t)){let i=t[n];this.append(n,i)}}else throw new TypeError("Provided initializer must be an object")}get(t){t=`${t}`,vWt(t);let r=vlt(this[WC],t);return r===void 0?null:this[WC][r].join(", ")}forEach(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=Bqo(this),i=0;for(;i<n.length;){var o=n[i];let s=o[0],a=o[1];t.call(r,a,s,this),n=Bqo(this),i++}}set(t,r){t=`${t}`,r=`${r}`,vWt(t),fqu(r);let n=vlt(this[WC],t);this[WC][n!==void 0?n:t]=[r]}append(t,r){t=`${t}`,r=`${r}`,vWt(t),fqu(r);let n=vlt(this[WC],t);n!==void 0?this[WC][n].push(r):this[WC][t]=[r]}has(t){return t=`${t}`,vWt(t),vlt(this[WC],t)!==void 0}delete(t){t=`${t}`,vWt(t);let r=vlt(this[WC],t);r!==void 0&&delete this[WC][r]}raw(){return this[WC]}keys(){return wqo(this,"key")}values(){return wqo(this,"value")}[Symbol.iterator](){return wqo(this,"key+value")}};F8.prototype.entries=F8.prototype[Symbol.iterator];Object.defineProperty(F8.prototype,Symbol.toStringTag,{value:"Headers",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(F8.prototype,{get:{enumerable:!0},forEach:{enumerable:!0},set:{enumerable:!0},append:{enumerable:!0},has:{enumerable:!0},delete:{enumerable:!0},keys:{enumerable:!0},values:{enumerable:!0},entries:{enumerable:!0}});Rqo=Symbol("internal");Dqo=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==Dqo)throw new TypeError("Value of `this` is not a HeadersIterator");var e=this[Rqo];let t=e.target,r=e.kind,n=e.index,i=Bqo(t,r),o=i.length;return n>=o?{value:void 0,done:!0}:(this[Rqo].index=n+1,{value:i[n],done:!1})}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));Object.defineProperty(Dqo,Symbol.toStringTag,{value:"HeadersIterator",writable:!1,enumerable:!1,configurable:!0});SVe=Symbol("Response internals"),t2m=mqu.default.STATUS_CODES,rne=class e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};nO.call(this,t,r);let n=r.status||200,i=new F8(r.headers);if(t!=null&&!i.has("Content-Type")){let o=yqu(t);o&&i.append("Content-Type",o)}this[SVe]={url:r.url,status:n,statusText:r.statusText||t2m[n],headers:i}}get url(){return this[SVe].url}get status(){return this[SVe].status}get ok(){return this[SVe].status>=200&&this[SVe].status<300}get statusText(){return this[SVe].statusText}get headers(){return this[SVe].headers}clone(){return new e(Aqu(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok})}};nO.mixIn(rne.prototype);Object.defineProperties(rne.prototype,{url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});Object.defineProperty(rne.prototype,Symbol.toStringTag,{value:"Response",writable:!1,enumerable:!1,configurable:!0});Ihe=Symbol("Request internals"),Tqo=YYr.default.parse,r2m=YYr.default.format,n2m="destroy"in DJ.default.Readable.prototype;vwe=class e{constructor(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;JYr(t)?n=Tqo(t.url):(t&&t.href?n=Tqo(t.href):n=Tqo(`${t}`),t={});let i=r.method||t.method||"GET";if(i=i.toUpperCase(),(r.body!=null||JYr(t)&&t.body!==null)&&(i==="GET"||i==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let o=r.body!=null?r.body:JYr(t)&&t.body!==null?Aqu(t):null;nO.call(this,o,{timeout:r.timeout||t.timeout||0,size:r.size||t.size||0});let s=new F8(r.headers||t.headers||{});if(o!=null&&!s.has("Content-Type")){let c=yqu(o);c&&s.append("Content-Type",c)}let a=JYr(t)?t.signal:null;if("signal"in r&&(a=r.signal),a!=null&&!i2m(a))throw new TypeError("Expected signal to be an instanceof AbortSignal");this[Ihe]={method:i,redirect:r.redirect||t.redirect||"follow",headers:s,parsedURL:n,signal:a},this.follow=r.follow!==void 0?r.follow:t.follow!==void 0?t.follow:20,this.compress=r.compress!==void 0?r.compress:t.compress!==void 0?t.compress:!0,this.counter=r.counter||t.counter||0,this.agent=r.agent||t.agent}get method(){return this[Ihe].method}get url(){return r2m(this[Ihe].parsedURL)}get headers(){return this[Ihe].headers}get redirect(){return this[Ihe].redirect}get signal(){return this[Ihe].signal}clone(){return new e(this)}};nO.mixIn(vwe.prototype);Object.defineProperty(vwe.prototype,Symbol.toStringTag,{value:"Request",writable:!1,enumerable:!1,configurable:!0});Object.defineProperties(vwe.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0}});CWt.prototype=Object.create(Error.prototype);CWt.prototype.constructor=CWt;CWt.prototype.name="AbortError";dqu=DJ.default.PassThrough,s2m=YYr.default.resolve;Iwe.isRedirect=function(e){return e===301||e===302||e===303||e===307||e===308};Iwe.Promise=global.Promise;a2m=Iwe});var PVe=E(IM=>{"use strict";var Che={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},xWt={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"},c2m="tag:yaml.org,2002:",u2m={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function Iqu(e){let t=[0],r=e.indexOf(`
|
|
540
540
|
`);for(;r!==-1;)r+=1,t.push(r),r=e.indexOf(`
|
|
541
541
|
`,r);return t}function vqu(e){let t,r;return typeof e=="string"?(t=Iqu(e),r=e):(Array.isArray(e)&&(e=e[0]),e&&e.context&&(e.lineStarts||(e.lineStarts=Iqu(e.context.src)),t=e.lineStarts,r=e.context.src)),{lineStarts:t,src:r}}function Nqo(e,t){if(typeof e!="number"||e<0)return null;let{lineStarts:r,src:n}=vqu(t);if(!r||!n||e>n.length)return null;for(let o=0;o<r.length;++o){let s=r[o];if(e<s)return{line:o,col:e-r[o-1]+1};if(e===s)return{line:o+1,col:1}}let i=r.length;return{line:i,col:e-r[i-1]+1}}function l2m(e,t){let{lineStarts:r,src:n}=vqu(t);if(!r||!(e>=1)||e>r.length)return null;let i=r[e-1],o=r[e];for(;o&&o>i&&n[o-1]===`
|
|
542
542
|
`;)--o;return n.slice(i,o)}function p2m({start:e,end:t},r,n=80){let i=l2m(e.line,r);if(!i)return null;let{col:o}=e;if(i.length>n)if(o<=n-10)i=i.substr(0,n-1)+"\u2026";else{let l=Math.round(n/2);i.length>o+l&&(i=i.substr(0,o+l-1)+"\u2026"),o-=i.length-n,i="\u2026"+i.substr(1-n)}let s=1,a="";t&&(t.line===e.line&&o+(t.col-e.col)<=n+1?s=t.col-e.col:(s=Math.min(i.length+1,n)-o,a="\u2026"));let c=o>1?" ".repeat(o-1):"",u="^".repeat(s);return`${i}
|
|
@@ -3470,7 +3470,7 @@ ${fal.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&PXo(th
|
|
|
3470
3470
|
`).length),this}updateBottomBar(t){return iKt(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+`
|
|
3471
3471
|
`}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&&xin(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var fm=ye(J4(),1),Rcl=ye(NHt(),1);var non=ye(J4(),1),Pcl=ye(NHt(),1),ion=function(e,t,r){return typeof e[t]!="function"?(0,non.of)(e):(0,non.from)((0,Pcl.default)(e[t])(r).then(n=>(e[t]=n,e)))};var Bcl={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}},Vft=class extends F5e{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,fm.from)(t):(0,fm.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,fm.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,fm.from)([t]),this.process=n.pipe((0,fm.concatMap)(this.processQuestion.bind(this)),(0,fm.publish)()),this.process.connect(),this.process.pipe((0,fm.reduce)((i,o)=>(Bcl.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,fm.defer)(()=>(0,fm.of)(t).pipe((0,fm.concatMap)(this.setDefaultType.bind(this)),(0,fm.concatMap)(this.filterIfRunnable.bind(this)),(0,fm.concatMap)(()=>ion(t,"message",this.answers)),(0,fm.concatMap)(()=>ion(t,"default",this.answers)),(0,fm.concatMap)(()=>ion(t,"choices",this.answers)),(0,fm.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,fm.defer)(()=>(0,fm.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,fm.defer)(()=>(0,fm.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&Bcl.get(this.answers,t.name)!==void 0)return fm.EMPTY;if(t.when===!1)return fm.EMPTY;if(typeof t.when!="function")return(0,fm.of)(t);let{answers:r}=this;return(0,fm.defer)(()=>(0,fm.from)((0,Rcl.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,fm.filter)(n=>n!=null)))}};function Dcl(e){let t=function(r,n){let i;try{i=new Vft(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",sKt),this.registerPrompt("input",P5e),this.registerPrompt("number",aKt),this.registerPrompt("confirm",cKt),this.registerPrompt("rawlist",uKt),this.registerPrompt("expand",lKt),this.registerPrompt("checkbox",pKt),this.registerPrompt("password",fKt),this.registerPrompt("editor",EKt)},t.restoreDefaultPrompts(),t}var XZo=Dcl();function Gph(e,t){XZo.registerPrompt(e,t)}function qph(){XZo.restoreDefaultPrompts()}var Wph={prompt:XZo,ui:{BottomBar:IKt,Prompt:Vft},createPromptModule:Dcl,registerPrompt:Gph,restoreDefaultPrompts:qph,Separator:FM},Fu=Wph;var Hph=["prod","pre-prod","beta","dev","local"];function Kph(e){return Hph.some(t=>t===e)}function YJ(e="prod"){let t=e?.trim();return t!=null&&Kph(t)?t:"local"}function oon(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?!1:process.env.FERN_DISABLE_TELEMETRY!=="true"}var Gft=require("path");function Fcl(){let e=Jph();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function Jph(e=process.argv[1]?(0,Gft.dirname)(process.argv[1]):process.cwd(),t=Gft.sep==="\\"){let r=t?kcl(e):e;return n=>{if(!n)return;let i=t?kcl(n):n,{dir:o,base:s,ext:a}=Gft.posix.parse(i);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let c=decodeURIComponent(s);o||(o=".");let u=o.lastIndexOf("/node_modules");if(u>-1)return`${o.slice(u+14).replace(/\//g,".")}:${c}`;if(o.startsWith(r)){let l=o.slice(r.length+1).replace(/\//g,".");return l?`${l}:${c}`:c}return c}}function kcl(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var lO={};$(lO,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>Con,DOMExceptionCoercer:()=>m$o,EXCEPTION_STEP_INTERNAL_FIELDS:()=>RKt,ErrorCoercer:()=>TKt,ErrorEventCoercer:()=>h$o,ErrorPropertiesBuilder:()=>wKt,EventCoercer:()=>g$o,ExceptionStepsBuffer:()=>E$o,ObjectCoercer:()=>PKt,PrimitiveCoercer:()=>BKt,PromiseRejectionEventCoercer:()=>A$o,ReduceableCache:()=>y$o,StringCoercer:()=>OKt,chromeStackLineParser:()=>l$o,createDefaultStackParser:()=>d$o,createStackParser:()=>vul,geckoStackLineParser:()=>p$o,getInjectedReleaseId:()=>udh,getUtf8ByteLength:()=>xul,nodeStackLineParser:()=>gul,opera10StackLineParser:()=>dul,opera11StackLineParser:()=>mul,resolveExceptionStepsConfig:()=>b$o,reverseAndStripFrames:()=>Iul,stripReservedExceptionStepFields:()=>sdh,winjsStackLineParser:()=>ful});var jM=(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.AiQueue="ai_queue",e.AiCaptureQueue="ai_capture_queue",e.LogsQueue="logs_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.PushRegistered="push_registered",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysInProgress="surveys_in_progress",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e})({});function S1e(e){let t=[];return JSON.stringify(e,function(r,n){if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(n))return"[Circular]";t.push(n)}return n}})??"null"}var Yph=Array.isArray,jcl=Object.prototype,C$v=jcl.hasOwnProperty,son=jcl.toString,X4=Yph||function(e){return son.call(e)==="[object Array]"};var vKt=e=>e===Object(e)&&!X4(e);var $he=e=>e===void 0,pk=e=>son.call(e)=="[object String]",ZZo=e=>pk(e)&&e.trim().length===0,$Zo=e=>e===null,XJ=e=>$he(e)||$Zo(e),qft=e=>son.call(e)=="[object Number]"&&e===e;var zcl=e=>son.call(e)==="[object Boolean]";function aon(e){return e===null||typeof e!="object"}function N5e(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function w1e(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Lcl(e,Error)}}function Qcl(e){return N5e(e,"ErrorEvent")}function Wft(e){return"u">typeof Event&&Lcl(e,Event)}function Mcl(e){return N5e(e,"Object")}function Lcl(e,t){try{return e instanceof t}catch{return!1}}var Xph=["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","pinterestbot","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"],con=new Map,Zph=256;function $ph(e,t){let r="";for(let n=0;n<t.length;n++){let i=t[n];r+=i.length+":"+i}return e.length+":"+e+"|"+t.length+":"+r}var _cl=function(e,t=[]){if(!e)return!1;let r=$ph(e,t),n=con.get(r);if(n!==void 0)return n;let i=e.toLowerCase(),o=Xph.concat(t).some(s=>i.indexOf(s.toLowerCase())!==-1);return con.size>=Zph&&con.clear(),con.set(r,o),o};function CKt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),qft(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),CKt(i??r,t,r,n))}var efh=864e5,tfh=1,rfh=10;function Ucl(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??tfh,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??rfh}}var uon=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=CKt(t.bucketSize,0,100,t._logger),this._refillRate=CKt(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=CKt(t.refillInterval,0,efh,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 lon="0123456789abcdef",pon=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+=lon.charAt(this.bytes[r]>>>4),t+=lon.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+=lon.charAt(this.bytes[r]>>>4),t+=lon.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}},e$o=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??nfh()}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 pon.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,pon.ofInner(t)}},nfh=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),Vcl,_N=()=>ifh().toString(),ifh=()=>(Vcl||(Vcl=new e$o)).generate();var fon=class{add(t){let r=_N(),n=++this.nextId;return this.promiseByIds[r]={id:n,promise:t},t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds).map(n=>n.promise),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds).map(n=>n.promise),r=t.length}getPromises(t=[],r=this.nextId){let n=new Set(t);return Object.values(this.promiseByIds).filter(i=>i.id<=r&&!n.has(i.promise)).map(i=>i.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}};function ofh(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var Gcl=(e,t,r)=>{function n(o,...s){t(()=>{let a=r[o];a(e,...s)})}return{debug:(...o)=>{n("debug",...o)},info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{r.error(e,...o)},createLogger:o=>Gcl(`${e} ${o}`,t,r)}},sfh=e=>e();function qcl(e,t=sfh){return Gcl(e,t,ofh())}var Kft="Mobile",mon="iOS",Hft="Android",Ycl="Tablet",Q$v=Hft+" "+Ycl;var cfh="Apple",M$v=cfh+" Watch",Xcl="Safari",hon="BlackBerry",Zcl="Samsung",ufh=Zcl+"Browser",lfh=Zcl+" Internet",gon="Chrome",pfh=gon+" OS",ffh=gon+" "+mon,$cl="Internet Explorer",dfh=$cl+" "+Kft,n$o="Opera",L$v=n$o+" Mini",eul="Edge",mfh="Microsoft "+eul,i$o="Firefox",hfh=i$o+" "+mon,o$o="Nintendo",s$o="PlayStation",don="Xbox",gfh=Hft+" "+Kft,Afh=Kft+" "+Xcl,xKt="Windows",yfh=xKt+" Phone";var tul="Generic",_$v=tul+" "+Kft.toLowerCase(),U$v=tul+" "+Ycl.toLowerCase(),bfh="Konqueror",Efh="Oculus Browser",Wcl="Vivaldi",Ifh="Yandex",Hcl="Whale",vfh="DuckDuckGo",Cfh="Pale Moon",Kcl="Waterfox",Jcl="Brave",rul="Claude",nul="Codex",iul="ChatGPT",xfh="Google Search App",O0="(\\d+(\\.\\d+)?)",t$o=new RegExp("Version/"+O0),r$o=new RegExp("("+rul+"|"+nul+"|"+iul+")\\/"+O0);var V$v=new RegExp(don,"i"),G$v=new RegExp(s$o+" \\w+","i"),q$v=new RegExp(o$o+" \\w+","i"),Sfh=new RegExp(hon+"|PlayBook|BB10","i"),wfh={"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 W$v={[dfh]:[new RegExp("rv:"+O0)],[mfh]:[new RegExp(eul+"?\\/"+O0)],[gon]:[new RegExp("("+gon+"|CrMo)\\/"+O0)],[ffh]:[new RegExp("CriOS\\/"+O0)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+O0)],[Xcl]:[t$o],[Afh]:[t$o],[n$o]:[new RegExp("("+n$o+"|OPR)\\/"+O0)],[i$o]:[new RegExp(i$o+"\\/"+O0)],[hfh]:[new RegExp("FxiOS\\/"+O0)],[bfh]:[new RegExp("Konqueror[:/]?"+O0,"i")],[hon]:[new RegExp(hon+" "+O0),t$o],[gfh]:[new RegExp("android\\s"+O0,"i")],[lfh]:[new RegExp(ufh+"\\/"+O0)],[Efh]:[new RegExp("OculusBrowser\\/"+O0)],[Wcl]:[new RegExp(Wcl+"\\/"+O0)],[Ifh]:[new RegExp("YaBrowser\\/"+O0)],[Hcl]:[new RegExp(Hcl+"\\/"+O0)],[Jcl]:[new RegExp(Jcl+"\\/"+O0)],[rul]:[r$o],[nul]:[r$o],[iul]:[r$o],[vfh]:[new RegExp("(DuckDuckGo|Ddg)\\/"+O0)],[Cfh]:[new RegExp("PaleMoon\\/"+O0)],[Kcl]:[new RegExp(Kcl+"\\/"+O0)],[xfh]:[new RegExp("GSA\\/"+O0)],[$cl]:[new RegExp("(rv:|MSIE )"+O0)],Mozilla:[new RegExp("rv:"+O0)]};var H$v=[[new RegExp(don+"; "+don+" (.*?)[);]","i"),e=>[don,e&&e[1]||""]],[new RegExp(o$o,"i"),[o$o,""]],[new RegExp(s$o,"i"),[s$o,""]],[Sfh,[hon,""]],[new RegExp(xKt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[yfh,""];if(new RegExp(Kft).test(t)&&!/IEMobile\b/.test(t))return[xKt+" "+Kft,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=wfh[n]||"";return/arm/i.test(t)&&(i="RT"),[xKt,i]}return[xKt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[mon,t.join(".")]}return[mon,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=$he(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Hft+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Hft+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Hft,t.join(".")]}return[Hft,""]}],[/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/,[pfh,""]],[/Linux|debian/i,["Linux",""]]];var Aon="[Circular]",yon="[Truncated]",rG="[Unserializable]",oul="[Function]",Y$v=Date.prototype.getTime,X$v=Date.prototype.toISOString;function xne(e){let t="";for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(t+=e[r]+e[r+1],r++):t+="\uFFFD"}else t+=n>=56320&&n<=57343?"\uFFFD":e[r]}return t}function ege(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(let n of r){let i;try{i=t[n]}catch{i=rG}Object.defineProperty(e,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}function a$o(e,t=Date.now()){if(typeof e!="string"||!e)return;let r=e.trim(),n=/^\d+\s*,/.test(r)?r.slice(0,r.indexOf(",")).trim():r;if(/^\d+$/.test(n)){let s=1e3*Math.min(Number(n),300);return s>0?s:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(n))return;let i=/^\w{3} \w{3} /.test(n)?n+" GMT":n,o=Date.parse(i)-t;if(!(!Number.isFinite(o)||o<=0))return Math.min(o,3e5)}var j5e=class{record(t){if(t.kind==="too-large")return;if(t.kind!=="retry-later")return void this.reset();if(!t.retryAfterMs)return;let r=this.isOpen(),n=Date.now(),i=Math.min(t.retryAfterMs,3e5);if(!r){this._installedAt=n,this._until=n+i;return}this._until=Math.max(this._until,Math.min(n+i,this._installedAt+3e5))}remainingMs(){let t=Date.now();if(t<this._installedAt-5e3)return this.reset(),0;let r=Math.min(3e5,Math.max(0,this._until-t));return r===0&&this.reset(),r}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}};var sul="utf8",Tfh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ofh(e){return typeof e=="string"&&Tfh.test(e)}function z5e(e,t){return Ofh(e)?e:t()}function Jft(e,t){let r=new Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function aul(e){return e?.replace(/\/+$/,"")}async function cul(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 c$o(){return new Date().toISOString()}function UN(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function T1e(e,t,r){let n;try{return await Promise.race([e,new Promise((i,o)=>{n=UN(()=>{try{r?.(),i()}catch(s){o(s)}},t)})])}finally{clearTimeout(n)}}var uul=e=>e&&typeof e.then=="function";function SKt(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var bon,lul,Eon;function pul(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return Eon&&r.length===lul||(lul=r.length,Eon=r.reduce((n,i)=>{bon||(bon={});let o=bon[i];if(o)n[o[0]]=o[1];else{let s=e(i);for(let a=s.length-1;a>=0;a--){let u=s[a]?.filename,l=t[i];if(u&&l){n[u]=l,bon[i]=[u,l];break}}}return n},{})),Eon}var u$o=50,Pfh=1e3,Bfh=100,Rfh=4,wKt=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),c=this.parseStacktrace(s,a);return{$exception_list:this.convertToExceptionList(c,i),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&X4(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;if(t.stack!=""&&t.stack!=null)try{i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?r.skipFirstLines:0),r.chunkIdMap)}catch{}return{...t,cause:n,stack:i,errors:t.errors?.map(o=>this.parseStacktrace(o,r))}}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=[],i=(o,s,a)=>{let c=n.length,u=s===void 0?{type:typeof r.type=="string"&&r.type.length>0?r.type:"generic",...typeof r.handled=="boolean"?{handled:r.handled}:r.handled===void 0?{handled:!0}:{},synthetic:typeof r.synthetic=="boolean"?r.synthetic:o.synthetic,exception_id:c}:{type:"chained",source:a,synthetic:o.synthetic,exception_id:c,parent_id:s},l={type:o.type,value:o.value,mechanism:u};o.stack&&(l.stacktrace={type:"raw",frames:o.stack}),n.push(l),o.cause&&i(o.cause,c,"cause");for(let p of o.errors??[])i(p,c,"member")};return i(t),n}buildParsingContext(t){return{chunkIdMap:pul(this.stackParser),skipFirstLines:t.skipFirstLines??1}}getAggregateErrors(t){try{if(w1e(t)){let r=Object.getPrototypeOf(t);for(let n=0;r&&n<Bfh;n++){let i=Object.getOwnPropertyDescriptor(r,"constructor")?.value;if(typeof i=="function"&&i.name==="AggregateError"){let o=t.errors;return X4(o)?o:void 0}r=Object.getPrototypeOf(r)}}}catch{}}buildCoercingContext(t,r,n=0){let i=0,o=0,s=!1,a=new Set,c=[],u={},l=(f,m,g=0)=>{let A=p(m,g),y=A.apply;if(A.apply=R=>{c.push(f);try{return y(R)}finally{c.pop()}},g>Rfh||g>0&&c.indexOf(f)!==-1)return this.coerceFallback(A);let I=typeof f=="object"&&f!==null||typeof f=="function";if(g===0&&i>=u$o||I&&a.has(f))return;I&&a.add(f),g===0&&i++;let x=this.getAggregateErrors(f);s||=!!x;let v;try{if(v=this.applyCoercers(f,A),!v)throw u}catch(R){if(R===u){g===0&&i--;return}if(!s)throw R;v=this.coerceFallback(A)}if(!x||i>=u$o)return v;let S;try{S=x.length}catch{return v}if(!Number.isInteger(S)||S<0||S>4294967295)return v;let B=[];for(let R=0;i<u$o&&o<Pfh&&R<S;R++){o++;let D;try{D=A.next(x[R])}catch{i++,D=this.coerceFallback(p(m+1))}D&&B.push(D)}return{...v,errors:B}},p=(f,m=0)=>({...r,syntheticException:f==0?r.syntheticException:void 0,mechanism:f==0?t:{},apply:g=>{let A=l(g,f,m+1);if(!A)throw u;return A},next:g=>l(g,f+1)}),d=p(n);return{...d,apply:f=>l(f,n)??this.coerceFallback(d)}}};var cR="?",Dfh="<anonymous>",kfh=/^([a-z][a-z0-9.+-]+):/i,Ffh=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function Nfh(e){if(!e||e===Dfh)return!1;let t=kfh.exec(e);return!t||Ffh.includes(t[1].toLowerCase())}function Sne(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?cR:r,in_app:Nfh(t)};return $he(n)||(o.lineno=n),$he(i)||(o.colno=i),o}var Ion=(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]:cR,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var jfh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,zfh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Qfh=/\((\S*)(?::(\d+))(?::(\d+))\)/,l$o=(e,t)=>{let r=jfh.exec(e);if(r){let[,i,o,s]=r;return Sne(t,i,cR,+o,+s)}let n=zfh.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=Qfh.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=Ion(n[1]||cR,n[2]);return Sne(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var Mfh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Lfh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,p$o=(e,t)=>{let r=Mfh.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=Lfh.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]||cR;return[o,i]=Ion(o,i),Sne(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var _fh=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ful=(e,t)=>{let r=_fh.exec(e);return r?Sne(t,r[2],r[1]||cR,+r[3],r[4]?+r[4]:void 0):void 0};var Ufh=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,dul=(e,t)=>{let r=Ufh.exec(e);return r?Sne(t,r[2],r[3]||cR,+r[1]):void 0},Vfh=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,mul=(e,t)=>{let r=Vfh.exec(e);return r?Sne(t,r[5],r[3]||r[4]||cR,+r[1],+r[2]):void 0};var Gfh=/^\s*[-]{4,}$/,qfh=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Wfh=/^Promise\.(?:all|any)$/,Hfh=/^index \d+$/,Kfh="node:internal/promise",gul=(e,t)=>{let r=e.match(qfh);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||cR,o=s?`${s}.${a}`:a);let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&r[5]&&!u&&(c=r[5]),Wfh.test(o)&&Hfh.test(c||"")&&(c=Kfh),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:hul(r[3]),colno:hul(r[4]),in_app:Jfh(c||"",u),platform:t}}if(e.match(Gfh))return{filename:e,platform:t}};function Jfh(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 hul(e){return parseInt(e||"",10)||void 0}var Aul=/\(error: (.*)\)/,yul=50,Yfh=10,Xfh=1e3;function f$o(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function Zfh(e){for(let t=1;t<=Yfh;t++){let r=e.length-2*t;if(r<0)break;let n=!0;for(let i=0;i<t;i++){let o=e[r+i];if(!f$o(o,e[r+t+i])){n=!1;break}}if(n){for(let i=0;i<t;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}function $fh(e,t){let r=t.start+t.length,n=Eul(e,t);n&&e.splice(r+n===e.length?r:t.start,n)}function bul(e,t){let r=t.start;for(;r>0&&f$o(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function Eul(e,t){let r=t.start+t.length,n=r;for(;n<e.length&&f$o(e[n],e[n-t.length]);)n++;return n-r}function edh(e,t){let r=t[0],n=e.length-(r?bul(e,r):0);for(let i of t)n-=Eul(e,i);return n}function tdh(e){let t=e.map(n=>`${n.function}|${n.filename}|${n.lineno}|${n.colno}|${n.module}`),r=0;for(let n=1;n<t.length;n++)rdh(t,n,r)&&(r=n);e.push(...e.splice(0,r))}function rdh(e,t,r){for(let n=0;n<e.length;n++){let i=e[(t+n)%e.length],o=e[(r+n)%e.length];if(i!==o)return i<o}return!1}function Iul(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,yul).map(r=>({...r,filename:r.filename||ndh(t).filename,function:r.function||cR}))}function ndh(e){return e[e.length-1]||{}}function d$o(){return vul("web:javascript",l$o,p$o)}function vul(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
|
|
3472
3472
|
`),s=Math.min(o.length,n+Xfh),a=[];for(let l=n;l<s;l++){let p=o[l];if(p.length>1024)continue;let d=Aul.test(p)?p.replace(Aul,"$1"):p;if(!d.match(/\S*Error: /)){for(let f of t){let m=f(d,e);if(m){i.push(m);let g=Zfh(i);if(g){for(let A=a.length-1;A>=0;A--){let y=a[A];if(y.start+y.length<=g.start)break;a.pop()}a.push(g)}break}}if(edh(i,a)>=yul)break}}let c=[...a].sort((l,p)=>p.start-l.start),u=c[c.length-1];if(u){let l=bul(i,u);i.splice(u.start-l,l);for(let p of c)p.start-=l}for(let l of c)$fh(i,l);return a.some(l=>l.start===0&&i.length===l.length)&&tdh(i),Iul(i)}}var m$o=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=pk(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 N5e(t,"DOMException")}isDOMError(t){return N5e(t,"DOMError")}};var TKt=class{match(t){return w1e(t)}coerce(t,r){let n=this.getStack(t),i=n===void 0?r.syntheticException?.stack:void 0,o=!!i;return{type:this.getType(t),value:this.getMessage(t,r),stack:n??i,cause:t.cause?r.next(t.cause):void 0,synthetic:o}}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){try{let r=t.stacktrace;if(typeof r=="string"&&r.length>0)return r;let n=t.stack;return typeof n=="string"&&n.length>0?n:void 0}catch{return}}};var h$o=class{match(t){if(!Qcl(t))return!1;let r=t;return r.error!=null||this._hasUsableMessage(r)}coerce(t,r){if(t.error!=null)return r.apply(t.error);let n=r.apply(t.message);return{...n,stack:this._buildLocationStack(t)??n.stack,synthetic:!0}}_hasUsableMessage(t){return pk(t.message)&&t.message.length>0}_buildLocationStack(t){let r=t,n=r.lineno??0,i=r.colno??0;if(!(!pk(r.filename)||r.filename.length===0)&&n!==0)return`Error
|
|
3473
|
-
at ${r.filename}:${n}:${i}`}};var idh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,OKt=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(idh);return i&&(r=i[1],n=i[2]),[r,n]}};var Cul=["fatal","error","warning","log","info","debug"];function von(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 PKt=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:this.getStack(t)??r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){if(Wft(t))return t.constructor.name;let r="name"in t?t.name:void 0;return pk(r)&&!ZZo(r)?r:"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=von(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return pk(t)&&!ZZo(t)&&Cul.indexOf(t)>=0}getStack(t){try{return pk(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:pk(t.stack)&&t.stack.length>0?t.stack:void 0}catch{return}}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(w1e(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var g$o=class{match(t){return Wft(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${von(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var BKt=class{match(t){return aon(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var A$o=class{match(t){return N5e(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Wft(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return aon(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var y$o=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 RKt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},odh=new Set([RKt.MESSAGE,RKt.TIMESTAMP]),Con={enabled:!0,max_bytes:32768};function b$o(e){return e?{enabled:e.enabled??Con.enabled,max_bytes:adh(e.max_bytes,Con.max_bytes)}:{...Con}}function sdh(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>odh.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var E$o=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=b$o(t)}setConfig(t){this._config=b$o(t),this._trimToMaxBytes()}add(t){let r=cdh(t);if(!r)return;let n=xul(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(t=>t.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let t=this._entries.shift();t&&(this._totalBytes-=t.bytes)}}};function adh(e,t){if(!qft(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function cdh(e){let t;try{t=S1e(e)}catch{return}try{let r=JSON.parse(t);if(!vKt(r))return;let n=r,i=n[RKt.MESSAGE],o=n[RKt.TIMESTAMP];return!pk(i)||i.trim().length===0||!pk(o)&&!qft(o)?void 0:{step:n,json:t}}catch{return}}function xul(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let n=0;n<t.length;n++)t[n]==="%"?(r+=1,n+=2):r+=1;return r}function udh(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var I$o=e=>{if("flags"in e){let t=Sul(e.flags),r=wul(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,Yft(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,ldh(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function ldh(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 Sul=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,DKt(r)]).filter(([,t])=>t!==void 0)),wul=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?Yft(n):void 0]}))},DKt=e=>e===void 0?void 0:e.variant??e.enabled,Yft=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var Tul=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx"],pdh=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...Tul,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],kKt=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return pdh.forEach(n),t.forEach(n),r};var xon=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 v$o(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var ddh="NativeGzipValidationError",mdh=31,hdh=139,gdh=8,Adh=e=>e.length>=2&&e[0]===mdh&&e[1]===hdh;var FKt,ydh=()=>{if(FKt)return FKt;FKt=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;FKt[e]=t>>>0}return FKt},bdh=e=>{let t=ydh(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},Son=e=>{throw Jft(ddh,`Native gzip produced invalid output: ${e}`)},Edh=async(e,t)=>{e.size<18&&Son("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!Adh(r)||r[2]!==gdh)&&Son("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==bdh(t)&&Son("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&Son("invalid-size")};async function NKt(e,t=!0,r){try{let n=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),o=i.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async u=>{try{await o.abort(u)}catch{}throw u}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await Edh(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var nG=class extends Error{constructor(t,r,n,i){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.responseBodyDeadline=n,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return a$o(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let t=Jft("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=UN(()=>{this._bodyReadTimedOut=!0;let o=Jft("AbortError","Response body read timed out");i(o),this.cancelResponseBody(o)},this.responseBodyDeadline-Date.now())}),r;try{r=Promise.resolve(this.response.text())}catch(n){r=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([r,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(t=>JSON.parse(t))}cancelResponseBody(t){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(t),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},tge=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var Dul=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function Oul(e){if(e instanceof nG){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}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 Idh(e){return typeof e=="object"&&(e instanceof nG||kul(e))}function kul(e){return e instanceof tge}function vdh(e){if(e instanceof nG)return e.status===502||e.status===504;if(!(e instanceof tge))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var Pul=10485760;function Bul(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,sul):new TextEncoder().encode(e).length}catch{return 0}}function Xft(e){return typeof e=="object"&&e instanceof nG&&e.status===413}function won(e){return e instanceof nG?e.status===408||e.status===429||e.status>=500:kul(e)}function Rul(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var C$o="default",jKt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new wKt([new TKt,new PKt,new OKt,new BKt],d$o())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new fon,this._events=new xon,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=qcl("[PostHog]",this.logMsgIfDebug.bind(this)),o&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=aul(i||"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:won},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=r.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=(r.disabled??!1)||o,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,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=!v$o()||(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(jM.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(jM.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(jM.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){let r=t.properties||{},n={...r,...this.getCommonEventProperties()};return Dul(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=kKt(n)),{distinct_id:t.distinct_id,event:t.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}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 groupIdentifyStatelessImmediate(t,r,n,i,o,s){let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});await this.sendImmediate("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,{type:"required",consume:i=>i.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).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=!1){await this._initPromise;let a=s?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,u={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(u.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(u.evaluation_contexts=this.evaluationContexts);let l=this.getEvaluationRuntime();l&&(u.evaluation_runtime=l);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(u)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:vdh},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:I$o(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof nG)return{type:"api_error",statusCode:t.status};if(t instanceof tge){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 c=DKt(a.response);return c===void 0&&(c=!1),{response:c,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 c=a[t];return c===void 0?null:c}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={geoip_disable:o??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let c=await this.getFlags(t,r,n,i,a);if(!c.success)return;let u=c.response;return u.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"),u.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:u?.requestId,quotaLimited:u.quotaLimited}):u}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(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,{type:"required",consume:o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);return this._logger.error(a),this._events.emit("error",new Error(s)),Promise.resolve(void 0)}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(jM.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(jM.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(jM.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return C$o}persistedQueueKeyForRoute(t){return jM.Queue}getActiveQueueRoutes(){return[C$o]}getRouteQueue(t){return this.getPersistedProperty(this.persistedQueueKeyForRoute(t))||[]}enqueue(t,r,n,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let s=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(o)),a=this.getPersistedProperty(s)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:o}),this.setPersistedProperty(s,a),this._events.emit(t,o),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=UN(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,i??this.getQueueRouteKey(o))}catch(s){this._events.emit("error",s)}}}normalizeMessage(t){let{type:r,library:n,library_version:i,...o}=t,s=Rul(o.properties)?o.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),i!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:i}),s&&(o.properties=s),o.uuid=z5e(o.uuid,_N),o}normalizeTimestampForWire(t){let r=t instanceof Date?t:typeof t=="string"?new Date(t):null;if(!r||Number.isNaN(r.getTime()))return t;let n=r.toISOString(),i=typeof t=="string"?t.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}prepareMessage(t,r){let n={...t,timestamp:r?.timestamp?r?.timestamp:c$o(),uuid:z5e(r?.uuid,_N)};return(r?.disableGeoip??this.disableGeoip)&&(Rul(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async t=>{await Oul(t)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(t,r=[]){let n=r.filter(o=>!!o),i=0;for(;;){let o=this.promiseQueue.getPromises([...n,...this.flushPromises],t);if(o.length===0)return;i>0&&this._logger.debug(`flush() re-checking ${o.length} pending promise(s) before flushing`),await Promise.all(o.map(s=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(t){if(this.disabled)return Promise.resolve();if(!t&&this.pendingFlushPromise)return this.pendingFlushPromise;let r=this.flushPromise,n=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(t)return this.waitForPendingPromises(n,[r,i])}).then(()=>SKt([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),SKt([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}compressPayload(t){return NKt(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=C$o){let i={api_key:this.apiKey,batch:t.map(u=>{if(!u)return u;let l=this.normalizeTimestampForWire(u.timestamp);return l===u.timestamp?u:{...u,timestamp:l}}),sent_at:c$o()};this.historicalMigration&&(i.historical_migration=!0);let o=S1e(i),s=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(o),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||o};await this.fetchWithRetry(s,c,{type:"successful-write"},r)}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(i=>this.getRouteQueue(i).length>0))return;let r=[],n;for(let i of t)try{await this._flushRoute(i,r)}catch(o){n===void 0&&(n=o)}if(n!==void 0)throw n;this._events.emit("flush",r)}async _flushRoute(t,r){let n=this.persistedQueueKeyForRoute(t),i=this.getPersistedProperty(n)||[];if(!i.length)return;let o=i.length,s=0;for(;i.length>0&&s<o;){let a=i.slice(0,this.maxBatchSize),c=a.map(p=>p.message===void 0?p.message:this.normalizeMessage(p.message)),u=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(y=>y===m||typeof g=="string"&&g.length>0&&y.message?.uuid===g);return A===-1?!0:(d.splice(A,1),!1)});this.setPersistedProperty(n,f),i=f,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},l={retryCheck:p=>Xft(p)?!1:won(p)};try{await this.sendBatch(c,l,t)}catch(p){if(Xft(p)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw p instanceof tge||await u(),this._events.emit("error",p),p}await u(),r.push(...c),s+=c.length}}async _sendOtlpBatch({path:t,auth:r,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let i;try{i=JSON.stringify(n)}catch(l){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,l)),{kind:"too-large",measuredLocally:!0}}let o=Bul(i);if(o>Pul)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${Pul}`)),{kind:"too-large",measuredLocally:!0};let s=r==="bearer"?`${this.host}/i/v1/${t}`:`${this.host}/i/v1/${t}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(i),c=a||i,u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...r==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(s,u,{type:"successful-write"},{retryCheck:l=>Xft(l)||l instanceof nG&&l.retryAfterMs!==void 0?!1:won(l)}),{kind:"ok"}}catch(l){if(Xft(l))return{kind:"too-large"};if(won(l)){let p=l instanceof nG?l.retryAfterMs:void 0;return{kind:"retry-later",error:l,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:l}}}async _sendLogsBatch(t){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:t})}async _sendMetricsBatch(t){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:t})}async _sendTracesBatch(t){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:t})}async fetchWithRetry(t,r,n,i,o){let s=r.body?r.body:"",a=Bul(s),c={...this._retryOptions,...i},u=0;return await cul(async()=>{u++;let l=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((x,v)=>{f=UN(()=>{let S=Jft("AbortError",`Request timed out after ${p}ms`);v(S),l.abort(S)},p)}),g,A=!1,y,I=()=>y??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let x;try{x=this.fetch(t,{signal:l.signal,...r})}catch(B){throw new tge(B)}x.then(B=>{l.signal.aborted&&!A&&Promise.resolve(B.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([x,m]),A=!0}catch(B){throw new tge(B)}let v=r.mode==="no-cors",S=n.type==="successful-write"?300:400;if(!v&&(g.status<200||g.status>=S))throw new nG(g,a,d,l);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(B){throw l.signal.aborted?new tge(B):B}}finally{clearTimeout(f),l.signal.aborted&&g&&I()}},{...c,retryCheck:l=>{let p=c.retryCheck(l);return p&&u<=c.retryCount&&l instanceof nG&&l.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:T1e((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(s=>this.getRouteQueue(s).length>0);){let o=this._dequeuedMessagesCount;if(await this.flush(),r)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(i){if(!Idh(i))throw i;await Oul(i)}})(),t,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:t}),r=!0})}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 Tdh=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var nrC=new RegExp(Tdh.source,"i"),Ful=/[a-z][a-z0-9+.-]{0,63}:\/\//i,irC=new RegExp(`^${Ful.source}`,"i"),orC=new RegExp(Ful.source,"gi");var Odh=["is_not","is_set"],Pdh=1152921504606847e3,sl=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function x$o(e){if(typeof e=="boolean")return!0;if(typeof e=="string"){let t=e.toLowerCase();return t==="true"||t==="false"}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!x$o(t in e?e[t]:null))return!1;return!0}function S$o(e){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true";if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!S$o(t in e?e[t]:null))return!1;return!0}function zKt(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new sl("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new sl("Cannot stringify an unpaired surrogate like the flags service")}}function Oon(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void zKt(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new sl(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new sl("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&Oon(e[r],t)}finally{t.delete(e)}return}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new sl("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new sl("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))zKt(n),Oon(e[n],t)}finally{t.delete(e)}return}throw new sl(`Cannot represent ${typeof e} like the flags service`)}}function Bdh(e,t){let r=0,n=0;for(;r<e.length&&n<t.length;){let i=e.charCodeAt(r),o=t.charCodeAt(n),s=i>=55296&&i<=56319,a=o>=55296&&o<=56319,c=s?e.charCodeAt(r+1):0,u=a?t.charCodeAt(n+1):0,l=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+u-56320+65536:o;if(l!==p)return l-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function w$o(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return zKt(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new sl(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new sl(`Cannot distinguish integer ${e} from an integral JSON float during local evaluation`);return String(e)}if(Array.isArray(e)){if(t.has(e))throw new sl("Cannot stringify a circular array during local evaluation");t.add(e);try{let r=[];for(let n=0;n<e.length;n++)r.push(n in e?w$o(e[n],t):"null");return`[${r.join(",")}]`}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new sl("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new sl("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(zKt),`{${n.sort(Bdh).map(i=>`${JSON.stringify(i)}:${w$o(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new sl(`Cannot stringify ${typeof e} like the flags service`)}function Ton(e){return typeof e=="string"?(zKt(e),e):w$o(e)}function Nul(e){try{return new RegExp(e),!0}catch{return!1}}function iG(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function zul(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new sl(`Invalid semver: ${t}`);return parseInt(e,10)}function n1(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new sl(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:zul(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function oG(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function Rdh(e,t){let r=n1(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function Ddh(e,t){let[r,n,i]=n1(e,t),o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function kdh(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new sl(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let u=parseInt(c,10);if(!isNaN(u))return u}else try{return zul(c,e,t)}catch{}throw new sl(`Invalid wildcard semver: ${e}`)},s=o(i[0]);if(i.length===1)return{lower:[s,0,0],upper:[s+1,0,0]};let a=o(i[1]);return{lower:[s,a,0],upper:[s,a+1,0]}}function jul(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 sl(`${e} is in an invalid date format`)}throw new sl(`The date provided ${e} must be a string, number, or date object`)}function T$o(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r||!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}function O$o(e,t,r={}){let n=e.key,i=e.value,o=e.operator||"exact",s=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,n)){if(o==="is_not_set")return!1;if(o==="is_set")return!0}else throw new sl(`Property ${n} not found in propertyValues`);let c=t[n];if(c===void 0)return r.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${o} operator`),o==="is_not";if(c===null&&!Odh.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let u=(p,d)=>{if(r.propertyMatchingVersion!==2&&x$o(p)||Array.isArray(p)&&p.length===0)return Oon(d),S$o(p)===S$o(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&x$o(p))return Oon(d),!1;if(Array.isArray(p)){let f=Ton(d).toLowerCase();return p.some(m=>Ton(m).toLowerCase()===f)}return Ton(p).toLowerCase()===Ton(d).toLowerCase()},l=(p,d,f)=>{if(f==="gt")return p>d;if(f==="gte")return p>=d;if(f==="lt")return p<d;if(f==="lte")return p<=d;throw new Error(`Invalid operator: ${f}`)};switch(o){case"exact":return u(i,c);case"is_not":return!u(i,c);case"is_set":return!0;case"icontains":return iG(c).includes(iG(i));case"not_icontains":return!iG(c).includes(iG(i));case"starts_with":return iG(c).startsWith(iG(i));case"not_starts_with":return!iG(c).startsWith(iG(i));case"ends_with":return iG(c).endsWith(iG(i));case"not_ends_with":return!iG(c).endsWith(iG(i));case"regex":return Nul(String(i))&&String(c).match(String(i))!==null;case"not_regex":return Nul(String(i))&&String(c).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let p=typeof i=="number"?i:parseFloat(String(i)),d=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(p)&&Number.isFinite(d)?l(d,p,o):l(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new sl("Date operations cannot be performed on boolean values");let p=T$o(String(i));p==null&&(p=jul(i));let d=jul(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return oG(n1(String(c),s),n1(String(i),s))===0;case"semver_neq":return oG(n1(String(c),s),n1(String(i),s))!==0;case"semver_gt":return oG(n1(String(c),s),n1(String(i),s))>0;case"semver_gte":return oG(n1(String(c),s),n1(String(i),s))>=0;case"semver_lt":return oG(n1(String(c),s),n1(String(i),s))<0;case"semver_lte":return oG(n1(String(c),s),n1(String(i),s))<=0;case"semver_tilde":{let p=n1(String(c),s),{lower:d,upper:f}=Rdh(String(i),s);return oG(p,d)>=0&&oG(p,f)<0}case"semver_caret":{let p=n1(String(c),s),{lower:d,upper:f}=Ddh(String(i),s);return oG(p,d)>=0&&oG(p,f)<0}case"semver_wildcard":{let p=n1(String(c),s),{lower:d,upper:f}=kdh(String(i),s);return oG(p,d)>=0&&oG(p,f)<0}default:throw new sl(`Unknown operator: ${o}`)}}async function Qul(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function QKt(e,t,r="",n="."){let i=await Qul(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/Pdh}async function P$o(e,t){if(e==null||e.id==null||e.exclusion_percentage==null)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let n=Math.min(Math.max(r,0),100);if(!(n!==100&&await QKt("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function Pon(e){let t=[],r=0;for(let n of e){let i=r+n.rollout_percentage/100;t.push({valueMin:r,valueMax:i,key:n.key}),r=i}return t}async function B$o(e,t,r){let n=await QKt(e,t,"variant");return Pon(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function R$o(e,t){if(t===!1||t==null||!e)return null;let r=typeof t=="boolean"?t.toString():t,n=e[r]||null;return n==null?null:Yft(n)}var Mul=9223372036854776e3,Fdh="9223372036854775808",Ndh=Object.prototype.propertyIsEnumerable;function jdh(){return{ancestors:new WeakSet,remainingNodes:1e4}}function wne(e,t){try{return Lul(e,t,jdh(),0)}catch{return[]}}function zdh(e,t){let r=e.toString(),n=BigInt(Fdh);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function F$o(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:yon};if(r.remainingNodes--,zcl(e))return{boolValue:e};if(typeof e=="bigint")return zdh(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("u"<typeof BigInt)return{stringValue:String(e)};let i=BigInt(e).toString();return e>=Mul||e<-Mul?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:xne(e)};if(typeof e=="function")return{stringValue:oul};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:Aon};if(n>=20)return{stringValue:yon};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?xne(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return F$o(i.call(e),t,r,n+1)}catch{}return X4(e)?{arrayValue:{values:Qdh(e,t,r,n+1)}}:{kvlistValue:{values:Lul(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:xne(String(e))}}function Qdh(e,t,r,n){let i=[],o=Math.min(e.length,1e3),s=0;for(;s<o&&r.remainingNodes>0;s++)try{let a=s in e?e[s]:void 0;if(XJ(a))continue;i.push(F$o(a,t,r,n))}catch{i.push({stringValue:rG})}return e.length>s&&i.push({stringValue:yon}),i}function Lul(e,t,r,n){let i=[];for(let o in e)if(Ndh.call(e,o)){if(!o){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let s=e[o];if($Zo(s)||$he(s))continue;i.push({key:xne(o),value:F$o(s,t,r,n)})}catch{i.push({key:xne(o),value:{stringValue:rG}})}}return i}function LKt(e,t,r){return{...ege({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}var Mdh=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function _Kt(e,t){let r=ege({},e),n={};for(let i of Mdh)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...wne(r,t),...wne(n,t)]}var _ul={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function Ldh(e){if(e)return Object.prototype.hasOwnProperty.call(_ul,e)?_ul[e]:e}function N$o(e,t){let r=Ldh(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var _dh={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},IrC=_dh.info;var Q5e=class{constructor(t){this._onFire=t,this._firesAt=0}get pending(){return!!this._timer}arm(t){this.clear(),this._firesAt=Date.now()+t,this._timer=UN(()=>{this._timer=void 0,this._onFire()},t)}armNoEarlierThan(t){this._timer&&Date.now()+t<=this._firesAt||this.arm(t)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function UKt(){return 1-.25+Math.random()*.25*2}var sG=1;function VKt(e,t,r,n){let i=Math.min(Math.max(0,t-1),6),o=e*2**i,s=n===void 0?o:Math.min(o,Math.max(n,e));return Math.round(s*r)}var GKt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function j$o(e){return String(e)+"000000"}function z$o(e,t,r,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${e}\0${t}\0${r??""}\0${i}`}function Uul(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function Q$o(e,t,r){return LKt(e,t,r)}function M$o(e,t,r,n){return{resourceMetrics:[{resource:{attributes:_Kt(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function Ron(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}}var Vul=1,qKt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new Q5e(()=>this.flush().catch(i=>{this._logger.error("Metrics flush failed:",i)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new j5e,this._consecutiveFlushFailures=0,this._flushJitter=sG,this._generation=0}count(t,r=1,n){this._capture({name:t,type:"count",value:r,unit:n?.unit,attributes:n?.attributes})}gauge(t,r,n){this._capture({name:t,type:"gauge",value:r,unit:n?.unit,attributes:n?.attributes})}histogram(t,r,n){this._capture({name:t,type:"histogram",value:r,unit:n?.unit,attributes:n?.attributes})}flush(){let t=this._flushPromise,n=(async()=>{t&&await t.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let t=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(t)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=sG,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(t){if(this._instance.isDisabled||this._instance.optedOut)return;let r=this._runBeforeSend(t);if(r===null)return;if(!r.name||typeof r.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof r.value!="number"||!Number.isFinite(r.value))return void this._logger.warn(`Dropping metric '${r.name}': value must be a finite number`);if(r.type==="count"&&r.value<0)return void this._logger.warn(`Dropping count '${r.name}': counters are monotonic, value must be >= 0`);let n,i;try{n=r.attributes?{...r.attributes}:void 0,i=z$o(r.type,r.name,r.unit,n)}catch(a){this._logger.warn(`Dropping metric '${r.name}': attributes could not be serialized`,a);return}let o=this._series.get(i);if(!o){if(!this._admitNewSeries())return;o={name:r.name,type:r.type,unit:r.unit,attributes:n,windowStartMs:Date.now()},this._series.set(i,o)}let s=this._typeByName.get(r.name);s===void 0?this._typeByName.set(r.name,r.type):s!==r.type&&!this._typeCollisionWarned.has(r.name)&&(this._typeCollisionWarned.add(r.name),this._logger.warn(`Metric name '${r.name}' is already used as a ${s}; recording it as a ${r.type} too will blend both series in charts. Use a distinct name.`)),this._fold(o,r.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(t,r){switch(t.type){case"count":t.total=(t.total??0)+r;break;case"gauge":t.last=r;break;case"histogram":{t.hist||(t.hist={count:0,sum:0,min:r,max:r,bucketCounts:new Array(GKt.length+1).fill(0)});let n=t.hist;n.count+=1,n.sum+=r,n.min=Math.min(n.min,r),n.max=Math.max(n.max,r),n.bucketCounts[Uul(r,GKt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=X4(r)?r:[r],i=t;for(let o of n)try{let s=o(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(VKt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let t=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let r=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(t));if(r===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=UKt()):(this._consecutiveFlushFailures=0,this._flushJitter=sG),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(t),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(t){return M$o(this._buildMetrics(t),Q$o(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=j$o(Date.now()),n=new Map;for(let i of t.values()){let o=z$o(i.type,i.name,i.unit,void 0),s=n.get(o);s||(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count"?s.sum={aggregationTemporality:Vul,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:Vul,dataPoints:[]},n.set(o,s));let a=wne(i.attributes??{},this._logger),c=j$o(i.windowStartMs);if(i.type==="count"){let u={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(u)}else if(i.type==="gauge"){let u={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(u)}else if(i.hist){let u={attributes:a,startTimeUnixNano:c,timeUnixNano:r,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:GKt};s.histogram.dataPoints.push(u)}}return Array.from(n.values())}_mergeWindowBack(t){for(let[r,n]of t){let i=this._series.get(r);if(!i){this._admitNewSeries()&&this._series.set(r,n);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,n.windowStartMs),i.type){case"count":i.total=(i.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(i.hist){i.hist.count+=n.hist.count,i.hist.sum+=n.hist.sum,i.hist.min=Math.min(i.hist.min,n.hist.min),i.hist.max=Math.max(i.hist.max,n.hist.max);for(let o=0;o<i.hist.bucketCounts.length;o++)i.hist.bucketCounts[o]+=n.hist.bucketCounts[o]}else i.hist=n.hist;break}}}};var qdh="0".repeat(32),Wdh="0".repeat(16),Hdh=/^[0-9a-f]+$/;function Kdh(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(t),t}catch{}for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());return t}function Jdh(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function Gul(e){let t=Jdh(Kdh(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function qul(){return Gul(16)}function Wul(){return Gul(8)}function Hul(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&Hdh.test(e)}function Kul(e){return Hul(e,32,qdh)}function Jul(e){return Hul(e,16,Wdh)}var Ydh=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Yul(e){let t=Xul(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:Xdh(t.flags)}}function Xdh(e){return 1&parseInt(e,16)?kon:Zdh}function Xul(e){if(typeof e!="string")return;let t=Ydh.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!Kul(n)||!Jul(i)))return{version:r,traceId:n,spanId:i,flags:o}}function Zul(e){return Xul(e)&&e.trim()}function Don(e){return Array.isArray(e)&&e.length===1?e[0]:e}var kon="01",Zdh="00";function $ul(e,t,r=kon){return`00-${e}-${t}-${r}`}var $dh=32,L$o=512;function Fon(e){if(typeof e!="string")return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>$dh)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=L$o?t:tmh(r)}}var emh=128;function tmh(e){let t=[...e],r=()=>t.reduce((n,i)=>n+i.length,0)+t.length-1;for(let n=t.length-1;n>=0&&r()>L$o;n--)t[n].length>emh&&t.splice(n,1);for(;t.length&&r()>L$o;)t.pop();return t.length?t.join(","):void 0}var ell="unknown";function M5e(e,t,r,n){return typeof e=="string"&&e.trim()?e.length>r?e.slice(0,r):e:(n?.debug(`${t} must be a non-empty string; using "${ell}"`),ell)}function Zft(e){if(e==null)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if(!(typeof t!="number"||!Number.isFinite(t))&&!(t<0||t>9223372036854))return t}function tll(e,t,r){let n=Zft(e);return n===void 0?(e!==void 0&&r?.debug("Span startTime is out of range or not a valid time; using the current time"),t):(t-n>864e5?r?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>t&&r?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function Non(e,t){return e<t?t:e}function WKt(e,t,r,n){let i=Zft(e);return i===void 0?(e!==void 0&&n?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):i}function zon(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var $ft=class{constructor(t,r,n){this._onEnd=r,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=t.traceId,this._spanId=t.spanId,this._parentSpanId=t.parentSpanId,this._traceState=t.traceState,this._traceFlags=t.traceFlags??kon,this._parentIsRemote=t.parentIsRemote??!1,this._name=t.name,this._kind=t.kind,this._autoKeys=new Set(t.autoAttributeKeys),this._maxAttributes=t.maxAttributes,this._maxEvents=t.maxEvents,this._maxAttributesPerEvent=t.maxAttributesPerEvent,this._maxAttributeValueLength=t.maxAttributeValueLength,this._attributes=Object.create(null);for(let i of Object.keys(t.attributes))this._writeAttribute(i,t.attributes[i]);this._startMono=t.backdated?void 0:zon(),this._startTime=t.clockAnchor&&this._startMono!==void 0?t.clockAnchor.wall+(this._startMono-t.clockAnchor.mono):t.startTime,this._startMono!==void 0&&(this._clockAnchor=t.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let t=zon();if(t!==void 0)return this._startTime+Math.max(0,t-this._startMono)}return Date.now()}_mutable(t){return this._ended?(this._logger?.debug(`Ignoring ${t} on a span that has already ended`),!1):!0}_writeAttribute(t,r){if(XJ(r)){t in this._attributes&&!this._autoKeys.has(t)&&this._userAttributeCount--,delete this._attributes[t];return}if(!this._autoKeys.has(t)&&!(t in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[t]=Mon(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=ege({},t);for(let n of Object.keys(r))this._writeAttribute(n,r[n])}return this}addEvent(t,r,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=r&&oll(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:M5e(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:WKt(n,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(t,r){if(this._mutable("setStatus")){if(t!=="ok"&&t!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(t)}"; expected "ok" or "error"`),this;this._status={code:t,...r&&{message:_$o(r,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(t){if(!this._mutable("recordException"))return this;let{type:r,message:n,stack:i}=U$o(t);return this.addEvent(rmh,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=M5e(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return $ul(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(t){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=this._now(),n=WKt(t,r,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:Non(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},rmh="exception",nmh=4294967295;function imh(e){try{return typeof e=="string"?e:String(e)}catch{return rG}}function L5e(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),nmh)}function omh(e,t){if(!t.length)return Object.keys(e);let r=t.filter(i=>Object.prototype.propertyIsEnumerable.call(e,i)),n=new Set(r);return[...r,...Object.keys(e).filter(i=>!n.has(i))]}function nll(e,t,r,n,i,o,s=[]){let a=0,c=0,u={};for(let f of omh(e.attributes,s)){let m=e.attributes[f];if(!XJ(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(u,f,{value:Mon(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=u,c&&(e.droppedAttributesCount=L5e(e.droppedAttributesCount)+c);let l=0,p=0,d=[];for(let f of e.events){if(l>=n){p++;continue}if(l++,f.attributes){let m=oll(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=L5e(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=L5e(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:_$o(imh(e.status.message),o)})}var Qon=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},ill=new Qon,HKt=class extends Qon{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function smh(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function O1e(e,t){let r=Don(e?.parent)??t,n=typeof r=="string"||r==null?r:rll(r,"traceparent"),i=Zul(n);if(!i)return ill;let o=typeof r=="string"||r==null?e?.tracestate:rll(r,"tracestate");return new HKt(i,Fon(o))}function rll(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function _$o(e,t){return e.length>t?e.slice(0,t):e}function Mon(e,t){return jon(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function jon(e,t,r,n){if(e===null||typeof e!="object")return XJ(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?_$o(e,t):e);if(r.ancestors.has(e))return Aon;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=amh(e);if(i.selfDescribed)return XJ(i.value)?String(i.value):jon(i.value,t,r,n+1);if(X4(e)){let a=Math.min(e.length,1e3),c=[];for(let u=0;u<a;u++)try{c.push(jon(e[u],t,r,n+1))}catch{c.push(rG)}return e.length>a&&(c.length=e.length),c}let o={},s=0;for(let a of Object.keys(e)){if(s>=1e3)break;let c;try{c=jon(e[a],t,r,n+1)}catch{c=rG}a&&!XJ(c)&&s++,Object.defineProperty(o,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return o}catch{return e}finally{r.ancestors.delete(e)}}function amh(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function oll(e,t,r){let n;try{n=Object.keys(e)}catch{return{attributes:{},dropped:0}}let i={},o=0,s=0;for(let a of n){if(o>=t){s++;continue}let c;try{c=Mon(e[a],r)}catch{c=rG}XJ(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function sll(e,t){for(let r of Object.keys(e))e[r]=Mon(e[r],t);return e}function KKt(e,t,r){return t===ill?r(t):e.with(t,()=>r(t))}function U$o(e){try{let t=smh(e);if(w1e(e))return{type:e.name||"Error",message:e.message||"",...t};if(typeof e=="string")return{type:"string",message:e};if(e&&typeof e=="object"){let r=e;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...t}}return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}var V$o={internal:1,server:2,client:3,producer:4,consumer:5},cmh={ok:1,error:2},umh=1,lmh=256,pmh=512;function fmh(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:umh)|lmh|(e.parentIsRemote?pmh:0)}function Lon(e){if(typeof e=="string")return xne(e);try{return xne(String(e))}catch{return rG}}function dmh(e){return e&&Object.prototype.hasOwnProperty.call(V$o,e)?V$o[e]:V$o.internal}function G$o(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function mmh(e,t){let r={name:Lon(e.name),timeUnixNano:G$o(e.timestamp)};if(e.attributes){let i=wne(e.attributes,t);i.length&&(r.attributes=i)}let n=L5e(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function all(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:Lon(e.name),kind:dmh(e.kind),startTimeUnixNano:G$o(e.startTime),endTimeUnixNano:G$o(e.endTime),flags:fmh(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=Lon(e.traceState));let n=wne(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>mmh(s,t)));let i=L5e(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=L5e(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:cmh[e.status.code],...e.status.message&&{message:Lon(e.status.message)}}),r}function cll(e,t,r){return LKt(e,t,r)}function ull(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:_Kt(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var lll=8;function _on(){return zon()??Date.now()}function q$o(e){try{return e instanceof $ft}catch{return!1}}function pll(e,t){let r=Yul(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:Fon(t),traceFlags:r.flags,isRemote:!0}}function hmh(e){try{return typeof e.traceparent=="function"}catch{return!1}}function gmh(e){return!!e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)&&Array.isArray(e.events)&&e.name!==void 0&&e.kind!==void 0&&e.startTime!==void 0&&e.endTime!==void 0}function Uon(e,t,r){e[t]!==r&&(e[t]=r)}function Amh(e,t){try{let r=Object.getOwnPropertyDescriptors(e);for(let n of["traceId","spanId","parentSpanId","traceState"])r[n]={value:t[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{return e}}var JKt=class{constructor(t,r,n,i,o,s){this._instance=t,this._config=r,this._logger=n,this._getContext=i,this._contextManager=o,this._onSpanQueued=s,this._queue=[],this._flushTimer=new Q5e(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=sG,this._retryAfter=new j5e,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=r.maxExportBatchSize}startSpan(t,r){if(this._instance.isDisabled||this._instance.optedOut)return O1e(r,this._contextManager.active());let n=Don(r?.parent);if(n&&typeof n!="string"&&!q$o(n)){if(hmh(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),O1e(r,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let i=this._resolveParent(n,r);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),O1e(r,this._contextManager.active());let o=Date.now(),s=tll(r?.startTime,o,this._logger),a=Wul();this._liveSpans.set(a,_on());let c=this._autoContextAttributes();return new $ft({traceId:i?.traceId??qul(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:M5e(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:ege({...c},r?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:s,backdated:s!==o,clockAnchor:Zft(r?.startTime)===void 0?i?.clockAnchor:void 0},(u,l)=>this._onSpanEnd(u,l),this._logger)}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this.startSpan(t,i);try{let a=KKt(this._contextManager,s,o);return uul(a)?a.then(c=>(s.end(),c),c=>{throw this._recordCallbackError(s,c),s.end(),c}):(s.end(),a)}catch(a){throw this._recordCallbackError(s,a),s.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let t=this._generation,r=Promise.resolve().then(()=>t===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===r&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=r,r}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=sG,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=pll(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if(q$o(t))return t.childContext();let n=this._contextManager.active();if(q$o(n))return n.childContext();if(n instanceof HKt)return pll(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let t;try{t=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let r={};return t.distinctId&&(r.posthogDistinctId=t.distinctId),t.sessionId&&(r.sessionId=t.sessionId),t.currentUrl&&(r["url.full"]=t.currentUrl),t.screenName&&(r["screen.name"]=t.screenName),t.appState&&(r["app.state"]=t.appState),r}_recordCallbackError(t,r){if(!(t instanceof $ft))return;let{type:n,message:i,stack:o}=U$o(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=_on()-this._config.maxSpanAgeMs,r=0;for(let[n,i]of this._liveSpans){if(i>t)break;this._liveSpans.delete(n),r++}r&&this._recordDrop(r,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(t,r){if(!this._liveSpans.delete(t.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(t,r);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(i){this._logger.debug("Span queue notification failed",i)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(t){let r=t.droppedAttributesCount??0,n=t.droppedEventsCount??0,i=0;for(let o of t.events)i+=o.droppedAttributesCount??0;(r||n||i)&&this._logger.debug(`Span limits discarded data from "${t.name}": ${r} attributes, ${n} events, ${i} event attributes`)}_runBeforeSpanSend(t,r){if(!this._config.beforeSpanSend.length)return t;let n={traceId:t.traceId,spanId:t.spanId,parentSpanId:t.parentSpanId,traceState:t.traceState},i={startTime:t.startTime,endTime:t.endTime},o={attributes:t.droppedAttributesCount,events:t.droppedEventsCount},s=Object.keys(t.attributes),a={traceFlags:t.traceFlags,parentIsRemote:t.parentIsRemote},c=t.status&&{...t.status},u=t,l=t;try{for(let f of this._config.beforeSpanSend){let m=f(u);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;u=this._keepSpanIdentity(m,n)}if(l={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:u.name,kind:u.kind,status:u.status,attributes:u.attributes,events:u.events,startTime:u.startTime,endTime:u.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!gmh(l))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;l.name=M5e(l.name,"Span name",this._config.maxAttributeValueLength,this._logger),l.status&&l.status.code!=="ok"&&l.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),l.status=c),l.startTime=Zft(l.startTime)??i.startTime,l.endTime=Non(Zft(l.endTime)??i.endTime,l.startTime);let d=[];for(let f of l.events)try{d.push({...f,name:M5e(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:WKt(f.timestamp,l.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return l.events=d,nll(l,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),l}catch(p){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",p),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(t,r){(t.traceId!==r.traceId||t.spanId!==r.spanId||t.parentSpanId!==r.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{Uon(t,"traceId",r.traceId),Uon(t,"spanId",r.spanId),Uon(t,"parentSpanId",r.parentSpanId),Uon(t,"traceState",r.traceState)}catch{return Amh(t,r)}return t}_recordDrop(t,r){this._droppedSinceWarning+=t,this._dropReasons.add(r),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(t){let r=[];for(let n of t)try{r.push(all(n,this._logger))}catch(i){this._logger.debug("Failed to encode a span; dropping it",i),this._recordDrop(1,"its attributes could not be encoded")}return r}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let t=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(t,"the user has opted out"),this._warnAboutDrops(),t}async _flushInner(){if(!this._queue.length)return 0;let t=this._discardQueueIfConsentWithdrawn();if(t)return t;let r=sll(cll(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),o=this._queue.length,s=0,a=1/0,c=this._generation;try{for(;o>0&&this._queue.length>0;){let u=this._discardQueueIfConsentWithdrawn();if(u)return s+u;let l=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(l,a,o,this._queue.length)),d=this._queue.slice(0,p),f=this._encodeBatch(d);if(!f.length){this._queue.splice(0,p),o-=p,s+=p,this._resetHeadBatchBudget();continue}let m=_on()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(ull(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=sG,this._resetHeadBatchBudget(),this._queue.splice(0,p),o-=p,s+=p,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(g.kind==="too-large"){if(p===1){this._queue.splice(0,1),o-=1,s+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=sG,this._resetHeadBatchBudget();continue}let A=Math.max(1,Math.floor(p/2));g.measuredLocally?a=A:this._maxExportBatchSize=A,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${A}`);continue}if(g.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=UKt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=_on()+this._nextFlushDelay()),this._headBatchFailures<lll)return this._logger.debug("Span export failed; retrying on the next flush",g.error),s;if(this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=sG,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${lll} times in a row`),this._retryAfter.isOpen())return s;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",g.error),this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=sG,this._resetHeadBatchBudget(),this._recordDrop(p,"the ingestion endpoint rejected the batch")}return s}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(t=>{this._logger.debug("Background span flush failed",t)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(VKt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var YKt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var ymh=5e3,bmh=512,Emh=2048,Imh=128,vmh=128,Cmh=128,xmh=8192,Smh=1e4,wmh=36e5;function P1e(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var fll=["service.name","service.version","deployment.environment"];function Tmh(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(fll.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of fll)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function Omh(e,t){if(!e)return[];let r=[e].flat().filter(i=>!!i),n=r.filter(i=>typeof i=="function");return n.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-n.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function W$o(e,t,r){let n=ege({...t},Tmh(e?.resourceAttributes)),i=P1e(e?.maxExportBatchSize,bmh);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:Omh(e?.beforeSpanSend,r),maxAttributesPerSpan:P1e(e?.maxAttributesPerSpan,Imh),maxEventsPerSpan:P1e(e?.maxEventsPerSpan,vmh),maxAttributesPerEvent:Cmh,maxAttributeValueLength:P1e(e?.maxAttributeValueLength,xmh),flushIntervalMs:P1e(e?.flushIntervalMs,ymh),maxExportBatchSize:i,maxQueueSize:Math.max(P1e(e?.maxQueueSize,Emh),i),maxLiveSpans:P1e(e?.maxLiveSpans,Smh),maxSpanAgeMs:P1e(e?.maxSpanAgeMs,wmh)}}var H$o=require("fs"),hll=require("fs/promises"),J$o=require("path"),gll=require("readline"),Von=new lO.ReduceableCache(25),XKt=new lO.ReduceableCache(20),Y$o=7,Pmh=1e3,Bmh=1e4,K$o=10485760;async function All(e,t=hll.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],u=c?.filename;if(!c||typeof u!="string"||typeof c.lineno!="number"||Nmh(u)||jmh(c)||!(0,J$o.isAbsolute)(u)&&i===void 0)continue;n[u]||(n[u]=[]),n[u].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=yll(a,i);if(c===void 0||XKt.get(c))continue;let u=n[a];if(!u)continue;u.sort((d,f)=>d-f);let l=Qmh(u);if(l.every(d=>zmh(c,d)))continue;let p=Mmh(Von,c,{});s.push(Dmh(a,l,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&kmh(e,Von,i),Von.reduce(),e}async function Rmh(e,t,r){let n,i=!1;try{n=await t(e,H$o.constants.O_RDONLY|H$o.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>K$o?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${K$o}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function Dmh(e,t,r,n,i,o){let s=await Rmh(e,i,o);if(s===void 0)return void XKt.set(n,1);let a=s;return new Promise(c=>{let u=!1;function l(x){u||(u=!0,x?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:K$o-1})}catch{XKt.set(n,1),l();return}let d;try{d=(0,gll.createInterface)({input:p})}catch{XKt.set(n,1),l(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void l(p);let A=g[0],y=g[1];function I(){XKt.set(n,1),d.close(),d.removeAllListeners(),l(p)}p.on("error",I),d.on("error",I),d.on("close",()=>l(p)),d.on("line",x=>{if(f++,!(f<A)&&(r[f]=Lmh(x,0),f>=y)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let v=t[m];if(v===void 0){d.close(),d.removeAllListeners();return}A=v[0],y=v[1]}})})}function kmh(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=yll(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;Fmh(n.lineno,n,o)}}function Fmh(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=bll(e);i<e;i++){let o=r[i];if(o===void 0)return void dll(t);t.pre_context.push(o)}if(r[e]===void 0)return void dll(t);t.context_line=r[e];let n=Ell(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 dll(e){delete e.pre_context,delete e.context_line,delete e.post_context}function Nmh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function jmh(e){return e.lineno!==void 0&&e.lineno>Bmh||e.colno!==void 0&&e.colno>Pmh}function yll(e,t){return(0,J$o.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function zmh(e,t){let r=Von.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 Qmh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=mll(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+Y$o:(i.push(n),n=mll(o)),t++}return i}function mll(e){return[bll(e),Ell(e)]}function bll(e){return Math.max(1,e-Y$o)}function Ell(e){return e+Y$o}function Mmh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function Lmh(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}var edt=require("path");function Ill(e=process.cwd()){let t=edt.sep==="\\",r=i=>t?i.replace(/\\/g,"/"):i,n=r(e);return async i=>{for(let o of i)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,edt.isAbsolute)(o.filename)&&(o.filename=r((0,edt.relative)(n,r(o.filename))));return i}}var vll="5.55.0";var rge={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var B1e=class e{constructor(t){this._host=t.host,this._distinctId=t.distinctId,this._groups=t.groups,this._disableGeoip=t.disableGeoip,this._flags=t.flags,this._requestId=t.requestId,this._evaluatedAt=t.evaluatedAt,this._flagDefinitionsLoadedAt=t.flagDefinitionsLoadedAt,this._errorsWhileComputing=t.errorsWhileComputing??!1,this._quotaLimited=t.quotaLimited??!1,this._accessed=t.accessed??new Set,this._isSlice=t.isSlice??!1}isEnabled(t,r={}){let n=this._flags[t];return this._recordAccess(t),n?.enabled??r.defaultValue??!1}getFlag(t){let r=this._flags[t];if(this._recordAccess(t),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(t){return this._flags[t]?.payload}onlyAccessed(){let t={};for(let r of this._accessed){let n=this._flags[r];n&&(t[r]=n)}return this._cloneWith(t)}only(t){let r={},n=[];for(let i of t){let o=this._flags[i];o?r[i]=o:n.push(i)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let t={},r=[];for(let[n,i]of Object.entries(this._flags)){let o=i.enabled===!1?!1:i.variant??!0;t[`$feature/${n}`]=o,i.enabled&&r.push(n)}return r.length>0&&(r.sort(),t.$active_feature_flags=r),t}_cloneWith(t){return new e({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:t,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(t){if(this._accessed.add(t),this._distinctId===""||this._isSlice&&!(t in this._flags))return;let r=this._flags[t],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,i={$feature_flag:t,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${t}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(rge.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(rge.QUOTA_LIMITED),r===void 0&&o.push(rge.FLAG_MISSING),o.length>0&&(i.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:t,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}};var _mh=6e4;function Cll(e){return e==="client"||e==="server"?e:"all"}function Umh(e,t){return e===t||e==="all"||t==="all"}var tdt=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function Vmh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var Tne=class e extends Error{constructor(t){super(t),Vmh(this,e)}},Gon=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.pollerStopped=!1,this.filteredOutFlagKeys=new Set,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.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}withEvaluationSnapshot(t){return t.definitions?t:{...t,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}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 c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(u){u instanceof Tne||u instanceof sl?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${t}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${u}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a=this.withEvaluationSnapshot({...t,definitions:void 0});return await Promise.all(s.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof Tne||u instanceof sl?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(this.loadedSuccessfullyOnce&&(r=this.withEvaluationSnapshot(r)),o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=this.withEvaluationSnapshot(r),t=r.definitions.featureFlagsByKey[t.key]??t;let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=R$o(t.filters?.payloads,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(!t.active)return!1;if(t.ensure_experience_continuity)throw new sl("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=r.definitions.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new sl("Flag has unknown group type index");if(!(u 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[u];return await this.matchFeatureFlagProperties(t,i[u],l,r)}{let u=this.getBucketingValueForFlag(t,n,o);if(u===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 sl(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,u,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}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!n.definitions.featureFlagsByKey)throw new sl("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new sl(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new sl(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new sl(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=n.definitions.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new sl(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))i[c]=!1;else throw new sl(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new sl(`Dependency '${c}' 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){i=this.withEvaluationSnapshot(i);let o=t.filters||{},s=await P$o(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,u=o.early_exit??!1,{groups:l,groupProperties:p}=i,d=!1,f;for(let m of a)try{let g=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,A=n,y=r;if(g!==c&&g!=null){let x=i.definitions.groupTypeMapping[String(g)];if(!x||!(x in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(x in p)){d=!0;continue}A=p[x],y=l[x]}let I=await this.isConditionMatch(t,y,m,A,i);if(I==="match"){let x=m.variant,v=o.multivariate?.variants||[];f=x&&v.some(S=>S.key===x)?x:await this.getMatchingVariant(t,y)||!0;break}if(u&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof Tne)throw g;if(g instanceof sl)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new sl("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){o=this.withEvaluationSnapshot(o);let s=o.definitions,a=n.rollout_percentage,c=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let l=u.type,p=!1;if(l==="cohort"){let d=await Sll(u,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=u.operator==="not_in"?!d:d}else p=l==="flag"?await this.evaluateFlagDependency(u,i,o):xll(u,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await QKt(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return B$o(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return Pon(t.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(t){if(!this.evaluationContexts||this.evaluationContexts.length===0)return t;let r=new Set(this.evaluationContexts);return t.filter(n=>{let i=n.evaluation_contexts??n.evaluation_tags;return!i||i.length===0?!0:i.some(o=>r.has(o))})}getEvaluationRuntimeForFlag(t){let r=this.featureFlagsByKey[t];return r?Cll(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>Umh(Cll(r.evaluation_runtime),t)).map(r=>r.key)}updateFlagState(t){let r=this.filterFlagsByEvaluationContexts(t.flags);this.featureFlags=r,this.featureFlagsByKey=r.reduce((i,o)=>(i[o.key]=o,i),{});let n=new Set(r.map(i=>i.key));this.filteredOutFlagKeys=new Set(t.flags.filter(i=>!n.has(i.key)).map(i=>i.key)),this.groupTypeMapping=t.group_type_mapping??t.groupTypeMapping??{},this.cohorts=t.cohorts,this.propertyMatchingVersion=t.property_matching_version??t.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((t.minimal_flag_called_events??t.minimalFlagCalledEvents)===!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(this.featureFlags),!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(){let t=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(_mh,t*2**this.backOffCount):t}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);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 tdt(`Your project key or secret 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.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new tdt(`Your secret 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 secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new tdt(`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=n.group_type_mapping||{},o=n.minimal_flag_called_events===!0,s={flags:n.flags??[],group_type_mapping:i,cohorts:n.cohorts||{},minimal_flag_called_events:o,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:o};if(this.updateFlagState(s),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(s)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(t){t instanceof tdt&&this.onError?.(t)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}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}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=UN(()=>{o.abort()},this.timeout),r.signal=o.signal}let i=()=>clearTimeout(n);try{let o=this.fetch,s=await o(t,r);return s.status!==200?(i(),s):{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{i()}},json:async()=>{try{return await s.json()}finally{i()}}}}catch(o){throw i(),o}}async stopPoller(t=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await T1e(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function xll(e,t,r,n){return O$o(e,t,{warnFunction:r,propertyMatchingVersion:n})}function Gmh(e,t){if(!(e in t))throw new Tne(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Sll(e,t,r,n=!1,i,o){let s=String(e.value);Gmh(s,r);let a=r[s];return wll(a,t,r,n,i,o)}async function wll(e,t,r,n=!1,i,o){if(!e)return!0;let s=e.type,a=e.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let u of a)try{let l=await wll(u,t,r,n,i,o);if(s==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof Tne)throw l;if(l instanceof sl)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new sl("Can't match cohort without a given cohort property value");return s==="AND"}for(let u of a)try{let l;if(u.type==="cohort")l=await Sll(u,t,r,n,i,o);else if(u.type==="flag"){if(!i)throw new sl(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await i(u)}else l=xll(u,t,void 0,o);let p=u.negation||!1;if(s==="AND"){if(!l&&!p||l&&p)return!1}else if(l&&!p||!l&&p)return!0}catch(l){if(l instanceof Tne)throw l;if(l instanceof sl)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new sl("can't match cohort without a given cohort property value");return s==="AND"}var qmh=["--unhandled-rejections","--unhandled_rejections"],Wmh=new Set(["throw","strict","warn","warn-with-error-code","none"]),Hmh=[...globalThis.process?.execArgv??[]],Kmh=globalThis.process?.env?.NODE_OPTIONS;function Jmh(e){let t=[],r="",n=!1;for(let i=0;i<e.length;i++){let o=e[i];o==="\\"&&n&&i+1<e.length?r+=e[++i]:o!==" "||n?o==='"'?n=!n:r+=o:r&&(t.push(r),r="")}return r&&t.push(r),t}function Tll(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=qmh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);Wmh.has(o)&&(t=o)}return t}function Ymh(e=Hmh,t=Kmh){return Tll(e)??Tll(Jmh(t??""))??"throw"}var Oll=Ymh();function Pll(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function Xmh(e,t){let r=!1;return Object.assign((n,i)=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length;Pll(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function Bll(e,t,r=Oll){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>Pll(e,i,o));n.on("uncaughtException",Xmh(e,t))}}function Rll(e,t=Oll){let r=globalThis.process;!r||t==="throw"||t==="strict"||t==="warn-with-error-code"||r.on("unhandledRejection",n=>{e(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var Zmh=2e3,X$o=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new uon({...Ucl(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return vKt(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i,o){let s={...o},a=t.buildFromUnknown(r,n);a.$exception_list=await t.modifyFrames(a.$exception_list);let c=lO.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(Bll(this.onException.bind(this),this.onFatalError.bind(this)),Rll(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(this.client.getErrorPropertiesBuilder(),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._capturePreparedEvent(n,!1)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(Zmh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},_5e=X$o;var qon=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function $mh(e){return e==="v0"||e==="v1"}function Dll(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return $mh(e)?e:"v0"}var ehh="$ai_",ZKt="analytics";function kll(e){return typeof e.event=="string"&&e.event.startsWith(ehh)}var rdt=class e extends Error{constructor({requestId:t,drops:r,retryExhausted:n,cause:i}){super(e.buildMessage(t,r,n,i)),this.name="CaptureV1Error",this.requestId=t,this.drops=r,this.retryExhausted=n,this.cause=i}static buildMessage(t,r,n,i){let o=`Capture V1 batch ${t} did not fully deliver: ${r.length} dropped, ${n.length} undelivered`;return i instanceof Error&&(o+=` (${i.message})`),o}};function Z$o(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function thh(e){return typeof e=="string"?e:void 0}var rhh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Z$o},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Z$o},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Z$o},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:thh}],nhh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function ihh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ohh(e){if(typeof e=="string"){let r=new Date(e);if(Number.isNaN(r.getTime()))return new Date().toISOString();let n=r.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function Fll(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function shh(e){let r={...ihh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of rhh)if(o in r){let c=a(r[o]);c!==void 0&&(n[s]=c),delete r[o]}let i={};for(let{property:o,field:s}of nhh)if(o in r){let a=r[o];typeof a=="string"&&(i[s]=a),delete r[o]}return delete r.$lib,delete r.$lib_version,Fll(r,"$set",e.$set),Fll(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:ohh(e.timestamp),...i,options:n,properties:r}}function Nll(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(shh)};return r&&(n.historical_migration=!0),n}var ahh="/i/v1/analytics/events",chh=3e4,uhh=new Set([408,500,502,503,504]),Won=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??chh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>UN(i,n))),this.generateRequestId=r.generateRequestId??_N,this.compress=r.compress??NKt}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=Nll(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${ahh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let u=1;u<=c;u++){let l=u===c,p=S1e({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,u,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!l&&uhh.has(A)){let y=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(u,y)}else{let y=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,y)}else{let y;try{y=await d.waitFor(this.parseResponse(m))}catch(v){if(g.aborted)throw v;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,y,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(l)return void this.onError(new rdt({requestId:r,drops:s,retryExhausted:I.map(v=>v.uuid)}));a=I;let x=this.parseRetryAfter(m);f=this.backoffDelay(u,x)}}catch(m){if(d&&!d.signal.aborted)throw m;if(l)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(u)}finally{d?.cleanup()}f!==void 0&&await this.sleep(f)}}async sendOnce(t,r,n,i){let o=this.buildHeaders(n,i),s=r;if(this.config.compressionEnabled){let p=await this.compress(r,this.config.isDebug);p!==null&&(s=p,o["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",u,l=new Promise((p,d)=>{u=UN(()=>{let f=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);f.name="AbortError",d(f),a.abort(f)},this.config.requestTimeoutMs)});try{let p=this.fetchFn(t,{method:"POST",headers:o,body:s,signal:a.signal}),d=!1;p.then(y=>{a.signal.aborted&&!d&&this.cancelBody(y)}).catch(()=>{});let f=await Promise.race([p,l]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:y=>Promise.race([y,l]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(u),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(u),p}}buildHeaders(t,r){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(t),"PostHog-Request-Id":r,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(t,r,n){let i=r.results??{},o=[];for(let s of t){let a=i[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&o.push(s))}return o}backoffDelay(t,r){let n=Math.min(this.config.initialRetryDelayMs*2**(t-1),this.maxBackoffMs);return r===void 0?n:Math.max(n,Math.min(r,this.maxBackoffMs))}parseRetryAfter(t){let r=t.headers?.get("Retry-After");if(!r)return;let n=r.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let i=Date.parse(n);if(Number.isNaN(i))return;let o=i-this.now();return o>0?o:void 0}async parseResponse(t){let r=await t.text(),n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let i=n.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error("unexpected results shape");return{results:i??{}}}async buildHttpError(t,r,n){let i="";try{i=(await n(t.text())).slice(0,512)}catch{}let o=i?`: ${i}`:"";return new Error(`Capture V1 request failed with HTTP ${r}${o}`)}surfaceBatchFailure(t,r,n,i){this.onError(new rdt({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new rdt({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var U5e="ai-capture",Hon="/i/v0/ai/batch/";var phh=new TextEncoder;function ees(e){return phh.encode(S1e(e)).length}function jll(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=ees(a);if(c>t){i.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}o.length>0&&s+c>r&&(n.push(o),o=[],s=0),o.push(a),s+=c}return o.length>0&&n.push(o),{batches:n,dropped:i}}var fhh=100,zll=3e4,dhh=5e4,mhh=50,hhh=500,ghh="https://us.i.posthog.com",Qll=new Set;function Jon(e,t){Qll.has(e)||(Qll.add(e),console.warn(`[PostHog] ${t}`))}function Ahh(e){return typeof e=="string"?e.trim():""}function yhh(e){return(typeof e=="string"?e.trim():"")||void 0}function bhh(e){return(typeof e=="string"?e.trim():"")||ghh}function Ehh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function Ihh(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))t[`$feature/${n}`]=i;let r=Object.keys(e).filter(n=>e[n]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}var Yon=class extends jKt{constructor(t,r={}){let n=Ahh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:bhh(r.host),personalApiKey:yhh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new qon,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=Dll(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,fhh):i.featureFlagsPollingInterval===null?null:zll,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.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.');i.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new Gon({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:n,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation,evaluationContexts:i.evaluationContexts??i.evaluationEnvironments}))}this.errorTracking=new _5e(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||dhh}enqueue(t,r,n,i){super.enqueue(t,r,n,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(t=!1){let r=this.flushWithPendingPromises();return!this._traces||t&&this._traces.throttled?r:SKt([r,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(t){let r=this._flushEventsAndSpans(t),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(r.catch(()=>{}))}catch{}return r}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??hhh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??mhh;this._waitUntilCycle.timer=UN(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{t?.()}}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)}getQueueRouteKey(t){return this.captureMode==="v1"&&kll(t)?"ai":ZKt}persistedQueueKeyForRoute(t){return t===U5e?jM.AiCaptureQueue:t==="ai"?jM.AiQueue:jM.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[ZKt,"ai"]:[ZKt];return this._aiCaptureRouteActive&&t.push(U5e),t}getBatchEndpointPath(t){return t===U5e?Hon:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=ZKt){if(n===U5e)return this.sendAiCaptureBatch(t,r);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(t,r,n);let i=t.filter(o=>o!==void 0);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(t,r){let{batches:n,dropped:i}=jll(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${Hon}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let o of n)await this.sendAiSubBatch(o,r)}async sendAiSubBatch(t,r){try{await super.sendBatch(t,r,U5e)}catch(n){if(!Xft(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${ees(o)} bytes) was rejected with 413 by ${Hon} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let i=Math.ceil(t.length/2);await this.sendAiSubBatch(t.slice(0,i),r),await this.sendAiSubBatch(t.slice(i),r)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new Won({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(t,r)=>this.fetch(t,r),onError:t=>this._events.emit("error",t),compress:t=>this.compressPayload(t)})),this._v1Sender}getLibraryVersion(){return vll}get metrics(){return this._metrics||(this._metrics=new qKt(this,Ron(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new YKt}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new JKt(this,W$o(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let t=this.context?.get();return{distinctId:t?.distinctId,sessionId:t?.sessionId}}startSpan(t,r){return this._tracesPipeline?.startSpan(t,r)??O1e(r,this._spanContextManager.active())}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this._tracesPipeline;return s?i?s.withSpan(t,i,o):s.withSpan(t,o):KKt(this._spanContextManager,O1e(i,this._spanContextManager.active()),o)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let t=super.getCommonEventProperties();return(this.options.isServer??!0)&&(t.$is_server=!0),t}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}_warnIfInvalidCapture(t,r,n){typeof t=="string"&&this._logger.warn(r),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(t,r,n,i,o){return this.addPendingPromise(this._prepareEventMessage(r,i).then(({distinctId:s,event:a,properties:c,options:u})=>{let l={timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,l,o):this.enqueue(t,p,l,o)}).catch(s=>{s&&console.error(s)}))}_capturePreparedEvent(t,r){return this._sendPreparedEvent("capture",t,r)}capture(t){this._warnIfInvalidCapture(t,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(t,!1)}async captureImmediate(t){return this._warnIfInvalidCapture(t,"Called captureImmediate() with a string as the first argument when an object was expected.","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._capturePreparedEvent(t,!0)}captureAi(t){if(this.disabled)return;let r=z5e(t.uuid,_N);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=z5e(t.uuid,_N);return await this._sendPreparedAiEvent({...t,uuid:r},!0),r}_sendPreparedAiEvent(t,r){return typeof t?.event=="string"&&!t.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${t.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",t,r,void 0,U5e)}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};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:l,disableGeoip:n},!1,{includeContextProperties:!1})}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};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:l,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:t,properties:r={},propertiesOnce:n={}}){if(Object.keys(r).length===0&&Object.keys(n).length===0)return;let i={};Object.keys(r).length>0&&(i.$set=r),Object.keys(n).length>0&&(i.$set_once=n),this.capture({distinctId:t,event:"$set",properties:i})}unsetPersonProperties({distinctId:t,properties:r}){let n=Ehh(r);n.length!==0&&this.capture({distinctId:t,event:"$set",properties:{$unset:n}})}alias(t){this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(t){await this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(t){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(t)}getFeatureFlagKeysByEvaluationRuntime(t){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(t)??[]}async waitForLocalEvaluationReady(t=zll){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){if(this.disabled)return void this._logger.warn("The client is disabled");let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let R=this._flagOverrides[t];if(R===void 0)return;let D=this._payloadOverrides?.[t];return{key:t,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:D}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,y,I,x,v,S;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let R=this.featureFlagsPoller?.featureFlagsByKey[t];if(R)try{let D=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(R,d,{matchValue:i});if(D){m=!0;let O=D.value;I=R.id,v="Evaluated locally",S=R.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:D.payload??void 0,reason:v,reasonCode:R.active===!1?"flag_disabled":void 0}}}catch(D){if(D instanceof Tne||D instanceof sl)this._logger?.info(`${D.name} when computing flag locally: ${t}: ${D.message}`);else throw D}}if(!m&&!c){let R=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,u,l,a,[t]);if(R===void 0)y=rge.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,g=R.requestId,A=R.evaluatedAt;let D=[];R.errorsWhileComputingFlags&&D.push(rge.ERRORS_WHILE_COMPUTING),R.quotaLimited?.includes("feature_flags")&&D.push(rge.QUOTA_LIMITED);let O=R.flags[t];if(O===void 0)D.push(rge.FLAG_MISSING);else{I=O.metadata?.id,x=O.metadata?.version,v=O.reason?.description??O.reason?.code,S=O.metadata?.has_experiment;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:z,reason:v,reasonCode:O.reason?.code}}D.length>0&&(y=D.join(","))}}if(o){let R=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,D={$feature_flag:t,$feature_flag_response:R,$feature_flag_id:I,$feature_flag_version:x,$feature_flag_reason:v,locally_evaluated:m,[`$feature/${t}`]:R,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(S!==void 0&&(D.$feature_flag_has_experiment=S),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(D.$feature_flag_definitions_loaded_at=O)}y&&(D.$feature_flag_error=y),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:R,groups:s,disableGeoip:a,properties:D})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){Jon("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");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(Jon("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),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.disabled)return void this._logger.warn("The client is disabled");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){Jon("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return i===void 0?void 0:i.enabled===!1?!1:!!(i.variant??!0)||!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:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},g={},A=!0;if(f&&(m=f.response,g=f.payloads,A=f.fallbackToFlags),A&&!c){let y=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,u,l,s,a);m={...m,...y.flags||{}},g={...g,...y.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:g}}async evaluateFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new B1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new B1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new B1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,y=!1,I=!1,x=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),v=new Set;if(x)for(let[R,D]of Object.entries(x.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[R];m[R]={key:R,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:x.payloads[R],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},v.add(R)}let S=f!==void 0&&Array.from(f).some(R=>this.featureFlagsPoller?.featureFlagsByKey[R]===void 0);if((x?x.fallbackToFlags||S:!0)&&!c){let R=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,u,l,s,a);if(R){this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,g=R.requestId,A=R.evaluatedAt,y=!!R.errorsWhileComputingFlags,I=Array.isArray(R.quotaLimited)&&R.quotaLimited.includes("feature_flags");for(let[D,O]of Object.entries(R.flags)){if(v.has(D))continue;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}m[D]={key:D,enabled:O.enabled,variant:O.variant,payload:z,id:O.metadata?.id,version:O.metadata?.version,reason:O.reason?.description??O.reason?.code,locallyEvaluated:!1,hasExperiment:O.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[R,D]of Object.entries(this._flagOverrides)){if(D===void 0){delete m[R];continue}let O=m[R];m[R]={key:R,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:O?.payload,id:O?.id,version:O?.version,reason:O?.reason,locallyEvaluated:O?.locallyEvaluated??!1,hasExperiment:O?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[R,D]of Object.entries(this._payloadOverrides)){let O=m[R];O&&(m[R]={...O,payload:D})}if(f!==void 0)for(let R of Object.keys(m))f.has(R)||delete m[R];return new B1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:y,quotaLimited:I})}_shouldSendMinimalFlagCalledEvent(t,r){return t==="$feature_flag_called"&&this._minimalFlagCalledEvents&&r.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=o&&Object.keys(o).length>0?`_${JSON.stringify(Object.entries(o).sort(([l],[p])=>l<p?-1:l>p?1:0))}`:"",u=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(u)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(u):this.distinctIdHasSentFlagCalls[r]=new Set([u]),this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:t=>this._captureFlagCalledEventIfNeeded(t),logWarning:t=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${t}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){await this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!0,{includeContextProperties:!1})}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){let r=Date.now()+(t??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),this._metrics&&(await T1e(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await T1e(this._traces.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,r-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(t){if(this.disabled||!this.apiKey||!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=UN(()=>{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(Mcl(s)&&r&&o in r){let a={};for(let[c,u]of Object.entries(s))a[String(c)]=String(u);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");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 u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,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={...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}personPropertiesForLocalEvaluation(t,r){return{distinct_id:t,...r||{}}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!_5e.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(_5e.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:s},r,n).then(a=>this._capturePreparedEvent({...a,uuid:i,flags:o},!1)))}}async captureExceptionImmediate(t,r,n,i){if(!_5e.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(_5e.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){return this._prepareEventMessage(t)}async _prepareEventMessage(t,r={}){let{distinctId:n,event:i,properties:o,groups:s,flags:a,sendFeatureFlags:c,timestamp:u,disableGeoip:l,uuid:p}=t,d=this.context?.get(),f=r.includeContextProperties??!0,m=n||d?.distinctId,g=f?{...this.props,...d?.properties||{},...o||{}}:{...o||{}};m||(m=_N(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?kKt(g):g,y=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:u,disableGeoip:l,uuid:p});if(!y)return Promise.reject(null);let I=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){Jon("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let x=typeof c=="object"?c:void 0,v=await this.getFeatureFlagsForEvent(y.distinctId,s,l,x);return Ihh(v)}return{}}).catch(()=>({})).then(x=>{let v=y.groups||s;return{...x,...y.properties||{},...v!==void 0&&Object.keys(v).length>0?{$groups:v}:{}}});return y.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&_cl(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(y.event="$bot_pageview",I.$browser_type="bot"),{distinctId:y.distinctId,event:y.event,properties:I,options:{timestamp:y.timestamp,disableGeoip:y.disableGeoip,uuid:y.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)try{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)}}catch(s){return this._logger.error(`Error in before_send function for event '${t.event}':`,s),null}return i}};var Mll=require("async_hooks"),Xon=class{constructor(){this.storage=new Mll.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 Lll=require("async_hooks"),Zon=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new Lll.AsyncLocalStorage}};var _ll=require("zlib"),Ull=require("util"),vhh=(0,Ull.promisify)(_ll.gzip);async function Vll(e,t=!0){try{let r=await vhh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var $on=require("os");function Gll(){let e,t;try{e=(0,$on.platform)(),t=(0,$on.release)()}catch{}return N$o(e,t)}var qll="posthog-node";function Chh(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 c=s.tags[tes.POSTHOG_ID_TAG];if(c===void 0)return s;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],d=p.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(A=>({...A,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},m=lO.getInjectedReleaseId();return m&&(f.$release_id=m),t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var tes=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=qll,this.name=qll,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Chh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var One=class extends Yon{getLibraryId(){return"posthog-node"}compressPayload(t){return Vll(t,this.isDebug)}initializeContext(){return new Xon}initializeSpanContextManager(){return new Zon}hostResourceAttributes(){return Gll()}createErrorPropertiesBuilder(){return new lO.ErrorPropertiesBuilder([new lO.EventCoercer,new lO.ErrorCoercer,new lO.ObjectCoercer,new lO.StringCoercer,new lO.PrimitiveCoercer],lO.createStackParser("node:javascript",lO.nodeStackLineParser),[Fcl(),t=>All(t,void 0,this._logger),Ill()])}};function Wll(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var esn=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},xhh="feature_flag_evaluated",Shh=3e3,whh=3e3,tsn=class{evaluator;environment;sendFeatureFlagEvents;pending=new Map;resolved=new Map;constructor({environment:t,sendFeatureFlagEvents:r,posthogApiKey:n,evaluator:i}){this.environment=t,this.sendFeatureFlagEvents=r,this.evaluator=i??new One(n??"",{featureFlagsRequestTimeoutMs:Shh,isServer:!1})}isEnabled(t,r){let n=Hll(t,r),i=this.pending.get(n);if(i!=null)return i;let o=this.evaluateAndRemember(t,r,n);return this.pending.set(n,o),o}async evaluateAndRemember(t,r,n){let i=await this.evaluate(t,r);return this.resolved.set(n,i),i}getCachedValue(t,r){return this.resolved.get(Hll(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,whh),t.unref()})])}catch{}finally{clearTimeout(t)}}async flushAfterPendingEvaluations(){await Promise.allSettled(this.pending.values()),await this.evaluator.flush()}async evaluate(t,r){let{org:n}=r,i=Ohh(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,res(n),{personProperties:i,groups:{organization:n},groupProperties:{organization:i},sendFeatureFlagEvents:!1})}catch{return!1}return this.sendFeatureFlagEvents&&this.captureFlagUsage({flag:t,org:n,result:o,properties:i}),Wll(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=Thh(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.183.0"};this.tryCapture({distinctId:res(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:res(r),event:xhh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:Wll(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function Thh(e){if(e!=null)return e.enabled?e.variant??!0:!1}function res(e){return`org:${e}`}function Ohh({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function Hll(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var rsn;function nsn(){return rsn==null&&(rsn=Phh()),rsn}async function nes(){await rsn?.flush()}function Phh(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new esn:new tsn({posthogApiKey:e,environment:YJ(),sendFeatureFlagEvents:oon()})}var isn=class{posthog;constructor({posthogApiKey:t}){this.posthog=new One(t,{isServer:!1})}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.183.0",usingAccessToken:!0,cliReleaseEnvironment:YJ(),...zpe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:YJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var $Kt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};Of();tr();var ndt=require("fs/promises"),Kll=require("os"),Jll=require("path");xVe();var Bhh="id",Rhh=".fern",eJt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new One(r,{isServer:!1}),this.userId=t==null?void 0:K7o(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:"5.183.0",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:YJ(),agent:JHr(),...r!=null?{userEmail:r}:{},...zpe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:YJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}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 ol({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=Xw(),r=Be($t.of((0,Kll.homedir)()),Ae.of(Rhh),Ae.of(Bhh));try{await Vt(r)?this.persistedDistinctId=(await(0,ndt.readFile)(r)).toString():(await(0,ndt.mkdir)((0,Jll.dirname)(r),{recursive:!0}),await(0,ndt.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var ies;async function tJt(){return ies==null&&(ies=await Dhh()),ies}async function Dhh(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!oon())return new $Kt;let t=await mpt();return t!=null?new eJt({token:t,posthogApiKey:e}):await OM()!=null?new isn({posthogApiKey:e}):new eJt({token:void 0,posthogApiKey:e})}catch{return new $Kt}}En();ct();Dt();yM();var rJt=ye(require("process"),1);BZe();var Zll=ye(G4o(),1),$ll=ye(Xll(),1);function pO(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=SH(e),e.length===0))return 0;e=e.replace((0,$ll.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(Zll.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}En();function osn(e){let t=0;for(let r of e.split(`
|
|
3473
|
+
at ${r.filename}:${n}:${i}`}};var idh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,OKt=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(idh);return i&&(r=i[1],n=i[2]),[r,n]}};var Cul=["fatal","error","warning","log","info","debug"];function von(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 PKt=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:this.getStack(t)??r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){if(Wft(t))return t.constructor.name;let r="name"in t?t.name:void 0;return pk(r)&&!ZZo(r)?r:"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=von(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return pk(t)&&!ZZo(t)&&Cul.indexOf(t)>=0}getStack(t){try{return pk(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:pk(t.stack)&&t.stack.length>0?t.stack:void 0}catch{return}}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(w1e(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var g$o=class{match(t){return Wft(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${von(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var BKt=class{match(t){return aon(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var A$o=class{match(t){return N5e(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Wft(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return aon(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var y$o=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 RKt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},odh=new Set([RKt.MESSAGE,RKt.TIMESTAMP]),Con={enabled:!0,max_bytes:32768};function b$o(e){return e?{enabled:e.enabled??Con.enabled,max_bytes:adh(e.max_bytes,Con.max_bytes)}:{...Con}}function sdh(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>odh.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var E$o=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=b$o(t)}setConfig(t){this._config=b$o(t),this._trimToMaxBytes()}add(t){let r=cdh(t);if(!r)return;let n=xul(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(t=>t.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let t=this._entries.shift();t&&(this._totalBytes-=t.bytes)}}};function adh(e,t){if(!qft(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function cdh(e){let t;try{t=S1e(e)}catch{return}try{let r=JSON.parse(t);if(!vKt(r))return;let n=r,i=n[RKt.MESSAGE],o=n[RKt.TIMESTAMP];return!pk(i)||i.trim().length===0||!pk(o)&&!qft(o)?void 0:{step:n,json:t}}catch{return}}function xul(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let n=0;n<t.length;n++)t[n]==="%"?(r+=1,n+=2):r+=1;return r}function udh(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var I$o=e=>{if("flags"in e){let t=Sul(e.flags),r=wul(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,Yft(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,ldh(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function ldh(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 Sul=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,DKt(r)]).filter(([,t])=>t!==void 0)),wul=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?Yft(n):void 0]}))},DKt=e=>e===void 0?void 0:e.variant??e.enabled,Yft=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var Tul=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx"],pdh=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...Tul,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],kKt=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return pdh.forEach(n),t.forEach(n),r};var xon=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 v$o(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var ddh="NativeGzipValidationError",mdh=31,hdh=139,gdh=8,Adh=e=>e.length>=2&&e[0]===mdh&&e[1]===hdh;var FKt,ydh=()=>{if(FKt)return FKt;FKt=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;FKt[e]=t>>>0}return FKt},bdh=e=>{let t=ydh(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},Son=e=>{throw Jft(ddh,`Native gzip produced invalid output: ${e}`)},Edh=async(e,t)=>{e.size<18&&Son("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!Adh(r)||r[2]!==gdh)&&Son("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==bdh(t)&&Son("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&Son("invalid-size")};async function NKt(e,t=!0,r){try{let n=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),o=i.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async u=>{try{await o.abort(u)}catch{}throw u}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await Edh(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var nG=class extends Error{constructor(t,r,n,i){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.responseBodyDeadline=n,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return a$o(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let t=Jft("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=UN(()=>{this._bodyReadTimedOut=!0;let o=Jft("AbortError","Response body read timed out");i(o),this.cancelResponseBody(o)},this.responseBodyDeadline-Date.now())}),r;try{r=Promise.resolve(this.response.text())}catch(n){r=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([r,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(t=>JSON.parse(t))}cancelResponseBody(t){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(t),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},tge=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var Dul=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function Oul(e){if(e instanceof nG){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}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 Idh(e){return typeof e=="object"&&(e instanceof nG||kul(e))}function kul(e){return e instanceof tge}function vdh(e){if(e instanceof nG)return e.status===502||e.status===504;if(!(e instanceof tge))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var Pul=10485760;function Bul(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,sul):new TextEncoder().encode(e).length}catch{return 0}}function Xft(e){return typeof e=="object"&&e instanceof nG&&e.status===413}function won(e){return e instanceof nG?e.status===408||e.status===429||e.status>=500:kul(e)}function Rul(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var C$o="default",jKt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new wKt([new TKt,new PKt,new OKt,new BKt],d$o())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new fon,this._events=new xon,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=qcl("[PostHog]",this.logMsgIfDebug.bind(this)),o&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=aul(i||"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:won},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=r.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=(r.disabled??!1)||o,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,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=!v$o()||(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(jM.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(jM.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(jM.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){let r=t.properties||{},n={...r,...this.getCommonEventProperties()};return Dul(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=kKt(n)),{distinct_id:t.distinct_id,event:t.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}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 groupIdentifyStatelessImmediate(t,r,n,i,o,s){let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});await this.sendImmediate("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,{type:"required",consume:i=>i.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).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=!1){await this._initPromise;let a=s?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,u={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(u.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(u.evaluation_contexts=this.evaluationContexts);let l=this.getEvaluationRuntime();l&&(u.evaluation_runtime=l);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(u)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:vdh},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:I$o(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof nG)return{type:"api_error",statusCode:t.status};if(t instanceof tge){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 c=DKt(a.response);return c===void 0&&(c=!1),{response:c,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 c=a[t];return c===void 0?null:c}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={geoip_disable:o??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let c=await this.getFlags(t,r,n,i,a);if(!c.success)return;let u=c.response;return u.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"),u.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:u?.requestId,quotaLimited:u.quotaLimited}):u}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(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,{type:"required",consume:o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);return this._logger.error(a),this._events.emit("error",new Error(s)),Promise.resolve(void 0)}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(jM.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(jM.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(jM.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return C$o}persistedQueueKeyForRoute(t){return jM.Queue}getActiveQueueRoutes(){return[C$o]}getRouteQueue(t){return this.getPersistedProperty(this.persistedQueueKeyForRoute(t))||[]}enqueue(t,r,n,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let s=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(o)),a=this.getPersistedProperty(s)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:o}),this.setPersistedProperty(s,a),this._events.emit(t,o),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=UN(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,i??this.getQueueRouteKey(o))}catch(s){this._events.emit("error",s)}}}normalizeMessage(t){let{type:r,library:n,library_version:i,...o}=t,s=Rul(o.properties)?o.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),i!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:i}),s&&(o.properties=s),o.uuid=z5e(o.uuid,_N),o}normalizeTimestampForWire(t){let r=t instanceof Date?t:typeof t=="string"?new Date(t):null;if(!r||Number.isNaN(r.getTime()))return t;let n=r.toISOString(),i=typeof t=="string"?t.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}prepareMessage(t,r){let n={...t,timestamp:r?.timestamp?r?.timestamp:c$o(),uuid:z5e(r?.uuid,_N)};return(r?.disableGeoip??this.disableGeoip)&&(Rul(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async t=>{await Oul(t)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(t,r=[]){let n=r.filter(o=>!!o),i=0;for(;;){let o=this.promiseQueue.getPromises([...n,...this.flushPromises],t);if(o.length===0)return;i>0&&this._logger.debug(`flush() re-checking ${o.length} pending promise(s) before flushing`),await Promise.all(o.map(s=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(t){if(this.disabled)return Promise.resolve();if(!t&&this.pendingFlushPromise)return this.pendingFlushPromise;let r=this.flushPromise,n=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(t)return this.waitForPendingPromises(n,[r,i])}).then(()=>SKt([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),SKt([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}compressPayload(t){return NKt(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=C$o){let i={api_key:this.apiKey,batch:t.map(u=>{if(!u)return u;let l=this.normalizeTimestampForWire(u.timestamp);return l===u.timestamp?u:{...u,timestamp:l}}),sent_at:c$o()};this.historicalMigration&&(i.historical_migration=!0);let o=S1e(i),s=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(o),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||o};await this.fetchWithRetry(s,c,{type:"successful-write"},r)}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(i=>this.getRouteQueue(i).length>0))return;let r=[],n;for(let i of t)try{await this._flushRoute(i,r)}catch(o){n===void 0&&(n=o)}if(n!==void 0)throw n;this._events.emit("flush",r)}async _flushRoute(t,r){let n=this.persistedQueueKeyForRoute(t),i=this.getPersistedProperty(n)||[];if(!i.length)return;let o=i.length,s=0;for(;i.length>0&&s<o;){let a=i.slice(0,this.maxBatchSize),c=a.map(p=>p.message===void 0?p.message:this.normalizeMessage(p.message)),u=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(y=>y===m||typeof g=="string"&&g.length>0&&y.message?.uuid===g);return A===-1?!0:(d.splice(A,1),!1)});this.setPersistedProperty(n,f),i=f,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},l={retryCheck:p=>Xft(p)?!1:won(p)};try{await this.sendBatch(c,l,t)}catch(p){if(Xft(p)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw p instanceof tge||await u(),this._events.emit("error",p),p}await u(),r.push(...c),s+=c.length}}async _sendOtlpBatch({path:t,auth:r,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let i;try{i=JSON.stringify(n)}catch(l){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,l)),{kind:"too-large",measuredLocally:!0}}let o=Bul(i);if(o>Pul)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${Pul}`)),{kind:"too-large",measuredLocally:!0};let s=r==="bearer"?`${this.host}/i/v1/${t}`:`${this.host}/i/v1/${t}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(i),c=a||i,u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...r==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(s,u,{type:"successful-write"},{retryCheck:l=>Xft(l)||l instanceof nG&&l.retryAfterMs!==void 0?!1:won(l)}),{kind:"ok"}}catch(l){if(Xft(l))return{kind:"too-large"};if(won(l)){let p=l instanceof nG?l.retryAfterMs:void 0;return{kind:"retry-later",error:l,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:l}}}async _sendLogsBatch(t){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:t})}async _sendMetricsBatch(t){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:t})}async _sendTracesBatch(t){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:t})}async fetchWithRetry(t,r,n,i,o){let s=r.body?r.body:"",a=Bul(s),c={...this._retryOptions,...i},u=0;return await cul(async()=>{u++;let l=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((x,v)=>{f=UN(()=>{let S=Jft("AbortError",`Request timed out after ${p}ms`);v(S),l.abort(S)},p)}),g,A=!1,y,I=()=>y??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let x;try{x=this.fetch(t,{signal:l.signal,...r})}catch(B){throw new tge(B)}x.then(B=>{l.signal.aborted&&!A&&Promise.resolve(B.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([x,m]),A=!0}catch(B){throw new tge(B)}let v=r.mode==="no-cors",S=n.type==="successful-write"?300:400;if(!v&&(g.status<200||g.status>=S))throw new nG(g,a,d,l);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(B){throw l.signal.aborted?new tge(B):B}}finally{clearTimeout(f),l.signal.aborted&&g&&I()}},{...c,retryCheck:l=>{let p=c.retryCheck(l);return p&&u<=c.retryCount&&l instanceof nG&&l.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:T1e((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(s=>this.getRouteQueue(s).length>0);){let o=this._dequeuedMessagesCount;if(await this.flush(),r)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(i){if(!Idh(i))throw i;await Oul(i)}})(),t,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:t}),r=!0})}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 Tdh=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var nrC=new RegExp(Tdh.source,"i"),Ful=/[a-z][a-z0-9+.-]{0,63}:\/\//i,irC=new RegExp(`^${Ful.source}`,"i"),orC=new RegExp(Ful.source,"gi");var Odh=["is_not","is_set"],Pdh=1152921504606847e3,sl=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function x$o(e){if(typeof e=="boolean")return!0;if(typeof e=="string"){let t=e.toLowerCase();return t==="true"||t==="false"}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!x$o(t in e?e[t]:null))return!1;return!0}function S$o(e){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true";if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!S$o(t in e?e[t]:null))return!1;return!0}function zKt(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new sl("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new sl("Cannot stringify an unpaired surrogate like the flags service")}}function Oon(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void zKt(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new sl(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new sl("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&Oon(e[r],t)}finally{t.delete(e)}return}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new sl("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new sl("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))zKt(n),Oon(e[n],t)}finally{t.delete(e)}return}throw new sl(`Cannot represent ${typeof e} like the flags service`)}}function Bdh(e,t){let r=0,n=0;for(;r<e.length&&n<t.length;){let i=e.charCodeAt(r),o=t.charCodeAt(n),s=i>=55296&&i<=56319,a=o>=55296&&o<=56319,c=s?e.charCodeAt(r+1):0,u=a?t.charCodeAt(n+1):0,l=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+u-56320+65536:o;if(l!==p)return l-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function w$o(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return zKt(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new sl(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new sl(`Cannot distinguish integer ${e} from an integral JSON float during local evaluation`);return String(e)}if(Array.isArray(e)){if(t.has(e))throw new sl("Cannot stringify a circular array during local evaluation");t.add(e);try{let r=[];for(let n=0;n<e.length;n++)r.push(n in e?w$o(e[n],t):"null");return`[${r.join(",")}]`}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new sl("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new sl("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(zKt),`{${n.sort(Bdh).map(i=>`${JSON.stringify(i)}:${w$o(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new sl(`Cannot stringify ${typeof e} like the flags service`)}function Ton(e){return typeof e=="string"?(zKt(e),e):w$o(e)}function Nul(e){try{return new RegExp(e),!0}catch{return!1}}function iG(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function zul(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new sl(`Invalid semver: ${t}`);return parseInt(e,10)}function n1(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new sl(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:zul(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function oG(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function Rdh(e,t){let r=n1(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function Ddh(e,t){let[r,n,i]=n1(e,t),o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function kdh(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new sl(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let u=parseInt(c,10);if(!isNaN(u))return u}else try{return zul(c,e,t)}catch{}throw new sl(`Invalid wildcard semver: ${e}`)},s=o(i[0]);if(i.length===1)return{lower:[s,0,0],upper:[s+1,0,0]};let a=o(i[1]);return{lower:[s,a,0],upper:[s,a+1,0]}}function jul(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 sl(`${e} is in an invalid date format`)}throw new sl(`The date provided ${e} must be a string, number, or date object`)}function T$o(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r||!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}function O$o(e,t,r={}){let n=e.key,i=e.value,o=e.operator||"exact",s=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,n)){if(o==="is_not_set")return!1;if(o==="is_set")return!0}else throw new sl(`Property ${n} not found in propertyValues`);let c=t[n];if(c===void 0)return r.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${o} operator`),o==="is_not";if(c===null&&!Odh.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let u=(p,d)=>{if(r.propertyMatchingVersion!==2&&x$o(p)||Array.isArray(p)&&p.length===0)return Oon(d),S$o(p)===S$o(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&x$o(p))return Oon(d),!1;if(Array.isArray(p)){let f=Ton(d).toLowerCase();return p.some(m=>Ton(m).toLowerCase()===f)}return Ton(p).toLowerCase()===Ton(d).toLowerCase()},l=(p,d,f)=>{if(f==="gt")return p>d;if(f==="gte")return p>=d;if(f==="lt")return p<d;if(f==="lte")return p<=d;throw new Error(`Invalid operator: ${f}`)};switch(o){case"exact":return u(i,c);case"is_not":return!u(i,c);case"is_set":return!0;case"icontains":return iG(c).includes(iG(i));case"not_icontains":return!iG(c).includes(iG(i));case"starts_with":return iG(c).startsWith(iG(i));case"not_starts_with":return!iG(c).startsWith(iG(i));case"ends_with":return iG(c).endsWith(iG(i));case"not_ends_with":return!iG(c).endsWith(iG(i));case"regex":return Nul(String(i))&&String(c).match(String(i))!==null;case"not_regex":return Nul(String(i))&&String(c).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let p=typeof i=="number"?i:parseFloat(String(i)),d=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(p)&&Number.isFinite(d)?l(d,p,o):l(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new sl("Date operations cannot be performed on boolean values");let p=T$o(String(i));p==null&&(p=jul(i));let d=jul(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return oG(n1(String(c),s),n1(String(i),s))===0;case"semver_neq":return oG(n1(String(c),s),n1(String(i),s))!==0;case"semver_gt":return oG(n1(String(c),s),n1(String(i),s))>0;case"semver_gte":return oG(n1(String(c),s),n1(String(i),s))>=0;case"semver_lt":return oG(n1(String(c),s),n1(String(i),s))<0;case"semver_lte":return oG(n1(String(c),s),n1(String(i),s))<=0;case"semver_tilde":{let p=n1(String(c),s),{lower:d,upper:f}=Rdh(String(i),s);return oG(p,d)>=0&&oG(p,f)<0}case"semver_caret":{let p=n1(String(c),s),{lower:d,upper:f}=Ddh(String(i),s);return oG(p,d)>=0&&oG(p,f)<0}case"semver_wildcard":{let p=n1(String(c),s),{lower:d,upper:f}=kdh(String(i),s);return oG(p,d)>=0&&oG(p,f)<0}default:throw new sl(`Unknown operator: ${o}`)}}async function Qul(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function QKt(e,t,r="",n="."){let i=await Qul(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/Pdh}async function P$o(e,t){if(e==null||e.id==null||e.exclusion_percentage==null)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let n=Math.min(Math.max(r,0),100);if(!(n!==100&&await QKt("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function Pon(e){let t=[],r=0;for(let n of e){let i=r+n.rollout_percentage/100;t.push({valueMin:r,valueMax:i,key:n.key}),r=i}return t}async function B$o(e,t,r){let n=await QKt(e,t,"variant");return Pon(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function R$o(e,t){if(t===!1||t==null||!e)return null;let r=typeof t=="boolean"?t.toString():t,n=e[r]||null;return n==null?null:Yft(n)}var Mul=9223372036854776e3,Fdh="9223372036854775808",Ndh=Object.prototype.propertyIsEnumerable;function jdh(){return{ancestors:new WeakSet,remainingNodes:1e4}}function wne(e,t){try{return Lul(e,t,jdh(),0)}catch{return[]}}function zdh(e,t){let r=e.toString(),n=BigInt(Fdh);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function F$o(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:yon};if(r.remainingNodes--,zcl(e))return{boolValue:e};if(typeof e=="bigint")return zdh(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("u"<typeof BigInt)return{stringValue:String(e)};let i=BigInt(e).toString();return e>=Mul||e<-Mul?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:xne(e)};if(typeof e=="function")return{stringValue:oul};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:Aon};if(n>=20)return{stringValue:yon};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?xne(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return F$o(i.call(e),t,r,n+1)}catch{}return X4(e)?{arrayValue:{values:Qdh(e,t,r,n+1)}}:{kvlistValue:{values:Lul(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:xne(String(e))}}function Qdh(e,t,r,n){let i=[],o=Math.min(e.length,1e3),s=0;for(;s<o&&r.remainingNodes>0;s++)try{let a=s in e?e[s]:void 0;if(XJ(a))continue;i.push(F$o(a,t,r,n))}catch{i.push({stringValue:rG})}return e.length>s&&i.push({stringValue:yon}),i}function Lul(e,t,r,n){let i=[];for(let o in e)if(Ndh.call(e,o)){if(!o){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let s=e[o];if($Zo(s)||$he(s))continue;i.push({key:xne(o),value:F$o(s,t,r,n)})}catch{i.push({key:xne(o),value:{stringValue:rG}})}}return i}function LKt(e,t,r){return{...ege({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}var Mdh=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function _Kt(e,t){let r=ege({},e),n={};for(let i of Mdh)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...wne(r,t),...wne(n,t)]}var _ul={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function Ldh(e){if(e)return Object.prototype.hasOwnProperty.call(_ul,e)?_ul[e]:e}function N$o(e,t){let r=Ldh(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var _dh={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},IrC=_dh.info;var Q5e=class{constructor(t){this._onFire=t,this._firesAt=0}get pending(){return!!this._timer}arm(t){this.clear(),this._firesAt=Date.now()+t,this._timer=UN(()=>{this._timer=void 0,this._onFire()},t)}armNoEarlierThan(t){this._timer&&Date.now()+t<=this._firesAt||this.arm(t)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function UKt(){return 1-.25+Math.random()*.25*2}var sG=1;function VKt(e,t,r,n){let i=Math.min(Math.max(0,t-1),6),o=e*2**i,s=n===void 0?o:Math.min(o,Math.max(n,e));return Math.round(s*r)}var GKt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function j$o(e){return String(e)+"000000"}function z$o(e,t,r,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${e}\0${t}\0${r??""}\0${i}`}function Uul(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function Q$o(e,t,r){return LKt(e,t,r)}function M$o(e,t,r,n){return{resourceMetrics:[{resource:{attributes:_Kt(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function Ron(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}}var Vul=1,qKt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new Q5e(()=>this.flush().catch(i=>{this._logger.error("Metrics flush failed:",i)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new j5e,this._consecutiveFlushFailures=0,this._flushJitter=sG,this._generation=0}count(t,r=1,n){this._capture({name:t,type:"count",value:r,unit:n?.unit,attributes:n?.attributes})}gauge(t,r,n){this._capture({name:t,type:"gauge",value:r,unit:n?.unit,attributes:n?.attributes})}histogram(t,r,n){this._capture({name:t,type:"histogram",value:r,unit:n?.unit,attributes:n?.attributes})}flush(){let t=this._flushPromise,n=(async()=>{t&&await t.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let t=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(t)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=sG,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(t){if(this._instance.isDisabled||this._instance.optedOut)return;let r=this._runBeforeSend(t);if(r===null)return;if(!r.name||typeof r.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof r.value!="number"||!Number.isFinite(r.value))return void this._logger.warn(`Dropping metric '${r.name}': value must be a finite number`);if(r.type==="count"&&r.value<0)return void this._logger.warn(`Dropping count '${r.name}': counters are monotonic, value must be >= 0`);let n,i;try{n=r.attributes?{...r.attributes}:void 0,i=z$o(r.type,r.name,r.unit,n)}catch(a){this._logger.warn(`Dropping metric '${r.name}': attributes could not be serialized`,a);return}let o=this._series.get(i);if(!o){if(!this._admitNewSeries())return;o={name:r.name,type:r.type,unit:r.unit,attributes:n,windowStartMs:Date.now()},this._series.set(i,o)}let s=this._typeByName.get(r.name);s===void 0?this._typeByName.set(r.name,r.type):s!==r.type&&!this._typeCollisionWarned.has(r.name)&&(this._typeCollisionWarned.add(r.name),this._logger.warn(`Metric name '${r.name}' is already used as a ${s}; recording it as a ${r.type} too will blend both series in charts. Use a distinct name.`)),this._fold(o,r.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(t,r){switch(t.type){case"count":t.total=(t.total??0)+r;break;case"gauge":t.last=r;break;case"histogram":{t.hist||(t.hist={count:0,sum:0,min:r,max:r,bucketCounts:new Array(GKt.length+1).fill(0)});let n=t.hist;n.count+=1,n.sum+=r,n.min=Math.min(n.min,r),n.max=Math.max(n.max,r),n.bucketCounts[Uul(r,GKt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=X4(r)?r:[r],i=t;for(let o of n)try{let s=o(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(VKt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let t=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let r=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(t));if(r===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=UKt()):(this._consecutiveFlushFailures=0,this._flushJitter=sG),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(t),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(t){return M$o(this._buildMetrics(t),Q$o(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=j$o(Date.now()),n=new Map;for(let i of t.values()){let o=z$o(i.type,i.name,i.unit,void 0),s=n.get(o);s||(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count"?s.sum={aggregationTemporality:Vul,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:Vul,dataPoints:[]},n.set(o,s));let a=wne(i.attributes??{},this._logger),c=j$o(i.windowStartMs);if(i.type==="count"){let u={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(u)}else if(i.type==="gauge"){let u={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(u)}else if(i.hist){let u={attributes:a,startTimeUnixNano:c,timeUnixNano:r,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:GKt};s.histogram.dataPoints.push(u)}}return Array.from(n.values())}_mergeWindowBack(t){for(let[r,n]of t){let i=this._series.get(r);if(!i){this._admitNewSeries()&&this._series.set(r,n);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,n.windowStartMs),i.type){case"count":i.total=(i.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(i.hist){i.hist.count+=n.hist.count,i.hist.sum+=n.hist.sum,i.hist.min=Math.min(i.hist.min,n.hist.min),i.hist.max=Math.max(i.hist.max,n.hist.max);for(let o=0;o<i.hist.bucketCounts.length;o++)i.hist.bucketCounts[o]+=n.hist.bucketCounts[o]}else i.hist=n.hist;break}}}};var qdh="0".repeat(32),Wdh="0".repeat(16),Hdh=/^[0-9a-f]+$/;function Kdh(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(t),t}catch{}for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());return t}function Jdh(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function Gul(e){let t=Jdh(Kdh(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function qul(){return Gul(16)}function Wul(){return Gul(8)}function Hul(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&Hdh.test(e)}function Kul(e){return Hul(e,32,qdh)}function Jul(e){return Hul(e,16,Wdh)}var Ydh=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Yul(e){let t=Xul(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:Xdh(t.flags)}}function Xdh(e){return 1&parseInt(e,16)?kon:Zdh}function Xul(e){if(typeof e!="string")return;let t=Ydh.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!Kul(n)||!Jul(i)))return{version:r,traceId:n,spanId:i,flags:o}}function Zul(e){return Xul(e)&&e.trim()}function Don(e){return Array.isArray(e)&&e.length===1?e[0]:e}var kon="01",Zdh="00";function $ul(e,t,r=kon){return`00-${e}-${t}-${r}`}var $dh=32,L$o=512;function Fon(e){if(typeof e!="string")return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>$dh)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=L$o?t:tmh(r)}}var emh=128;function tmh(e){let t=[...e],r=()=>t.reduce((n,i)=>n+i.length,0)+t.length-1;for(let n=t.length-1;n>=0&&r()>L$o;n--)t[n].length>emh&&t.splice(n,1);for(;t.length&&r()>L$o;)t.pop();return t.length?t.join(","):void 0}var ell="unknown";function M5e(e,t,r,n){return typeof e=="string"&&e.trim()?e.length>r?e.slice(0,r):e:(n?.debug(`${t} must be a non-empty string; using "${ell}"`),ell)}function Zft(e){if(e==null)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if(!(typeof t!="number"||!Number.isFinite(t))&&!(t<0||t>9223372036854))return t}function tll(e,t,r){let n=Zft(e);return n===void 0?(e!==void 0&&r?.debug("Span startTime is out of range or not a valid time; using the current time"),t):(t-n>864e5?r?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>t&&r?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function Non(e,t){return e<t?t:e}function WKt(e,t,r,n){let i=Zft(e);return i===void 0?(e!==void 0&&n?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):i}function zon(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var $ft=class{constructor(t,r,n){this._onEnd=r,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=t.traceId,this._spanId=t.spanId,this._parentSpanId=t.parentSpanId,this._traceState=t.traceState,this._traceFlags=t.traceFlags??kon,this._parentIsRemote=t.parentIsRemote??!1,this._name=t.name,this._kind=t.kind,this._autoKeys=new Set(t.autoAttributeKeys),this._maxAttributes=t.maxAttributes,this._maxEvents=t.maxEvents,this._maxAttributesPerEvent=t.maxAttributesPerEvent,this._maxAttributeValueLength=t.maxAttributeValueLength,this._attributes=Object.create(null);for(let i of Object.keys(t.attributes))this._writeAttribute(i,t.attributes[i]);this._startMono=t.backdated?void 0:zon(),this._startTime=t.clockAnchor&&this._startMono!==void 0?t.clockAnchor.wall+(this._startMono-t.clockAnchor.mono):t.startTime,this._startMono!==void 0&&(this._clockAnchor=t.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let t=zon();if(t!==void 0)return this._startTime+Math.max(0,t-this._startMono)}return Date.now()}_mutable(t){return this._ended?(this._logger?.debug(`Ignoring ${t} on a span that has already ended`),!1):!0}_writeAttribute(t,r){if(XJ(r)){t in this._attributes&&!this._autoKeys.has(t)&&this._userAttributeCount--,delete this._attributes[t];return}if(!this._autoKeys.has(t)&&!(t in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[t]=Mon(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=ege({},t);for(let n of Object.keys(r))this._writeAttribute(n,r[n])}return this}addEvent(t,r,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=r&&oll(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:M5e(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:WKt(n,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(t,r){if(this._mutable("setStatus")){if(t!=="ok"&&t!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(t)}"; expected "ok" or "error"`),this;this._status={code:t,...r&&{message:_$o(r,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(t){if(!this._mutable("recordException"))return this;let{type:r,message:n,stack:i}=U$o(t);return this.addEvent(rmh,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=M5e(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return $ul(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(t){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=this._now(),n=WKt(t,r,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:Non(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},rmh="exception",nmh=4294967295;function imh(e){try{return typeof e=="string"?e:String(e)}catch{return rG}}function L5e(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),nmh)}function omh(e,t){if(!t.length)return Object.keys(e);let r=t.filter(i=>Object.prototype.propertyIsEnumerable.call(e,i)),n=new Set(r);return[...r,...Object.keys(e).filter(i=>!n.has(i))]}function nll(e,t,r,n,i,o,s=[]){let a=0,c=0,u={};for(let f of omh(e.attributes,s)){let m=e.attributes[f];if(!XJ(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(u,f,{value:Mon(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=u,c&&(e.droppedAttributesCount=L5e(e.droppedAttributesCount)+c);let l=0,p=0,d=[];for(let f of e.events){if(l>=n){p++;continue}if(l++,f.attributes){let m=oll(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=L5e(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=L5e(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:_$o(imh(e.status.message),o)})}var Qon=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},ill=new Qon,HKt=class extends Qon{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function smh(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function O1e(e,t){let r=Don(e?.parent)??t,n=typeof r=="string"||r==null?r:rll(r,"traceparent"),i=Zul(n);if(!i)return ill;let o=typeof r=="string"||r==null?e?.tracestate:rll(r,"tracestate");return new HKt(i,Fon(o))}function rll(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function _$o(e,t){return e.length>t?e.slice(0,t):e}function Mon(e,t){return jon(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function jon(e,t,r,n){if(e===null||typeof e!="object")return XJ(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?_$o(e,t):e);if(r.ancestors.has(e))return Aon;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=amh(e);if(i.selfDescribed)return XJ(i.value)?String(i.value):jon(i.value,t,r,n+1);if(X4(e)){let a=Math.min(e.length,1e3),c=[];for(let u=0;u<a;u++)try{c.push(jon(e[u],t,r,n+1))}catch{c.push(rG)}return e.length>a&&(c.length=e.length),c}let o={},s=0;for(let a of Object.keys(e)){if(s>=1e3)break;let c;try{c=jon(e[a],t,r,n+1)}catch{c=rG}a&&!XJ(c)&&s++,Object.defineProperty(o,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return o}catch{return e}finally{r.ancestors.delete(e)}}function amh(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function oll(e,t,r){let n;try{n=Object.keys(e)}catch{return{attributes:{},dropped:0}}let i={},o=0,s=0;for(let a of n){if(o>=t){s++;continue}let c;try{c=Mon(e[a],r)}catch{c=rG}XJ(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function sll(e,t){for(let r of Object.keys(e))e[r]=Mon(e[r],t);return e}function KKt(e,t,r){return t===ill?r(t):e.with(t,()=>r(t))}function U$o(e){try{let t=smh(e);if(w1e(e))return{type:e.name||"Error",message:e.message||"",...t};if(typeof e=="string")return{type:"string",message:e};if(e&&typeof e=="object"){let r=e;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...t}}return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}var V$o={internal:1,server:2,client:3,producer:4,consumer:5},cmh={ok:1,error:2},umh=1,lmh=256,pmh=512;function fmh(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:umh)|lmh|(e.parentIsRemote?pmh:0)}function Lon(e){if(typeof e=="string")return xne(e);try{return xne(String(e))}catch{return rG}}function dmh(e){return e&&Object.prototype.hasOwnProperty.call(V$o,e)?V$o[e]:V$o.internal}function G$o(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function mmh(e,t){let r={name:Lon(e.name),timeUnixNano:G$o(e.timestamp)};if(e.attributes){let i=wne(e.attributes,t);i.length&&(r.attributes=i)}let n=L5e(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function all(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:Lon(e.name),kind:dmh(e.kind),startTimeUnixNano:G$o(e.startTime),endTimeUnixNano:G$o(e.endTime),flags:fmh(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=Lon(e.traceState));let n=wne(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>mmh(s,t)));let i=L5e(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=L5e(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:cmh[e.status.code],...e.status.message&&{message:Lon(e.status.message)}}),r}function cll(e,t,r){return LKt(e,t,r)}function ull(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:_Kt(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var lll=8;function _on(){return zon()??Date.now()}function q$o(e){try{return e instanceof $ft}catch{return!1}}function pll(e,t){let r=Yul(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:Fon(t),traceFlags:r.flags,isRemote:!0}}function hmh(e){try{return typeof e.traceparent=="function"}catch{return!1}}function gmh(e){return!!e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)&&Array.isArray(e.events)&&e.name!==void 0&&e.kind!==void 0&&e.startTime!==void 0&&e.endTime!==void 0}function Uon(e,t,r){e[t]!==r&&(e[t]=r)}function Amh(e,t){try{let r=Object.getOwnPropertyDescriptors(e);for(let n of["traceId","spanId","parentSpanId","traceState"])r[n]={value:t[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{return e}}var JKt=class{constructor(t,r,n,i,o,s){this._instance=t,this._config=r,this._logger=n,this._getContext=i,this._contextManager=o,this._onSpanQueued=s,this._queue=[],this._flushTimer=new Q5e(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=sG,this._retryAfter=new j5e,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=r.maxExportBatchSize}startSpan(t,r){if(this._instance.isDisabled||this._instance.optedOut)return O1e(r,this._contextManager.active());let n=Don(r?.parent);if(n&&typeof n!="string"&&!q$o(n)){if(hmh(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),O1e(r,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let i=this._resolveParent(n,r);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),O1e(r,this._contextManager.active());let o=Date.now(),s=tll(r?.startTime,o,this._logger),a=Wul();this._liveSpans.set(a,_on());let c=this._autoContextAttributes();return new $ft({traceId:i?.traceId??qul(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:M5e(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:ege({...c},r?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:s,backdated:s!==o,clockAnchor:Zft(r?.startTime)===void 0?i?.clockAnchor:void 0},(u,l)=>this._onSpanEnd(u,l),this._logger)}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this.startSpan(t,i);try{let a=KKt(this._contextManager,s,o);return uul(a)?a.then(c=>(s.end(),c),c=>{throw this._recordCallbackError(s,c),s.end(),c}):(s.end(),a)}catch(a){throw this._recordCallbackError(s,a),s.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let t=this._generation,r=Promise.resolve().then(()=>t===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===r&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=r,r}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=sG,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=pll(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if(q$o(t))return t.childContext();let n=this._contextManager.active();if(q$o(n))return n.childContext();if(n instanceof HKt)return pll(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let t;try{t=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let r={};return t.distinctId&&(r.posthogDistinctId=t.distinctId),t.sessionId&&(r.sessionId=t.sessionId),t.currentUrl&&(r["url.full"]=t.currentUrl),t.screenName&&(r["screen.name"]=t.screenName),t.appState&&(r["app.state"]=t.appState),r}_recordCallbackError(t,r){if(!(t instanceof $ft))return;let{type:n,message:i,stack:o}=U$o(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=_on()-this._config.maxSpanAgeMs,r=0;for(let[n,i]of this._liveSpans){if(i>t)break;this._liveSpans.delete(n),r++}r&&this._recordDrop(r,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(t,r){if(!this._liveSpans.delete(t.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(t,r);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(i){this._logger.debug("Span queue notification failed",i)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(t){let r=t.droppedAttributesCount??0,n=t.droppedEventsCount??0,i=0;for(let o of t.events)i+=o.droppedAttributesCount??0;(r||n||i)&&this._logger.debug(`Span limits discarded data from "${t.name}": ${r} attributes, ${n} events, ${i} event attributes`)}_runBeforeSpanSend(t,r){if(!this._config.beforeSpanSend.length)return t;let n={traceId:t.traceId,spanId:t.spanId,parentSpanId:t.parentSpanId,traceState:t.traceState},i={startTime:t.startTime,endTime:t.endTime},o={attributes:t.droppedAttributesCount,events:t.droppedEventsCount},s=Object.keys(t.attributes),a={traceFlags:t.traceFlags,parentIsRemote:t.parentIsRemote},c=t.status&&{...t.status},u=t,l=t;try{for(let f of this._config.beforeSpanSend){let m=f(u);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;u=this._keepSpanIdentity(m,n)}if(l={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:u.name,kind:u.kind,status:u.status,attributes:u.attributes,events:u.events,startTime:u.startTime,endTime:u.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!gmh(l))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;l.name=M5e(l.name,"Span name",this._config.maxAttributeValueLength,this._logger),l.status&&l.status.code!=="ok"&&l.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),l.status=c),l.startTime=Zft(l.startTime)??i.startTime,l.endTime=Non(Zft(l.endTime)??i.endTime,l.startTime);let d=[];for(let f of l.events)try{d.push({...f,name:M5e(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:WKt(f.timestamp,l.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return l.events=d,nll(l,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),l}catch(p){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",p),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(t,r){(t.traceId!==r.traceId||t.spanId!==r.spanId||t.parentSpanId!==r.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{Uon(t,"traceId",r.traceId),Uon(t,"spanId",r.spanId),Uon(t,"parentSpanId",r.parentSpanId),Uon(t,"traceState",r.traceState)}catch{return Amh(t,r)}return t}_recordDrop(t,r){this._droppedSinceWarning+=t,this._dropReasons.add(r),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(t){let r=[];for(let n of t)try{r.push(all(n,this._logger))}catch(i){this._logger.debug("Failed to encode a span; dropping it",i),this._recordDrop(1,"its attributes could not be encoded")}return r}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let t=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(t,"the user has opted out"),this._warnAboutDrops(),t}async _flushInner(){if(!this._queue.length)return 0;let t=this._discardQueueIfConsentWithdrawn();if(t)return t;let r=sll(cll(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),o=this._queue.length,s=0,a=1/0,c=this._generation;try{for(;o>0&&this._queue.length>0;){let u=this._discardQueueIfConsentWithdrawn();if(u)return s+u;let l=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(l,a,o,this._queue.length)),d=this._queue.slice(0,p),f=this._encodeBatch(d);if(!f.length){this._queue.splice(0,p),o-=p,s+=p,this._resetHeadBatchBudget();continue}let m=_on()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(ull(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=sG,this._resetHeadBatchBudget(),this._queue.splice(0,p),o-=p,s+=p,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(g.kind==="too-large"){if(p===1){this._queue.splice(0,1),o-=1,s+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=sG,this._resetHeadBatchBudget();continue}let A=Math.max(1,Math.floor(p/2));g.measuredLocally?a=A:this._maxExportBatchSize=A,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${A}`);continue}if(g.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=UKt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=_on()+this._nextFlushDelay()),this._headBatchFailures<lll)return this._logger.debug("Span export failed; retrying on the next flush",g.error),s;if(this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=sG,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${lll} times in a row`),this._retryAfter.isOpen())return s;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",g.error),this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=sG,this._resetHeadBatchBudget(),this._recordDrop(p,"the ingestion endpoint rejected the batch")}return s}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(t=>{this._logger.debug("Background span flush failed",t)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(VKt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var YKt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var ymh=5e3,bmh=512,Emh=2048,Imh=128,vmh=128,Cmh=128,xmh=8192,Smh=1e4,wmh=36e5;function P1e(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var fll=["service.name","service.version","deployment.environment"];function Tmh(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(fll.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of fll)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function Omh(e,t){if(!e)return[];let r=[e].flat().filter(i=>!!i),n=r.filter(i=>typeof i=="function");return n.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-n.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function W$o(e,t,r){let n=ege({...t},Tmh(e?.resourceAttributes)),i=P1e(e?.maxExportBatchSize,bmh);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:Omh(e?.beforeSpanSend,r),maxAttributesPerSpan:P1e(e?.maxAttributesPerSpan,Imh),maxEventsPerSpan:P1e(e?.maxEventsPerSpan,vmh),maxAttributesPerEvent:Cmh,maxAttributeValueLength:P1e(e?.maxAttributeValueLength,xmh),flushIntervalMs:P1e(e?.flushIntervalMs,ymh),maxExportBatchSize:i,maxQueueSize:Math.max(P1e(e?.maxQueueSize,Emh),i),maxLiveSpans:P1e(e?.maxLiveSpans,Smh),maxSpanAgeMs:P1e(e?.maxSpanAgeMs,wmh)}}var H$o=require("fs"),hll=require("fs/promises"),J$o=require("path"),gll=require("readline"),Von=new lO.ReduceableCache(25),XKt=new lO.ReduceableCache(20),Y$o=7,Pmh=1e3,Bmh=1e4,K$o=10485760;async function All(e,t=hll.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],u=c?.filename;if(!c||typeof u!="string"||typeof c.lineno!="number"||Nmh(u)||jmh(c)||!(0,J$o.isAbsolute)(u)&&i===void 0)continue;n[u]||(n[u]=[]),n[u].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=yll(a,i);if(c===void 0||XKt.get(c))continue;let u=n[a];if(!u)continue;u.sort((d,f)=>d-f);let l=Qmh(u);if(l.every(d=>zmh(c,d)))continue;let p=Mmh(Von,c,{});s.push(Dmh(a,l,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&kmh(e,Von,i),Von.reduce(),e}async function Rmh(e,t,r){let n,i=!1;try{n=await t(e,H$o.constants.O_RDONLY|H$o.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>K$o?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${K$o}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function Dmh(e,t,r,n,i,o){let s=await Rmh(e,i,o);if(s===void 0)return void XKt.set(n,1);let a=s;return new Promise(c=>{let u=!1;function l(x){u||(u=!0,x?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:K$o-1})}catch{XKt.set(n,1),l();return}let d;try{d=(0,gll.createInterface)({input:p})}catch{XKt.set(n,1),l(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void l(p);let A=g[0],y=g[1];function I(){XKt.set(n,1),d.close(),d.removeAllListeners(),l(p)}p.on("error",I),d.on("error",I),d.on("close",()=>l(p)),d.on("line",x=>{if(f++,!(f<A)&&(r[f]=Lmh(x,0),f>=y)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let v=t[m];if(v===void 0){d.close(),d.removeAllListeners();return}A=v[0],y=v[1]}})})}function kmh(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=yll(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;Fmh(n.lineno,n,o)}}function Fmh(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=bll(e);i<e;i++){let o=r[i];if(o===void 0)return void dll(t);t.pre_context.push(o)}if(r[e]===void 0)return void dll(t);t.context_line=r[e];let n=Ell(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 dll(e){delete e.pre_context,delete e.context_line,delete e.post_context}function Nmh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function jmh(e){return e.lineno!==void 0&&e.lineno>Bmh||e.colno!==void 0&&e.colno>Pmh}function yll(e,t){return(0,J$o.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function zmh(e,t){let r=Von.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 Qmh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=mll(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+Y$o:(i.push(n),n=mll(o)),t++}return i}function mll(e){return[bll(e),Ell(e)]}function bll(e){return Math.max(1,e-Y$o)}function Ell(e){return e+Y$o}function Mmh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function Lmh(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}var edt=require("path");function Ill(e=process.cwd()){let t=edt.sep==="\\",r=i=>t?i.replace(/\\/g,"/"):i,n=r(e);return async i=>{for(let o of i)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,edt.isAbsolute)(o.filename)&&(o.filename=r((0,edt.relative)(n,r(o.filename))));return i}}var vll="5.55.0";var rge={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var B1e=class e{constructor(t){this._host=t.host,this._distinctId=t.distinctId,this._groups=t.groups,this._disableGeoip=t.disableGeoip,this._flags=t.flags,this._requestId=t.requestId,this._evaluatedAt=t.evaluatedAt,this._flagDefinitionsLoadedAt=t.flagDefinitionsLoadedAt,this._errorsWhileComputing=t.errorsWhileComputing??!1,this._quotaLimited=t.quotaLimited??!1,this._accessed=t.accessed??new Set,this._isSlice=t.isSlice??!1}isEnabled(t,r={}){let n=this._flags[t];return this._recordAccess(t),n?.enabled??r.defaultValue??!1}getFlag(t){let r=this._flags[t];if(this._recordAccess(t),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(t){return this._flags[t]?.payload}onlyAccessed(){let t={};for(let r of this._accessed){let n=this._flags[r];n&&(t[r]=n)}return this._cloneWith(t)}only(t){let r={},n=[];for(let i of t){let o=this._flags[i];o?r[i]=o:n.push(i)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let t={},r=[];for(let[n,i]of Object.entries(this._flags)){let o=i.enabled===!1?!1:i.variant??!0;t[`$feature/${n}`]=o,i.enabled&&r.push(n)}return r.length>0&&(r.sort(),t.$active_feature_flags=r),t}_cloneWith(t){return new e({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:t,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(t){if(this._accessed.add(t),this._distinctId===""||this._isSlice&&!(t in this._flags))return;let r=this._flags[t],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,i={$feature_flag:t,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${t}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(rge.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(rge.QUOTA_LIMITED),r===void 0&&o.push(rge.FLAG_MISSING),o.length>0&&(i.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:t,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}};var _mh=6e4;function Cll(e){return e==="client"||e==="server"?e:"all"}function Umh(e,t){return e===t||e==="all"||t==="all"}var tdt=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function Vmh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var Tne=class e extends Error{constructor(t){super(t),Vmh(this,e)}},Gon=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.pollerStopped=!1,this.filteredOutFlagKeys=new Set,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.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}withEvaluationSnapshot(t){return t.definitions?t:{...t,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}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 c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(u){u instanceof Tne||u instanceof sl?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${t}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${u}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a=this.withEvaluationSnapshot({...t,definitions:void 0});return await Promise.all(s.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof Tne||u instanceof sl?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(this.loadedSuccessfullyOnce&&(r=this.withEvaluationSnapshot(r)),o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=this.withEvaluationSnapshot(r),t=r.definitions.featureFlagsByKey[t.key]??t;let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=R$o(t.filters?.payloads,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(!t.active)return!1;if(t.ensure_experience_continuity)throw new sl("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=r.definitions.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new sl("Flag has unknown group type index");if(!(u 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[u];return await this.matchFeatureFlagProperties(t,i[u],l,r)}{let u=this.getBucketingValueForFlag(t,n,o);if(u===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 sl(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,u,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}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!n.definitions.featureFlagsByKey)throw new sl("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new sl(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new sl(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new sl(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=n.definitions.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new sl(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))i[c]=!1;else throw new sl(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new sl(`Dependency '${c}' 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){i=this.withEvaluationSnapshot(i);let o=t.filters||{},s=await P$o(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,u=o.early_exit??!1,{groups:l,groupProperties:p}=i,d=!1,f;for(let m of a)try{let g=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,A=n,y=r;if(g!==c&&g!=null){let x=i.definitions.groupTypeMapping[String(g)];if(!x||!(x in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(x in p)){d=!0;continue}A=p[x],y=l[x]}let I=await this.isConditionMatch(t,y,m,A,i);if(I==="match"){let x=m.variant,v=o.multivariate?.variants||[];f=x&&v.some(S=>S.key===x)?x:await this.getMatchingVariant(t,y)||!0;break}if(u&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof Tne)throw g;if(g instanceof sl)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new sl("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){o=this.withEvaluationSnapshot(o);let s=o.definitions,a=n.rollout_percentage,c=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let l=u.type,p=!1;if(l==="cohort"){let d=await Sll(u,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=u.operator==="not_in"?!d:d}else p=l==="flag"?await this.evaluateFlagDependency(u,i,o):xll(u,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await QKt(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return B$o(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return Pon(t.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(t){if(!this.evaluationContexts||this.evaluationContexts.length===0)return t;let r=new Set(this.evaluationContexts);return t.filter(n=>{let i=n.evaluation_contexts??n.evaluation_tags;return!i||i.length===0?!0:i.some(o=>r.has(o))})}getEvaluationRuntimeForFlag(t){let r=this.featureFlagsByKey[t];return r?Cll(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>Umh(Cll(r.evaluation_runtime),t)).map(r=>r.key)}updateFlagState(t){let r=this.filterFlagsByEvaluationContexts(t.flags);this.featureFlags=r,this.featureFlagsByKey=r.reduce((i,o)=>(i[o.key]=o,i),{});let n=new Set(r.map(i=>i.key));this.filteredOutFlagKeys=new Set(t.flags.filter(i=>!n.has(i.key)).map(i=>i.key)),this.groupTypeMapping=t.group_type_mapping??t.groupTypeMapping??{},this.cohorts=t.cohorts,this.propertyMatchingVersion=t.property_matching_version??t.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((t.minimal_flag_called_events??t.minimalFlagCalledEvents)===!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(this.featureFlags),!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(){let t=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(_mh,t*2**this.backOffCount):t}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);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 tdt(`Your project key or secret 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.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new tdt(`Your secret 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 secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new tdt(`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=n.group_type_mapping||{},o=n.minimal_flag_called_events===!0,s={flags:n.flags??[],group_type_mapping:i,cohorts:n.cohorts||{},minimal_flag_called_events:o,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:o};if(this.updateFlagState(s),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(s)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(t){t instanceof tdt&&this.onError?.(t)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}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}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=UN(()=>{o.abort()},this.timeout),r.signal=o.signal}let i=()=>clearTimeout(n);try{let o=this.fetch,s=await o(t,r);return s.status!==200?(i(),s):{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{i()}},json:async()=>{try{return await s.json()}finally{i()}}}}catch(o){throw i(),o}}async stopPoller(t=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await T1e(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function xll(e,t,r,n){return O$o(e,t,{warnFunction:r,propertyMatchingVersion:n})}function Gmh(e,t){if(!(e in t))throw new Tne(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Sll(e,t,r,n=!1,i,o){let s=String(e.value);Gmh(s,r);let a=r[s];return wll(a,t,r,n,i,o)}async function wll(e,t,r,n=!1,i,o){if(!e)return!0;let s=e.type,a=e.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let u of a)try{let l=await wll(u,t,r,n,i,o);if(s==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof Tne)throw l;if(l instanceof sl)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new sl("Can't match cohort without a given cohort property value");return s==="AND"}for(let u of a)try{let l;if(u.type==="cohort")l=await Sll(u,t,r,n,i,o);else if(u.type==="flag"){if(!i)throw new sl(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await i(u)}else l=xll(u,t,void 0,o);let p=u.negation||!1;if(s==="AND"){if(!l&&!p||l&&p)return!1}else if(l&&!p||!l&&p)return!0}catch(l){if(l instanceof Tne)throw l;if(l instanceof sl)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new sl("can't match cohort without a given cohort property value");return s==="AND"}var qmh=["--unhandled-rejections","--unhandled_rejections"],Wmh=new Set(["throw","strict","warn","warn-with-error-code","none"]),Hmh=[...globalThis.process?.execArgv??[]],Kmh=globalThis.process?.env?.NODE_OPTIONS;function Jmh(e){let t=[],r="",n=!1;for(let i=0;i<e.length;i++){let o=e[i];o==="\\"&&n&&i+1<e.length?r+=e[++i]:o!==" "||n?o==='"'?n=!n:r+=o:r&&(t.push(r),r="")}return r&&t.push(r),t}function Tll(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=qmh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);Wmh.has(o)&&(t=o)}return t}function Ymh(e=Hmh,t=Kmh){return Tll(e)??Tll(Jmh(t??""))??"throw"}var Oll=Ymh();function Pll(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function Xmh(e,t){let r=!1;return Object.assign((n,i)=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length;Pll(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function Bll(e,t,r=Oll){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>Pll(e,i,o));n.on("uncaughtException",Xmh(e,t))}}function Rll(e,t=Oll){let r=globalThis.process;!r||t==="throw"||t==="strict"||t==="warn-with-error-code"||r.on("unhandledRejection",n=>{e(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var Zmh=2e3,X$o=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new uon({...Ucl(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return vKt(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i,o){let s={...o},a=t.buildFromUnknown(r,n);a.$exception_list=await t.modifyFrames(a.$exception_list);let c=lO.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(Bll(this.onException.bind(this),this.onFatalError.bind(this)),Rll(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(this.client.getErrorPropertiesBuilder(),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._capturePreparedEvent(n,!1)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(Zmh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},_5e=X$o;var qon=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function $mh(e){return e==="v0"||e==="v1"}function Dll(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return $mh(e)?e:"v0"}var ehh="$ai_",ZKt="analytics";function kll(e){return typeof e.event=="string"&&e.event.startsWith(ehh)}var rdt=class e extends Error{constructor({requestId:t,drops:r,retryExhausted:n,cause:i}){super(e.buildMessage(t,r,n,i)),this.name="CaptureV1Error",this.requestId=t,this.drops=r,this.retryExhausted=n,this.cause=i}static buildMessage(t,r,n,i){let o=`Capture V1 batch ${t} did not fully deliver: ${r.length} dropped, ${n.length} undelivered`;return i instanceof Error&&(o+=` (${i.message})`),o}};function Z$o(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function thh(e){return typeof e=="string"?e:void 0}var rhh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Z$o},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Z$o},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Z$o},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:thh}],nhh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function ihh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ohh(e){if(typeof e=="string"){let r=new Date(e);if(Number.isNaN(r.getTime()))return new Date().toISOString();let n=r.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function Fll(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function shh(e){let r={...ihh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of rhh)if(o in r){let c=a(r[o]);c!==void 0&&(n[s]=c),delete r[o]}let i={};for(let{property:o,field:s}of nhh)if(o in r){let a=r[o];typeof a=="string"&&(i[s]=a),delete r[o]}return delete r.$lib,delete r.$lib_version,Fll(r,"$set",e.$set),Fll(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:ohh(e.timestamp),...i,options:n,properties:r}}function Nll(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(shh)};return r&&(n.historical_migration=!0),n}var ahh="/i/v1/analytics/events",chh=3e4,uhh=new Set([408,500,502,503,504]),Won=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??chh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>UN(i,n))),this.generateRequestId=r.generateRequestId??_N,this.compress=r.compress??NKt}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=Nll(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${ahh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let u=1;u<=c;u++){let l=u===c,p=S1e({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,u,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!l&&uhh.has(A)){let y=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(u,y)}else{let y=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,y)}else{let y;try{y=await d.waitFor(this.parseResponse(m))}catch(v){if(g.aborted)throw v;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,y,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(l)return void this.onError(new rdt({requestId:r,drops:s,retryExhausted:I.map(v=>v.uuid)}));a=I;let x=this.parseRetryAfter(m);f=this.backoffDelay(u,x)}}catch(m){if(d&&!d.signal.aborted)throw m;if(l)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(u)}finally{d?.cleanup()}f!==void 0&&await this.sleep(f)}}async sendOnce(t,r,n,i){let o=this.buildHeaders(n,i),s=r;if(this.config.compressionEnabled){let p=await this.compress(r,this.config.isDebug);p!==null&&(s=p,o["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",u,l=new Promise((p,d)=>{u=UN(()=>{let f=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);f.name="AbortError",d(f),a.abort(f)},this.config.requestTimeoutMs)});try{let p=this.fetchFn(t,{method:"POST",headers:o,body:s,signal:a.signal}),d=!1;p.then(y=>{a.signal.aborted&&!d&&this.cancelBody(y)}).catch(()=>{});let f=await Promise.race([p,l]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:y=>Promise.race([y,l]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(u),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(u),p}}buildHeaders(t,r){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(t),"PostHog-Request-Id":r,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(t,r,n){let i=r.results??{},o=[];for(let s of t){let a=i[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&o.push(s))}return o}backoffDelay(t,r){let n=Math.min(this.config.initialRetryDelayMs*2**(t-1),this.maxBackoffMs);return r===void 0?n:Math.max(n,Math.min(r,this.maxBackoffMs))}parseRetryAfter(t){let r=t.headers?.get("Retry-After");if(!r)return;let n=r.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let i=Date.parse(n);if(Number.isNaN(i))return;let o=i-this.now();return o>0?o:void 0}async parseResponse(t){let r=await t.text(),n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let i=n.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error("unexpected results shape");return{results:i??{}}}async buildHttpError(t,r,n){let i="";try{i=(await n(t.text())).slice(0,512)}catch{}let o=i?`: ${i}`:"";return new Error(`Capture V1 request failed with HTTP ${r}${o}`)}surfaceBatchFailure(t,r,n,i){this.onError(new rdt({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new rdt({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var U5e="ai-capture",Hon="/i/v0/ai/batch/";var phh=new TextEncoder;function ees(e){return phh.encode(S1e(e)).length}function jll(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=ees(a);if(c>t){i.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}o.length>0&&s+c>r&&(n.push(o),o=[],s=0),o.push(a),s+=c}return o.length>0&&n.push(o),{batches:n,dropped:i}}var fhh=100,zll=3e4,dhh=5e4,mhh=50,hhh=500,ghh="https://us.i.posthog.com",Qll=new Set;function Jon(e,t){Qll.has(e)||(Qll.add(e),console.warn(`[PostHog] ${t}`))}function Ahh(e){return typeof e=="string"?e.trim():""}function yhh(e){return(typeof e=="string"?e.trim():"")||void 0}function bhh(e){return(typeof e=="string"?e.trim():"")||ghh}function Ehh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function Ihh(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))t[`$feature/${n}`]=i;let r=Object.keys(e).filter(n=>e[n]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}var Yon=class extends jKt{constructor(t,r={}){let n=Ahh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:bhh(r.host),personalApiKey:yhh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new qon,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=Dll(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,fhh):i.featureFlagsPollingInterval===null?null:zll,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.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.');i.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new Gon({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:n,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation,evaluationContexts:i.evaluationContexts??i.evaluationEnvironments}))}this.errorTracking=new _5e(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||dhh}enqueue(t,r,n,i){super.enqueue(t,r,n,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(t=!1){let r=this.flushWithPendingPromises();return!this._traces||t&&this._traces.throttled?r:SKt([r,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(t){let r=this._flushEventsAndSpans(t),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(r.catch(()=>{}))}catch{}return r}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??hhh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??mhh;this._waitUntilCycle.timer=UN(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{t?.()}}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)}getQueueRouteKey(t){return this.captureMode==="v1"&&kll(t)?"ai":ZKt}persistedQueueKeyForRoute(t){return t===U5e?jM.AiCaptureQueue:t==="ai"?jM.AiQueue:jM.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[ZKt,"ai"]:[ZKt];return this._aiCaptureRouteActive&&t.push(U5e),t}getBatchEndpointPath(t){return t===U5e?Hon:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=ZKt){if(n===U5e)return this.sendAiCaptureBatch(t,r);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(t,r,n);let i=t.filter(o=>o!==void 0);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(t,r){let{batches:n,dropped:i}=jll(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${Hon}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let o of n)await this.sendAiSubBatch(o,r)}async sendAiSubBatch(t,r){try{await super.sendBatch(t,r,U5e)}catch(n){if(!Xft(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${ees(o)} bytes) was rejected with 413 by ${Hon} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let i=Math.ceil(t.length/2);await this.sendAiSubBatch(t.slice(0,i),r),await this.sendAiSubBatch(t.slice(i),r)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new Won({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(t,r)=>this.fetch(t,r),onError:t=>this._events.emit("error",t),compress:t=>this.compressPayload(t)})),this._v1Sender}getLibraryVersion(){return vll}get metrics(){return this._metrics||(this._metrics=new qKt(this,Ron(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new YKt}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new JKt(this,W$o(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let t=this.context?.get();return{distinctId:t?.distinctId,sessionId:t?.sessionId}}startSpan(t,r){return this._tracesPipeline?.startSpan(t,r)??O1e(r,this._spanContextManager.active())}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this._tracesPipeline;return s?i?s.withSpan(t,i,o):s.withSpan(t,o):KKt(this._spanContextManager,O1e(i,this._spanContextManager.active()),o)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let t=super.getCommonEventProperties();return(this.options.isServer??!0)&&(t.$is_server=!0),t}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}_warnIfInvalidCapture(t,r,n){typeof t=="string"&&this._logger.warn(r),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(t,r,n,i,o){return this.addPendingPromise(this._prepareEventMessage(r,i).then(({distinctId:s,event:a,properties:c,options:u})=>{let l={timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,l,o):this.enqueue(t,p,l,o)}).catch(s=>{s&&console.error(s)}))}_capturePreparedEvent(t,r){return this._sendPreparedEvent("capture",t,r)}capture(t){this._warnIfInvalidCapture(t,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(t,!1)}async captureImmediate(t){return this._warnIfInvalidCapture(t,"Called captureImmediate() with a string as the first argument when an object was expected.","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._capturePreparedEvent(t,!0)}captureAi(t){if(this.disabled)return;let r=z5e(t.uuid,_N);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=z5e(t.uuid,_N);return await this._sendPreparedAiEvent({...t,uuid:r},!0),r}_sendPreparedAiEvent(t,r){return typeof t?.event=="string"&&!t.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${t.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",t,r,void 0,U5e)}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};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:l,disableGeoip:n},!1,{includeContextProperties:!1})}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};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:l,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:t,properties:r={},propertiesOnce:n={}}){if(Object.keys(r).length===0&&Object.keys(n).length===0)return;let i={};Object.keys(r).length>0&&(i.$set=r),Object.keys(n).length>0&&(i.$set_once=n),this.capture({distinctId:t,event:"$set",properties:i})}unsetPersonProperties({distinctId:t,properties:r}){let n=Ehh(r);n.length!==0&&this.capture({distinctId:t,event:"$set",properties:{$unset:n}})}alias(t){this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(t){await this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(t){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(t)}getFeatureFlagKeysByEvaluationRuntime(t){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(t)??[]}async waitForLocalEvaluationReady(t=zll){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){if(this.disabled)return void this._logger.warn("The client is disabled");let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let R=this._flagOverrides[t];if(R===void 0)return;let D=this._payloadOverrides?.[t];return{key:t,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:D}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,y,I,x,v,S;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let R=this.featureFlagsPoller?.featureFlagsByKey[t];if(R)try{let D=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(R,d,{matchValue:i});if(D){m=!0;let O=D.value;I=R.id,v="Evaluated locally",S=R.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:D.payload??void 0,reason:v,reasonCode:R.active===!1?"flag_disabled":void 0}}}catch(D){if(D instanceof Tne||D instanceof sl)this._logger?.info(`${D.name} when computing flag locally: ${t}: ${D.message}`);else throw D}}if(!m&&!c){let R=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,u,l,a,[t]);if(R===void 0)y=rge.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,g=R.requestId,A=R.evaluatedAt;let D=[];R.errorsWhileComputingFlags&&D.push(rge.ERRORS_WHILE_COMPUTING),R.quotaLimited?.includes("feature_flags")&&D.push(rge.QUOTA_LIMITED);let O=R.flags[t];if(O===void 0)D.push(rge.FLAG_MISSING);else{I=O.metadata?.id,x=O.metadata?.version,v=O.reason?.description??O.reason?.code,S=O.metadata?.has_experiment;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:z,reason:v,reasonCode:O.reason?.code}}D.length>0&&(y=D.join(","))}}if(o){let R=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,D={$feature_flag:t,$feature_flag_response:R,$feature_flag_id:I,$feature_flag_version:x,$feature_flag_reason:v,locally_evaluated:m,[`$feature/${t}`]:R,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(S!==void 0&&(D.$feature_flag_has_experiment=S),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(D.$feature_flag_definitions_loaded_at=O)}y&&(D.$feature_flag_error=y),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:R,groups:s,disableGeoip:a,properties:D})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){Jon("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");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(Jon("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),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.disabled)return void this._logger.warn("The client is disabled");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){Jon("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return i===void 0?void 0:i.enabled===!1?!1:!!(i.variant??!0)||!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:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},g={},A=!0;if(f&&(m=f.response,g=f.payloads,A=f.fallbackToFlags),A&&!c){let y=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,u,l,s,a);m={...m,...y.flags||{}},g={...g,...y.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:g}}async evaluateFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new B1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new B1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new B1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,y=!1,I=!1,x=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),v=new Set;if(x)for(let[R,D]of Object.entries(x.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[R];m[R]={key:R,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:x.payloads[R],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},v.add(R)}let S=f!==void 0&&Array.from(f).some(R=>this.featureFlagsPoller?.featureFlagsByKey[R]===void 0);if((x?x.fallbackToFlags||S:!0)&&!c){let R=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,u,l,s,a);if(R){this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,g=R.requestId,A=R.evaluatedAt,y=!!R.errorsWhileComputingFlags,I=Array.isArray(R.quotaLimited)&&R.quotaLimited.includes("feature_flags");for(let[D,O]of Object.entries(R.flags)){if(v.has(D))continue;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}m[D]={key:D,enabled:O.enabled,variant:O.variant,payload:z,id:O.metadata?.id,version:O.metadata?.version,reason:O.reason?.description??O.reason?.code,locallyEvaluated:!1,hasExperiment:O.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[R,D]of Object.entries(this._flagOverrides)){if(D===void 0){delete m[R];continue}let O=m[R];m[R]={key:R,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:O?.payload,id:O?.id,version:O?.version,reason:O?.reason,locallyEvaluated:O?.locallyEvaluated??!1,hasExperiment:O?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[R,D]of Object.entries(this._payloadOverrides)){let O=m[R];O&&(m[R]={...O,payload:D})}if(f!==void 0)for(let R of Object.keys(m))f.has(R)||delete m[R];return new B1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:y,quotaLimited:I})}_shouldSendMinimalFlagCalledEvent(t,r){return t==="$feature_flag_called"&&this._minimalFlagCalledEvents&&r.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=o&&Object.keys(o).length>0?`_${JSON.stringify(Object.entries(o).sort(([l],[p])=>l<p?-1:l>p?1:0))}`:"",u=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(u)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(u):this.distinctIdHasSentFlagCalls[r]=new Set([u]),this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:t=>this._captureFlagCalledEventIfNeeded(t),logWarning:t=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${t}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){await this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!0,{includeContextProperties:!1})}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){let r=Date.now()+(t??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),this._metrics&&(await T1e(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await T1e(this._traces.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,r-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(t){if(this.disabled||!this.apiKey||!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=UN(()=>{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(Mcl(s)&&r&&o in r){let a={};for(let[c,u]of Object.entries(s))a[String(c)]=String(u);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");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 u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,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={...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}personPropertiesForLocalEvaluation(t,r){return{distinct_id:t,...r||{}}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!_5e.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(_5e.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:s},r,n).then(a=>this._capturePreparedEvent({...a,uuid:i,flags:o},!1)))}}async captureExceptionImmediate(t,r,n,i){if(!_5e.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(_5e.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){return this._prepareEventMessage(t)}async _prepareEventMessage(t,r={}){let{distinctId:n,event:i,properties:o,groups:s,flags:a,sendFeatureFlags:c,timestamp:u,disableGeoip:l,uuid:p}=t,d=this.context?.get(),f=r.includeContextProperties??!0,m=n||d?.distinctId,g=f?{...this.props,...d?.properties||{},...o||{}}:{...o||{}};m||(m=_N(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?kKt(g):g,y=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:u,disableGeoip:l,uuid:p});if(!y)return Promise.reject(null);let I=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){Jon("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let x=typeof c=="object"?c:void 0,v=await this.getFeatureFlagsForEvent(y.distinctId,s,l,x);return Ihh(v)}return{}}).catch(()=>({})).then(x=>{let v=y.groups||s;return{...x,...y.properties||{},...v!==void 0&&Object.keys(v).length>0?{$groups:v}:{}}});return y.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&_cl(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(y.event="$bot_pageview",I.$browser_type="bot"),{distinctId:y.distinctId,event:y.event,properties:I,options:{timestamp:y.timestamp,disableGeoip:y.disableGeoip,uuid:y.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)try{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)}}catch(s){return this._logger.error(`Error in before_send function for event '${t.event}':`,s),null}return i}};var Mll=require("async_hooks"),Xon=class{constructor(){this.storage=new Mll.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 Lll=require("async_hooks"),Zon=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new Lll.AsyncLocalStorage}};var _ll=require("zlib"),Ull=require("util"),vhh=(0,Ull.promisify)(_ll.gzip);async function Vll(e,t=!0){try{let r=await vhh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var $on=require("os");function Gll(){let e,t;try{e=(0,$on.platform)(),t=(0,$on.release)()}catch{}return N$o(e,t)}var qll="posthog-node";function Chh(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 c=s.tags[tes.POSTHOG_ID_TAG];if(c===void 0)return s;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],d=p.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(A=>({...A,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},m=lO.getInjectedReleaseId();return m&&(f.$release_id=m),t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var tes=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=qll,this.name=qll,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Chh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var One=class extends Yon{getLibraryId(){return"posthog-node"}compressPayload(t){return Vll(t,this.isDebug)}initializeContext(){return new Xon}initializeSpanContextManager(){return new Zon}hostResourceAttributes(){return Gll()}createErrorPropertiesBuilder(){return new lO.ErrorPropertiesBuilder([new lO.EventCoercer,new lO.ErrorCoercer,new lO.ObjectCoercer,new lO.StringCoercer,new lO.PrimitiveCoercer],lO.createStackParser("node:javascript",lO.nodeStackLineParser),[Fcl(),t=>All(t,void 0,this._logger),Ill()])}};function Wll(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var esn=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},xhh="feature_flag_evaluated",Shh=3e3,whh=3e3,tsn=class{evaluator;environment;sendFeatureFlagEvents;pending=new Map;resolved=new Map;constructor({environment:t,sendFeatureFlagEvents:r,posthogApiKey:n,evaluator:i}){this.environment=t,this.sendFeatureFlagEvents=r,this.evaluator=i??new One(n??"",{featureFlagsRequestTimeoutMs:Shh,isServer:!1})}isEnabled(t,r){let n=Hll(t,r),i=this.pending.get(n);if(i!=null)return i;let o=this.evaluateAndRemember(t,r,n);return this.pending.set(n,o),o}async evaluateAndRemember(t,r,n){let i=await this.evaluate(t,r);return this.resolved.set(n,i),i}getCachedValue(t,r){return this.resolved.get(Hll(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,whh),t.unref()})])}catch{}finally{clearTimeout(t)}}async flushAfterPendingEvaluations(){await Promise.allSettled(this.pending.values()),await this.evaluator.flush()}async evaluate(t,r){let{org:n}=r,i=Ohh(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,res(n),{personProperties:i,groups:{organization:n},groupProperties:{organization:i},sendFeatureFlagEvents:!1})}catch{return!1}return this.sendFeatureFlagEvents&&this.captureFlagUsage({flag:t,org:n,result:o,properties:i}),Wll(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=Thh(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.183.1"};this.tryCapture({distinctId:res(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:res(r),event:xhh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:Wll(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function Thh(e){if(e!=null)return e.enabled?e.variant??!0:!1}function res(e){return`org:${e}`}function Ohh({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function Hll(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var rsn;function nsn(){return rsn==null&&(rsn=Phh()),rsn}async function nes(){await rsn?.flush()}function Phh(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new esn:new tsn({posthogApiKey:e,environment:YJ(),sendFeatureFlagEvents:oon()})}var isn=class{posthog;constructor({posthogApiKey:t}){this.posthog=new One(t,{isServer:!1})}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.183.1",usingAccessToken:!0,cliReleaseEnvironment:YJ(),...zpe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:YJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var $Kt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};Of();tr();var ndt=require("fs/promises"),Kll=require("os"),Jll=require("path");xVe();var Bhh="id",Rhh=".fern",eJt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new One(r,{isServer:!1}),this.userId=t==null?void 0:K7o(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:"5.183.1",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:YJ(),agent:JHr(),...r!=null?{userEmail:r}:{},...zpe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:YJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}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 ol({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=Xw(),r=Be($t.of((0,Kll.homedir)()),Ae.of(Rhh),Ae.of(Bhh));try{await Vt(r)?this.persistedDistinctId=(await(0,ndt.readFile)(r)).toString():(await(0,ndt.mkdir)((0,Jll.dirname)(r),{recursive:!0}),await(0,ndt.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var ies;async function tJt(){return ies==null&&(ies=await Dhh()),ies}async function Dhh(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!oon())return new $Kt;let t=await mpt();return t!=null?new eJt({token:t,posthogApiKey:e}):await OM()!=null?new isn({posthogApiKey:e}):new eJt({token:void 0,posthogApiKey:e})}catch{return new $Kt}}En();ct();Dt();yM();var rJt=ye(require("process"),1);BZe();var Zll=ye(G4o(),1),$ll=ye(Xll(),1);function pO(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=SH(e),e.length===0))return 0;e=e.replace((0,$ll.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(Zll.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}En();function osn(e){let t=0;for(let r of e.split(`
|
|
3474
3474
|
`))t=Math.max(t,pO(r));return t}var bpl=ye(ses(),1);var Fhh=/[\p{Lu}]/u,Nhh=/[\p{Ll}]/u,rpl=/^[\p{Lu}](?![\p{Lu}])/gu,opl=/([\p{Alpha}\p{N}_]|$)/u,aes=/[_.\- ]+/,jhh=new RegExp("^"+aes.source),npl=new RegExp(aes.source+opl.source,"gu"),ipl=new RegExp("\\d+"+opl.source,"gu"),zhh=(e,t,r,n)=>{let i=!1,o=!1,s=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];a=c>2?e[c-3]==="-":!0,i&&Fhh.test(u)?(e=e.slice(0,c)+"-"+e.slice(c),i=!1,s=o,o=!0,c++):o&&s&&Nhh.test(u)&&(!a||n)?(e=e.slice(0,c-1)+"-"+e.slice(c-1),s=o,o=!1,i=!0):(i=t(u)===u&&r(u)!==u,s=o,o=r(u)===u&&t(u)!==u)}return e},Qhh=(e,t)=>(rpl.lastIndex=0,e.replace(rpl,r=>t(r))),Mhh=(e,t)=>(npl.lastIndex=0,ipl.lastIndex=0,e.replace(npl,(r,n)=>t(n)).replace(ipl,r=>t(r)));function ces(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?aes.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=zhh(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(jhh,""),e=t.preserveConsecutiveUppercase?Qhh(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),Mhh(e,n))}var fes=ye(apl(),1);BZe();var cpl=(e=0)=>t=>`\x1B[${t+e}m`,upl=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,lpl=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,BE={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]}},fsC=Object.keys(BE.modifier),Vhh=Object.keys(BE.color),Ghh=Object.keys(BE.bgColor),dsC=[...Vhh,...Ghh];function qhh(){let e=new Map;for(let[t,r]of Object.entries(BE)){for(let[n,i]of Object.entries(r))BE[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=BE[n],e.set(i[0],i[1]);Object.defineProperty(BE,t,{value:r,enumerable:!1})}return Object.defineProperty(BE,"codes",{value:e,enumerable:!1}),BE.color.close="\x1B[39m",BE.bgColor.close="\x1B[49m",BE.color.ansi=cpl(),BE.color.ansi256=upl(),BE.color.ansi16m=lpl(),BE.bgColor.ansi=cpl(10),BE.bgColor.ansi256=upl(10),BE.bgColor.ansi16m=lpl(10),Object.defineProperties(BE,{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=>BE.rgbToAnsi256(...BE.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)=>BE.ansi256ToAnsi(BE.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>BE.ansi256ToAnsi(BE.hexToAnsi256(t)),enumerable:!1}}),BE}var Whh=qhh(),ppl=Whh;var ssn=new Set(["\x1B","\x9B"]),Hhh=39,les="\x07",mpl="[",Khh="]",hpl="m",pes=`${Khh}8;;`,fpl=e=>`${ssn.values().next().value}${mpl}${e}${hpl}`,dpl=e=>`${ssn.values().next().value}${pes}${e}${les}`,Jhh=e=>e.split(" ").map(t=>pO(t)),ues=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=pO(SH(e[e.length-1]));for(let[a,c]of n.entries()){let u=pO(c);if(s+u<=r?e[e.length-1]+=c:(e.push(c),s=0),ssn.has(c)&&(i=!0,o=n.slice(a+1).join("").startsWith(pes)),i){o?c===les&&(i=!1,o=!1):c===hpl&&(i=!1);continue}s+=u,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())},Yhh=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(pO(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},Xhh=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=Jhh(e),a=[""];for(let[u,l]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=pO(a[a.length-1]);if(u!==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[u]>t){let d=t-p,f=1+Math.floor((s[u]-d-1)/t);Math.floor((s[u]-1)/t)<f&&a.push(""),ues(a,l,t);continue}if(p+s[u]>t&&p>0&&s[u]>0){if(r.wordWrap===!1&&p<t){ues(a,l,t);continue}a.push("")}if(p+s[u]>t&&r.wordWrap===!1){ues(a,l,t);continue}a[a.length-1]+=l}r.trim!==!1&&(a=a.map(u=>Yhh(u)));let c=[...a.join(`
|
|
3475
3475
|
`)];for(let[u,l]of c.entries()){if(n+=l,ssn.has(l)){let{groups:d}=new RegExp(`(?:\\${mpl}(?<code>\\d+)m|\\${pes}(?<uri>.*)${les})`).exec(c.slice(u).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===Hhh?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=ppl.codes.get(Number(i));c[u+1]===`
|
|
3476
3476
|
`?(o&&(n+=dpl("")),i&&p&&(n+=fpl(p))):l===`
|
|
@@ -4132,7 +4132,7 @@ ${we.stack}`),Y&&f?.({event:"reload",ok:!1,durationMs:Date.now()-ft,error:In(we)
|
|
|
4132
4132
|
`)},rr=[],Ce=!1;if(se.on("all",(We,ft)=>{n.logger.info(de.dim(`[${We}] ${ft}`)),!Ce&&(rr.push($t.of(ft)),Oe!=null&&clearTimeout(Oe),Oe=setTimeout(()=>{(async()=>{Ce=!0;try{let we=z.getFilesToReload(rr);await te(we)&&await Yt()}finally{rr.length=0,Ce=!1}})()},KKg))}),ue){await Ge;return}let ge=`http://localhost:${i}${I}`;n.logger.info(`Docs preview server (Astro) ready on ${ge}`),Y=!0,f?.({event:"ready",url:ge,port:i,backendPort:s,pid:process.pid}),Re.start(),await Ge}async function eJg({bundlePath:e,forceDownload:t,cacheDir:r,context:n}){if(e!=null)return n.logger.info(`Using Astro bundle from path: ${e}`),await WSp($t.of(e));if(t){let a=d2e({astro:!0,cacheDir:r});await Vt(a)&&(n.logger.info("Force download requested. Deleting cached Astro bundle..."),await(0,Fwi.rm)(a,{recursive:!0}))}let i="https://prod-local-preview-astro-bundle.s3.amazonaws.com/";if(i==null)throw new T({message:"Failed to connect to the docs preview server. Please contact support@buildwithfern.com",code:T.Code.InternalError});let o=hqe({astro:!0,cacheDir:r});if((await xer({bucketUrl:i,logger:n.logger,preferCached:!0,astro:!0,tryTar:!0,cacheDir:r})).type==="failure")if(await Vt(o))n.logger.warn("Falling back to cached Astro bundle...");else throw new T({message:"Failed to download the Astro docs preview bundle. Please reach out to support@buildwithfern.com.",code:T.Code.NetworkError});return await WSp(o)}async function WSp(e){let t=Be(e,Ae.of(XKg)),r=ZKg;if(await Vt(t)){let i=JSON.parse(await(0,Fwi.readFile)(t,"utf-8"));typeof i.entry=="string"&&(r=i.entry)}let n=Be(e,Ae.of(r));if(!await Vt(n))throw new T({message:`${e} does not contain the Astro preview server (missing ${r}).`,code:T.Code.UserError});return{root:e,entry:n}}function tJg({rendererPort:e,rendererHost:t,mirrorPort:r,basepath:n,reloadClients:i,lifetime:o}){return azs.default.createServer((s,a)=>{if(s.url===KSp){a.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-store",connection:"keep-alive"}),a.write(`: connected
|
|
4133
4133
|
|
|
4134
4134
|
`),i.add(a),s.on("close",()=>i.delete(a));return}o.requestStarted(),a.once("close",()=>o.requestFinished());let c=VSp(s.url,n),u=azs.default.request(c!=null?{host:"127.0.0.1",port:r,method:s.method,path:c,headers:s.headers}:{host:"127.0.0.1",port:e,method:s.method,path:s.url,headers:{...s.headers,[HSp]:t}},l=>{let p={...l.headers};if(!((p["content-type"]??"").includes("text/html")&&p["content-encoding"]==null)){a.writeHead(l.statusCode??502,p),l.pipe(a);return}let f=[];l.on("data",m=>f.push(m)),l.on("end",()=>{let m=Buffer.concat(f).toString("utf-8"),g=m.lastIndexOf("</body>"),A=g>=0?`${m.slice(0,g)}${qSp}${m.slice(g)}`:`${m}${qSp}`,y=Buffer.from(A,"utf-8");delete p["transfer-encoding"],p["content-length"]=y.byteLength.toString(),a.writeHead(l.statusCode??502,p),a.end(y)}),l.on("error",()=>a.destroy())});u.on("error",l=>{a.headersSent||a.writeHead(502,{"content-type":"text/plain"}),a.end(`Astro preview server unavailable: ${l.message}
|
|
4135
|
-
`)}),s.pipe(u)})}function rJg(){return new Promise((e,t)=>{let r=czs.default.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address(),i=typeof n=="object"&&n!=null?n.port:void 0;r.close(()=>i!=null?e(i):t(new Error("could not allocate a port")))})})}function nJg(e,t,r){let n=Date.now()+r;return new Promise((i,o)=>{let s=!1;t.on("exit",c=>{s=!0,o(new Error(`Astro preview server exited with code ${c} before becoming ready`))});let a=()=>{if(s)return;if(Date.now()>n){o(new Error("timed out waiting for the Astro preview server to become ready"));return}let c=czs.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}ct();Dt();var XSp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,JSp="docs.buildwithfern.com",YSp=62;function MWe(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),XSp.test(t)}function Jir({orgId:e,previewId:t}){let r=e$(t),n=`${e}-preview-${r}.${JSp}`;if(n.length<=YSp)return n;let i=`${e}-preview-`,o=YSp-i.length;if(o<8)throw new T({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:T.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${JSp}`}ct();WI();Ch();tr();I0();Dt();En();var zzs=require("child_process"),l1p=ye($Sp(),1),Qzs=ye(Dwi(),1),Mzs=ye(require("fs"),1),_zs=require("fs/promises"),p1p=ye(require("http"),1),f1p=ye(require("os"),1),Ywi=ye(require("path"),1);Dzs();WI();tr();var kzs=require("fs/promises");async function Fzs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:u}=e,l=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!l&&!p)return r;let d=n.config.translations?.defaultLocale,f=new Set([...Object.keys(i??{}),...Object.keys(s??{})]);for(let m of f){if(m===d)continue;let g=i?.[m]??{};try{let A=async le=>{let oe=To(c,le),me=Xn(c,Ae.of(`translations/${m}/${oe}`));return await Vt(me)?me:le},y=async le=>{let oe=await A(le),me=await(0,kzs.readFile)(oe,"utf-8"),Se=me.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return Se!=null?me.slice(Se[0].length):me},I=async le=>{let oe=await A(le);return(0,kzs.readFile)(oe,"utf-8")},x={};for(let[le,oe]of Object.entries(n.pages))oe!=null&&(x[le]=oe);for(let[le,oe]of Object.entries(g))try{let me=x[le],Se=Xn(c,Ae.of(le)),{markdown:Re}=await BF({markdown:oe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,markdownLoader:y}),ce=await A_({markdown:Re,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,fileLoader:I}),ue=y_({markdown:ce,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t}),Oe=rP(ue);Oe=f_(Oe,a,u,{absolutePathToMarkdownFile:Se,absolutePathToFernFolder:c},t),x[le]={markdown:Oe,rawMarkdown:Oe,editThisPageUrl:me?.editThisPageUrl,editThisPageLaunch:me?.editThisPageLaunch}}catch(me){t.logger.warn(`Failed to process translated page "${le}" for locale "${m}": ${String(me)}. Falling back to base page.`)}let v=OGe(n.config.root,g,t),S=o?.[m],B=n.config.announcement,R=n.config.navbarLinks;S!=null&&(v=BGe(v,S),B=RGe(S)??B,S.navbarLinks!=null&&(R=S.navbarLinks));let D=n.apis,O=s?.[m],z=O,Y;if(O!=null&&v!=null){let le=wGe(v,D,O);le.size>0&&(t.logger.warn(`Translated API definition(s) [${Array.from(le).join(", ")}] for locale "${m}" diverge from the default-locale spec (e.g. changed OpenAPI tag names, operationIds, or paths, or a missing/added endpoint), so they can't be fully matched to the navigation tree. Serving the default-locale API for those (localized sidebar titles are still applied where they can be matched). For fully localized API reference content, translate only human-readable text and keep tag names/operationIds/paths identical to the base spec.`),z=Object.fromEntries(Object.entries(O).filter(([oe])=>!le.has(oe)))),Y=new Set(Object.keys(O).filter(oe=>!le.has(oe)))}let ee=z!=null&&Object.keys(z).length>0?{...n.apis,...z}:n.apis;O!=null&&Object.keys(O).length>0&&v!=null&&(v=TGe(v,D,O,{rewritableApiIds:Y}));let se={...n,apis:ee,pages:x,config:{...n.config,root:v,announcement:B,navbarLinks:R}};r.set(m,se),t.logger.debug(`Computed translated definition for locale "${m}"`+(O!=null?` (with ${Object.keys(O).length} translated API(s))`:""))}catch(A){t.logger.warn(`Failed to compute translation for locale "${m}": ${String(A)}`)}}return r}tr();var c7=require("fs/promises"),i1p=require("os"),jzs=ye(require("path"),1),BYg=".fern",RYg="logs",Nzs=100*1024*1024;function DYg(){return"cli@5.183.
|
|
4135
|
+
`)}),s.pipe(u)})}function rJg(){return new Promise((e,t)=>{let r=czs.default.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address(),i=typeof n=="object"&&n!=null?n.port:void 0;r.close(()=>i!=null?e(i):t(new Error("could not allocate a port")))})})}function nJg(e,t,r){let n=Date.now()+r;return new Promise((i,o)=>{let s=!1;t.on("exit",c=>{s=!0,o(new Error(`Astro preview server exited with code ${c} before becoming ready`))});let a=()=>{if(s)return;if(Date.now()>n){o(new Error("timed out waiting for the Astro preview server to become ready"));return}let c=czs.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}ct();Dt();var XSp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,JSp="docs.buildwithfern.com",YSp=62;function MWe(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),XSp.test(t)}function Jir({orgId:e,previewId:t}){let r=e$(t),n=`${e}-preview-${r}.${JSp}`;if(n.length<=YSp)return n;let i=`${e}-preview-`,o=YSp-i.length;if(o<8)throw new T({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:T.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${JSp}`}ct();WI();Ch();tr();I0();Dt();En();var zzs=require("child_process"),l1p=ye($Sp(),1),Qzs=ye(Dwi(),1),Mzs=ye(require("fs"),1),_zs=require("fs/promises"),p1p=ye(require("http"),1),f1p=ye(require("os"),1),Ywi=ye(require("path"),1);Dzs();WI();tr();var kzs=require("fs/promises");async function Fzs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:u}=e,l=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!l&&!p)return r;let d=n.config.translations?.defaultLocale,f=new Set([...Object.keys(i??{}),...Object.keys(s??{})]);for(let m of f){if(m===d)continue;let g=i?.[m]??{};try{let A=async le=>{let oe=To(c,le),me=Xn(c,Ae.of(`translations/${m}/${oe}`));return await Vt(me)?me:le},y=async le=>{let oe=await A(le),me=await(0,kzs.readFile)(oe,"utf-8"),Se=me.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return Se!=null?me.slice(Se[0].length):me},I=async le=>{let oe=await A(le);return(0,kzs.readFile)(oe,"utf-8")},x={};for(let[le,oe]of Object.entries(n.pages))oe!=null&&(x[le]=oe);for(let[le,oe]of Object.entries(g))try{let me=x[le],Se=Xn(c,Ae.of(le)),{markdown:Re}=await BF({markdown:oe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,markdownLoader:y}),ce=await A_({markdown:Re,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,fileLoader:I}),ue=y_({markdown:ce,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t}),Oe=rP(ue);Oe=f_(Oe,a,u,{absolutePathToMarkdownFile:Se,absolutePathToFernFolder:c},t),x[le]={markdown:Oe,rawMarkdown:Oe,editThisPageUrl:me?.editThisPageUrl,editThisPageLaunch:me?.editThisPageLaunch}}catch(me){t.logger.warn(`Failed to process translated page "${le}" for locale "${m}": ${String(me)}. Falling back to base page.`)}let v=OGe(n.config.root,g,t),S=o?.[m],B=n.config.announcement,R=n.config.navbarLinks;S!=null&&(v=BGe(v,S),B=RGe(S)??B,S.navbarLinks!=null&&(R=S.navbarLinks));let D=n.apis,O=s?.[m],z=O,Y;if(O!=null&&v!=null){let le=wGe(v,D,O);le.size>0&&(t.logger.warn(`Translated API definition(s) [${Array.from(le).join(", ")}] for locale "${m}" diverge from the default-locale spec (e.g. changed OpenAPI tag names, operationIds, or paths, or a missing/added endpoint), so they can't be fully matched to the navigation tree. Serving the default-locale API for those (localized sidebar titles are still applied where they can be matched). For fully localized API reference content, translate only human-readable text and keep tag names/operationIds/paths identical to the base spec.`),z=Object.fromEntries(Object.entries(O).filter(([oe])=>!le.has(oe)))),Y=new Set(Object.keys(O).filter(oe=>!le.has(oe)))}let ee=z!=null&&Object.keys(z).length>0?{...n.apis,...z}:n.apis;O!=null&&Object.keys(O).length>0&&v!=null&&(v=TGe(v,D,O,{rewritableApiIds:Y}));let se={...n,apis:ee,pages:x,config:{...n.config,root:v,announcement:B,navbarLinks:R}};r.set(m,se),t.logger.debug(`Computed translated definition for locale "${m}"`+(O!=null?` (with ${Object.keys(O).length} translated API(s))`:""))}catch(A){t.logger.warn(`Failed to compute translation for locale "${m}": ${String(A)}`)}}return r}tr();var c7=require("fs/promises"),i1p=require("os"),jzs=ye(require("path"),1),BYg=".fern",RYg="logs",Nzs=100*1024*1024;function DYg(){return"cli@5.183.1"}var qWe=class{logFilePath=null;initialized=!1;sessionStartTime;consoleLogger;constructor(){this.sessionStartTime=Date.now()}async initialize(t,r){if(this.initialized)return;this.consoleLogger=t;let n=r??Be(Be($t.of((0,i1p.homedir)()),Ae.of(BYg)),Ae.of(RYg));await Vt(n)||await(0,c7.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Be(n,Ae.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${jzs.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
4136
4136
|
`);await(0,c7.writeFile)(this.logFilePath,s,"utf-8"),this.initialized=!0,this.enforceLogSizeLimit(n)}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
|
|
4137
4137
|
`;try{await(0,c7.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:DYg(),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)}async enforceLogSizeLimit(t){try{let n=(await(0,c7.readdir)(t)).filter(c=>c.endsWith(".log")),i=[];for(let c of n){let u=jzs.default.join(t,c);try{let l=await(0,c7.stat)(u);i.push({name:c,fullPath:u,size:l.size,mtimeMs:l.mtimeMs})}catch{}}let o=i.reduce((c,u)=>c+u.size,0),s=Math.round(o/1024/1024*100)/100,a=Nzs/1024/1024;if(o<=Nzs){this.consoleLogger?.debug(`Log directory size ${s} MB does not exceed ${a} MB cap`);return}this.consoleLogger?.info(`Rotating logs: total size ${s} MB exceeds ${a} MB cap`),i.sort((c,u)=>c.mtimeMs-u.mtimeMs);for(let c of i){if(o<=Nzs)break;if(!(this.logFilePath!=null&&c.fullPath===this.logFilePath))try{await(0,c7.unlink)(c.fullPath),o-=c.size}catch{}}}catch{}}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 Jwi={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function o1p(e){let t=kYg();if(t==null)return;let{port:r,debugLogger:n,getDocsLoadResponse:i,extractLocaleFromPath:o}=e,s=new Map;function a(u){let l=JSON.stringify(u),p=[];for(let[d]of s)try{d.send(l)}catch{p.push(d)}for(let d of p){let f=s.get(d);f&&(clearInterval(f.pingInterval),s.delete(d))}}let c=t.serve({port:r,async fetch(u,l){if(u.method==="OPTIONS")return new Response(null,{status:204,headers:Jwi});let p=new URL(u.url);if(u.headers.get("upgrade")?.toLowerCase()==="websocket"){l.upgrade(u,{data:{connectionId:`${Date.now()}`}});return}if(u.method==="POST"&&p.pathname==="/v2/registry/docs/load-with-url")try{let f=await u.json(),m=o?.(f?.url);return new Response(JSON.stringify(i(m)),{headers:{"Content-Type":"application/json",...Jwi}})}catch{return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...Jwi}})}let d=/^\/_local\/(.*)/.exec(p.pathname);return u.method==="GET"&&d!=null?new Response(t.file(`/${d[1]}`),{headers:Jwi}):new Response("Not Found",{status:404})},websocket:{open(u){let{connectionId:l}=u.data,p=setInterval(()=>{let d=s.get(u);if(!d)return;let f=Date.now();if(f-d.lastPong>9e4){u.close();return}try{u.send(JSON.stringify({type:"ping",timestamp:f}))}catch{u.close()}},3e4);s.set(u,{pingInterval:p,lastPong:Date.now()});try{u.send(JSON.stringify({type:"connected",connectionId:l}))}catch{}},message(u,l){try{let p=JSON.parse(l.toString());if(p.type==="pong"){let d=s.get(u);d&&(d.lastPong=Date.now())}else qWe.isMetricsMessage(p)&&n.logFrontendMetrics(p)}catch{}},close(u){let l=s.get(u);l&&(clearInterval(l.pingInterval),s.delete(u))}}});return{sendData:a,stop:u=>c.stop(u)}}function kYg(){return globalThis.Bun}var s1p=require("fs"),a1p=ye(require("path"),1),FYg=`"use strict";
|
|
4138
4138
|
|
|
@@ -4453,7 +4453,7 @@ ${n}
|
|
|
4453
4453
|
|
|
4454
4454
|
Add a 'docs:' section to your fern.yml to get started.`,code:T.Code.ConfigError});let i=n.docs.raw.libraries;if(i==null)throw new T({message:`No libraries configured in docs.yml.
|
|
4455
4455
|
|
|
4456
|
-
Add a 'libraries' section to configure library documentation.`,code:T.Code.ConfigError});let o=await t.getTokenOrPrompt();await t.verifyOrgAccess({organization:n.org,token:o});let s=n.docs.absoluteFilePath??n.absoluteFilePath??t.cwd,a=$t.of(Zr(s)),c=new Ud({context:t,logLevel:Zn.Info});await lar({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:TP,docsConfig:n.docs.raw})}};function UVs(e){let t=new _Vs;di(e,"generate","[Beta] Generate MDX documentation from library source code. Requires 'libraries' config in docs.yml.",(r,n)=>t.handle(r,n),r=>r.option("library",{type:"string",description:"Name of a specific library defined in docs.yml to generate docs for"}))}function VVs(e){zA({cli:e,name:"md",subcommands:[UVs,fVs]})}Dt();function hDi(e,t,r,n,i,o){e.command(t,r,s=>{for(let a of o)a(s);return s.command("$0",!1,a=>{let c=a.version(!1);return i!=null?i(c):c},Dan(n)),s.version(!1).usage(r)})}ct();WI();Dt();En();ct();Dt();var gDi=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,previewId:n,skipUpload:i}){let o=new Ud({context:this.context,task:this.task});try{let s=await xir({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:o,token:this.token,instanceUrl:t,preview:r,previewId:n,disableTemplates:void 0,skipUpload:i,cliVersion:"5.183.
|
|
4456
|
+
Add a 'libraries' section to configure library documentation.`,code:T.Code.ConfigError});let o=await t.getTokenOrPrompt();await t.verifyOrgAccess({organization:n.org,token:o});let s=n.docs.absoluteFilePath??n.absoluteFilePath??t.cwd,a=$t.of(Zr(s)),c=new Ud({context:t,logLevel:Zn.Info});await lar({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:TP,docsConfig:n.docs.raw})}};function UVs(e){let t=new _Vs;di(e,"generate","[Beta] Generate MDX documentation from library source code. Requires 'libraries' config in docs.yml.",(r,n)=>t.handle(r,n),r=>r.option("library",{type:"string",description:"Name of a specific library defined in docs.yml to generate docs for"}))}function VVs(e){zA({cli:e,name:"md",subcommands:[UVs,fVs]})}Dt();function hDi(e,t,r,n,i,o){e.command(t,r,s=>{for(let a of o)a(s);return s.command("$0",!1,a=>{let c=a.version(!1);return i!=null?i(c):c},Dan(n)),s.version(!1).usage(r)})}ct();WI();Dt();En();ct();Dt();var gDi=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,previewId:n,skipUpload:i}){let o=new Ud({context:this.context,task:this.task});try{let s=await xir({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:o,token:this.token,instanceUrl:t,preview:r,previewId:n,disableTemplates:void 0,skipUpload:i,cliVersion:"5.183.1",loginCommand:"fern auth login"});return o.getResult()===Qf.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:In(s)}}}};ct();En();var cDt=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(`
|
|
4457
4457
|
`),this.stream.write(`${de.cyan("\u25C6")} ${de.bold(t.title)}
|
|
4458
4458
|
`),t.subtitle!=null&&this.stream.write(` ${de.dim(t.subtitle)}
|
|
4459
4459
|
`),this.stream.write(`
|
|
@@ -5147,7 +5147,7 @@ ${r}`}function Uji(e){let t=this,{emitParseErrors:r,...n}={...t.data("settings")
|
|
|
5147
5147
|
`),g="";return c&&(g=l.style.error(c)),[`${p} ${f} ${s}`,[m,g].filter(Boolean).join(`
|
|
5148
5148
|
`)]});var eay=jx((e,t)=>{let{validate:r=()=>!0}=e,n=fv(e.theme),[i,o]=vu("idle"),[s,a]=vu(),[c,u]=vu(""),l=Fx({status:i,theme:n});Nx(async(g,A)=>{if(i==="idle")if(kx(g)){let y=c;o("loading");let I=await r(y);I===!0?(u(y),o("done"),t(y)):(A.write(c),a(I||"You must provide a valid value"),o("idle"))}else u(A.line),a(void 0)});let p=n.style.message(e.message,i),d="",f;e.mask?d=(typeof e.mask=="string"?e.mask:"*").repeat(c.length):i!=="done"&&(f=`${n.style.help("[input is masked]")}${r2t}`),i==="done"&&(d=n.style.answer(d));let m="";return s&&(m=n.style.error(s)),[[l,p,e.mask?d:f].join(" "),m]});var lJe=ye(t1(),1);var tay={icon:{cursor:xS.pointer},style:{disabled:e=>lJe.default.dim(`- ${e}`),searchTerm:e=>lJe.default.cyan(e),description:e=>lJe.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${lJe.default.bold(t)} ${lJe.default.dim(r)}`).join(lJe.default.dim(" \u2022 "))},helpMode:"always"};function fia(e){return!Yd.isSeparator(e)&&!e.disabled}function ray(e){return e.map(t=>{if(Yd.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};return t.description&&(n.description=t.description),n})}var nay=jx((e,t)=>{let{pageSize:r=7,validate:n=()=>!0}=e,i=fv(tay,e.theme),[o,s]=vu("loading"),[a,c]=vu(""),[u,l]=vu([]),[p,d]=vu(),f=Fx({status:o,theme:i}),m=e3(()=>{let z=u.findIndex(fia),Y=u.findLastIndex(fia);return{first:z,last:Y}},[u]),[g=m.first,A]=vu();xU(()=>{let z=new AbortController;return s("loading"),d(void 0),(async()=>{try{let te=await e.source(a||void 0,{signal:z.signal});z.signal.aborted||(A(void 0),d(void 0),l(ray(te)),s("idle"))}catch(te){!z.signal.aborted&&te instanceof Error&&d(te.message)}})(),()=>{z.abort()}},[a]);let y=u[g];Nx(async(z,Y)=>{if(kx(z))if(y){s("loading");let te=await n(y.value);s("idle"),te===!0?(s("done"),t(y.value)):y.name===a?d(te||"You must provide a valid value"):(Y.write(y.name),c(y.name))}else Y.write(a);else if(s0e(z)&&y)Y.clearLine(0),Y.write(y.name),c(y.name);else if(o!=="loading"&&(HR(z)||$6(z))){if(Y.clearLine(0),HR(z)&&g!==m.first||$6(z)&&g!==m.last){let te=HR(z)?-1:1,ee=g;do ee=(ee+te+u.length)%u.length;while(!fia(u[ee]));A(ee)}}else c(Y.line)});let I=i.style.message(e.message,o),x;if(i.helpMode!=="never")if(e.instructions){let{pager:z,navigation:Y}=e.instructions;x=i.style.help(u.length>r?z:Y)}else x=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let v=sJe({items:u,active:g,renderItem({item:z,isActive:Y}){if(Yd.isSeparator(z))return` ${z.separator}`;if(z.disabled){let se=typeof z.disabled=="string"?z.disabled:"(disabled)";return i.style.disabled(`${z.name} ${se}`)}let te=Y?i.style.highlight:se=>se,ee=Y?i.icon.cursor:" ";return te(`${ee} ${z.name}`)},pageSize:r,loop:!1}),S;p?S=i.style.error(p):u.length===0&&a!==""&&o==="idle"&&(S=i.style.error("No results found"));let B;if(o==="done"&&y)return[f,I,i.style.answer(y.short)].filter(Boolean).join(" ").trimEnd();B=i.style.searchTerm(a);let R=y?.description,D=[f,I,B].filter(Boolean).join(" ").trimEnd(),O=[S??v," ",R?i.style.description(R):"",x].filter(Boolean).join(`
|
|
5149
5149
|
`).trimEnd();return[D,O]});var i2t=ye(t1(),1);var iay={icon:{cursor:xS.pointer},style:{disabled:e=>i2t.default.dim(`- ${e}`),description:e=>i2t.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${i2t.default.bold(t)} ${i2t.default.dim(r)}`).join(i2t.default.dim(" \u2022 "))},helpMode:"always",indexMode:"hidden",keybindings:[]};function n2t(e){return!Yd.isSeparator(e)&&!e.disabled}function oay(e){return e.map(t=>{if(Yd.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};return t.description&&(n.description=t.description),n})}var dia=jx((e,t)=>{let{loop:r=!0,pageSize:n=7}=e,i=fv(iay,e.theme),{keybindings:o}=i,[s,a]=vu("idle"),c=Fx({status:s,theme:i}),u=oJe(),l=!o.includes("vim"),p=e3(()=>oay(e.choices),[e.choices]),d=e3(()=>{let R=p.findIndex(n2t),D=p.findLastIndex(n2t);if(R===-1)throw new rpe("[select prompt] No selectable choices. All choices are disabled.");return{first:R,last:D}},[p]),f=e3(()=>"default"in e?p.findIndex(R=>n2t(R)&&R.value===e.default):-1,[e.default,p]),[m,g]=vu(f===-1?d.first:f),A=p[m];Nx((R,D)=>{if(clearTimeout(u.current),kx(R))a("done"),t(A.value);else if(HR(R,o)||$6(R,o)){if(D.clearLine(0),r||HR(R,o)&&m!==d.first||$6(R,o)&&m!==d.last){let O=HR(R,o)?-1:1,z=m;do z=(z+O+p.length)%p.length;while(!n2t(p[z]));g(z)}}else if(plr(R)&&!Number.isNaN(Number(D.line))){let O=Number(D.line)-1,z=-1,Y=p.findIndex(ee=>Yd.isSeparator(ee)?!1:(z++,z===O)),te=p[Y];te!=null&&n2t(te)&&g(Y),u.current=setTimeout(()=>{D.clearLine(0)},700)}else if(rJe(R))D.clearLine(0);else if(l){let O=D.line.toLowerCase(),z=p.findIndex(Y=>Yd.isSeparator(Y)||!n2t(Y)?!1:Y.name.toLowerCase().startsWith(O));z!==-1&&g(z),u.current=setTimeout(()=>{D.clearLine(0)},700)}}),xU(()=>()=>{clearTimeout(u.current)},[]);let y=i.style.message(e.message,s),I;if(i.helpMode!=="never")if(e.instructions){let{pager:R,navigation:D}=e.instructions;I=i.style.help(p.length>n?R:D)}else I=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let x=0,v=sJe({items:p,active:m,renderItem({item:R,isActive:D,index:O}){if(Yd.isSeparator(R))return x++,` ${R.separator}`;let z=i.indexMode==="number"?`${O+1-x}. `:"";if(R.disabled){let ee=typeof R.disabled=="string"?R.disabled:"(disabled)";return i.style.disabled(`${z}${R.name} ${ee}`)}let Y=D?i.style.highlight:ee=>ee,te=D?i.icon.cursor:" ";return Y(`${te} ${z}${R.name}`)},pageSize:n,loop:r});if(s==="done")return[c,y,i.style.answer(A.short)].filter(Boolean).join(" ");let{description:S}=A;return`${[[c,y].filter(Boolean).join(" "),v," ",S?i.style.description(S):"",I].filter(Boolean).join(`
|
|
5150
|
-
`).trimEnd()}${r2t}`});En();qi();var npe={GENERATION_STARTED:"generation_started",GENERATION_COMPLETED:"generation_completed",GENERATION_FAILED:"generation_failed",VERIFICATION_FAILED:"verification_failed",SDK_PR_CREATED:"sdk_pr_created",UPGRADE_APPLIED:"upgrade_applied",MAJOR_VERSION_BUMP:"major_version_bump"},say={[npe.GENERATION_STARTED]:!1,[npe.GENERATION_COMPLETED]:!1,[npe.GENERATION_FAILED]:!0,[npe.VERIFICATION_FAILED]:!0,[npe.SDK_PR_CREATED]:!1,[npe.UPGRADE_APPLIED]:!1,[npe.MAJOR_VERSION_BUMP]:!1};function BYp(e){return say[e]}function RYp(e,t){return{automation_mode:!0,surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function DYp(e,t){function r(i,o,s){s!=null&&(i[o]=s)}let n={surface:"cli",automation_mode:"true"};return r(n,"event",e.event),r(n,"action",t.action),r(n,"run_id",t.run_id),r(n,"org",t.org),r(n,"config_repo",t.config_repo),r(n,"trigger",t.trigger),r(n,"error_code",e.errorCode??"none"),n}function kYp(e,t){return{github_run_id:t.github_run_id,github_run_url:t.github_run_url,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,cli_version:t.cli_version,...e.attributes??{}}}function FYp(e,t){return{event:e.event,timestamp:new Date().toISOString(),surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function NYp(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?npe.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?npe.VERIFICATION_FAILED:npe.GENERATION_FAILED}var aay="",cay="FERN_AUTOMATION_EVENTS_ORIGIN",uay=3e3,xzi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[cay]??aay)),e.instance}constructor(t){this.origin=t}resolveEndpoint(){if(this.origin.length!==0)return`${this.origin.replace(/\/$/,"")}/v1/automation/events`}post(t,r){this.inflight.push(this.send(t,r))}async shutdown(){let t=this.inflight;this.inflight=[],t.length>0&&await Promise.allSettled(t)}async send(t,r){let n=this.resolveEndpoint();if(n==null)return;let i=new AbortController,o=setTimeout(()=>i.abort(),uay);try{let s={"content-type":"application/json"},a=await OM();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(FYp(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function jYp(){let{fern_run_id:e,github_run_id:t}=zpe();return{action:process.env.FERN_ACTION,run_id:e,github_run_id:t,github_run_url:process.env.FERN_GITHUB_RUN_URL,org:void 0,config_repo:process.env.FERN_CONFIG_REPO,config_commit_sha:process.env.FERN_CONFIG_COMMIT_SHA,config_branch:process.env.FERN_CONFIG_BRANCH,config_pr_number:process.env.FERN_CONFIG_PR_NUMBER,trigger:process.env.GITHUB_EVENT_NAME,cli_version:"5.183.
|
|
5150
|
+
`).trimEnd()}${r2t}`});En();qi();var npe={GENERATION_STARTED:"generation_started",GENERATION_COMPLETED:"generation_completed",GENERATION_FAILED:"generation_failed",VERIFICATION_FAILED:"verification_failed",SDK_PR_CREATED:"sdk_pr_created",UPGRADE_APPLIED:"upgrade_applied",MAJOR_VERSION_BUMP:"major_version_bump"},say={[npe.GENERATION_STARTED]:!1,[npe.GENERATION_COMPLETED]:!1,[npe.GENERATION_FAILED]:!0,[npe.VERIFICATION_FAILED]:!0,[npe.SDK_PR_CREATED]:!1,[npe.UPGRADE_APPLIED]:!1,[npe.MAJOR_VERSION_BUMP]:!1};function BYp(e){return say[e]}function RYp(e,t){return{automation_mode:!0,surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function DYp(e,t){function r(i,o,s){s!=null&&(i[o]=s)}let n={surface:"cli",automation_mode:"true"};return r(n,"event",e.event),r(n,"action",t.action),r(n,"run_id",t.run_id),r(n,"org",t.org),r(n,"config_repo",t.config_repo),r(n,"trigger",t.trigger),r(n,"error_code",e.errorCode??"none"),n}function kYp(e,t){return{github_run_id:t.github_run_id,github_run_url:t.github_run_url,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,cli_version:t.cli_version,...e.attributes??{}}}function FYp(e,t){return{event:e.event,timestamp:new Date().toISOString(),surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function NYp(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?npe.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?npe.VERIFICATION_FAILED:npe.GENERATION_FAILED}var aay="",cay="FERN_AUTOMATION_EVENTS_ORIGIN",uay=3e3,xzi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[cay]??aay)),e.instance}constructor(t){this.origin=t}resolveEndpoint(){if(this.origin.length!==0)return`${this.origin.replace(/\/$/,"")}/v1/automation/events`}post(t,r){this.inflight.push(this.send(t,r))}async shutdown(){let t=this.inflight;this.inflight=[],t.length>0&&await Promise.allSettled(t)}async send(t,r){let n=this.resolveEndpoint();if(n==null)return;let i=new AbortController,o=setTimeout(()=>i.abort(),uay);try{let s={"content-type":"application/json"},a=await OM();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(FYp(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function jYp(){let{fern_run_id:e,github_run_id:t}=zpe();return{action:process.env.FERN_ACTION,run_id:e,github_run_id:t,github_run_url:process.env.FERN_GITHUB_RUN_URL,org:void 0,config_repo:process.env.FERN_CONFIG_REPO,config_commit_sha:process.env.FERN_CONFIG_COMMIT_SHA,config_branch:process.env.FERN_CONFIG_BRANCH,config_pr_number:process.env.FERN_CONFIG_PR_NUMBER,trigger:process.env.GITHUB_EVENT_NAME,cli_version:"5.183.1"}}function zYp(){return process.env.FERN_AUTOMATION==="true"}var lay=3e3,Szi=class{constructor(t,r=xzi.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=jYp()}reporter;automationEventApiClient;context;setOrganization(t){this.context={...this.context,org:t}}emit(t,r){let n=this.captureSentryForFailure({event:t,context:this.context,error:r?.error}),i=n==null?t:{...t,attributes:{...t.attributes??{},sentry_event_id:n}};this.capturePostHogEvent({event:i,context:this.context}),this.captureAutomationEventApiEvent(i,this.context)}async flush(){let t;try{await Promise.race([this.automationEventApiClient.shutdown(),new Promise(r=>{t=setTimeout(r,lay)})])}finally{clearTimeout(t)}}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:RYp(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!BYp(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:DYp(t,r),context:{automation:kYp(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Dt();function wzi(e,t,r){if(t instanceof Qc)return;let n=ZMe(t,r?.code),i=r?.argv??process.argv,o=i.join(" "),s=r?.message??(t instanceof Error?t.message:void 0)??"",a=t??new T({message:s,code:n});zYp()?fay(i,e,n,s,a):pay(e,o,n,a)}function pay(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),QQt(r)&&e.captureException(n,{tags:{"error.code":r}})}function fay(e,t,r,n,i){let o=NYp(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Dt();function pJe(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function Tzi({cliName:e,packageVersion:t,isLocal:r}){return pJe()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var Ozi=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(Tzi(r)&&n!=null&&n.length>0){let i="production";if(i==null||i.length===0)throw new T({message:"SENTRY_ENVIRONMENT must be set when SENTRY_DSN is configured",code:T.Code.ConfigError});this.sentry=BQt({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[pXe(),hEe(),gEe(),$0e(),mEe()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),RQt()}}captureException(t,r){if(this.sentry!=null)try{let n=r?.tags,i=r?.context,o=n!=null&&Object.keys(n).length>0,s=i!=null&&Object.values(i).some(a=>a!=null);return!o&&!s?this.sentry.captureException(t):KP(a=>{if(o&&a.setTags(n),i!=null)for(let[c,u]of Object.entries(i))u!=null&&a.setContext(c,u);return this.sentry?.captureException(t,void 0,a)})}catch{return}}async flush(){this.sentry!=null&&await Promise.resolve(this.sentry.flush(2e3)).catch(()=>{})}};Dt();var Pzi=class{originalWrite;redirected=!1;redirect(){if(this.redirected)throw new T({message:"StdoutRedirector: already redirected \u2014 did you forget to restore()?",code:T.Code.InternalError});this.originalWrite=process.stdout.write,process.stdout.write=process.stderr.write.bind(process.stderr),this.redirected=!0}restore(){!this.redirected||this.originalWrite==null||(process.stdout.write=this.originalWrite,this.originalWrite=void 0,this.redirected=!1)}async withRedirect(t){this.redirect();try{return await t()}finally{this.restore()}}};$me();ct();Ky();Dt();En();var hlr=class{result=Qf.Success;lastFailureMessage=void 0;logImmediately;logPrefix;title;subtasks=[];shouldBufferLogs;bufferedLogs=[];status="notStarted";onResult;instrumentPostHogEventImpl;captureExceptionImpl;emitAutomationTelemetryEventImpl;constructor({logImmediately:t,logPrefix:r,title:n,takeOverTerminal:i,onResult:o,shouldBufferLogs:s,instrumentPostHogEvent:a,captureException:c,emitAutomationTelemetryEvent:u}){this.logImmediately=t,this.logPrefix=r??"",this.title=n,this.takeOverTerminal=i,this.onResult=o,this.shouldBufferLogs=s,this.instrumentPostHogEventImpl=a,this.captureExceptionImpl=c,this.emitAutomationTelemetryEventImpl=u}start(){return this.status="running",this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.status="finished",this.flushLogs(),this.onResult?.(this.getResult()))}isFinished(){return this.status==="finished"}takeOverTerminal;failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),this.finish(),new Qc(t??(r instanceof Qc?r.failureMessage:this.lastFailureMessage))}failWithoutThrowing(t,r,n){this.result=Qf.Failure,!(r instanceof Qc)&&(t!=null&&(this.lastFailureMessage=t),Nqt({message:t,error:r,logger:this.logger}),wzi(this,r,{...n,message:t}))}getLastFailureMessage(){return this.lastFailureMessage}captureException(t,r){return this.captureExceptionImpl?.(t,r)}emitAutomationTelemetryEvent(t,r){this.emitAutomationTelemetryEventImpl(t,r)}getResult(){return this.result}instrumentPostHogEvent(t){this.instrumentPostHogEventImpl(t)}logAtLevel(t,...r){this.logAtLevelWithOverrides(t,r)}logAtLevelWithOverrides(t,r,n={}){this.log({parts:r,level:t,time:new Date,...n})}log(t){this.bufferedLogs.push({...t,prefix:this.logPrefix}),this.shouldBufferLogs||this.flushLogs()}flushLogs(){this.logImmediately(this.bufferedLogs),this.bufferedLogs=[]}logger=pI(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new mia({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${de.blackBright(t)} `,takeOverTerminal:this.takeOverTerminal,onResult:this.onResult,shouldBufferLogs:this.shouldBufferLogs,instrumentPostHogEvent:i=>this.instrumentPostHogEventImpl(i),captureException:this.captureExceptionImpl,emitAutomationTelemetryEvent:this.emitAutomationTelemetryEventImpl});return this.subtasks.push(n),n}async runInteractiveTask(t,r){let n=this.addInteractiveTask(t).start();try{await r(n)}catch(o){n.failWithoutThrowing(void 0,o)}finally{n.finish()}let i=n.getResult()===Qf.Success;return i||(this.lastFailureMessage=n.getLastFailureMessage()??this.lastFailureMessage),i}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
|
|
5151
5151
|
`)}},mia=class extends hlr{name;subtitle;constructor({name:t,subtitle:r,...n}){super(n),this.name=t,this.subtitle=r}start(){return super.start(),this.logAtLevelWithOverrides(Zn.Info,["Started."],{omitOnTTY:!0}),this.flushLogs(),this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.result===Qf.Success?this.logAtLevelWithOverrides(Zn.Info,["Finished."],{omitOnTTY:!0}):this.logAtLevelWithOverrides(Zn.Error,["Failed."],{omitOnTTY:!0}),super.finish())}setSubtitle(t){this.subtitle=t}print({spinner:t}){let r=[this.name];return this.subtitle!=null&&r.push(de.dim(this.subtitle)),r.push(...this.subtasks.map(n=>n.print({spinner:t}))),Jz({prefix:this.getIcon({spinner:t}),content:r.join(`
|
|
5152
5152
|
`)})}printInteractiveTasks({spinner:t}){return this.print({spinner:t})}getIcon({spinner:t}){let r=this.subtasks.length>0;switch(this.status){case"notStarted":return r?de.dim("\u25B8 "):de.dim("\u25E6 ");case"running":return r?de.cyan("\u25BE "):t;case"finished":switch(this.getResult()){case Qf.Success:return r?de.green("\u25BE "):de.green("\u2713 ");case Qf.Failure:return r?de.red("\u25BE "):de.red("x ")}}}getResult(){if(this.result===Qf.Failure)return Qf.Failure;for(let t of this.subtasks)if(t.getResult()===Qf.Failure)return Qf.Failure;return Qf.Success}};Dt();var QYp=ye(tUe(),1);En();function MYp(e){return e.filter(t=>t.isUpgradeAvailable).length>0}function day(e){return(e.cliUpgradeInfo?.isUpgradeAvailable??!1)||MYp(e.generatorUpgradeInfo)}async function LYp({cliEnvironment:e,upgradeInfo:t}){if(!day(t)||e.packageVersion==t.cliUpgradeInfo?.latestVersion)return;let r=`${de.underline("Upgrades available")}
|
|
5153
5153
|
|
|
@@ -5156,7 +5156,7 @@ ${r}`}function Uji(e){let t=this,{emitParseErrors:r,...n}={...t.data("settings")
|
|
|
5156
5156
|
Run ${de.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
|
|
5157
5157
|
Run ${de.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),idt(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function hia({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!MYp(e))return;let i=t??"",o=e.filter(a=>a.isUpgradeAvailable);r!=null&&(o=o.slice(0,r+1));let s=o.sort((a,c)=>a.generatorName.localeCompare(c.generatorName)||a.currentVersion.localeCompare(c.currentVersion));for(let a of s)i+=`
|
|
5158
5158
|
${await may(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+de.dim(a.currentVersion)+de.reset(" \u2192 ")+de.green(a.latestVersion);return i+=`
|
|
5159
|
-
`,n?idt(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function may(e){let r=await new QYp.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new T({message:`Generator ${e} not found`,code:T.Code.ConfigError});return r.body.displayName}ai();lhe();Dt();var glr=ye(Wy(),1);function o2t(e){let t;return()=>(t??=e.runTask(r=>Af(r)),t)}function Bzi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!_Yp(t)||!_Yp(r))throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError});try{return t===r?0:Jw(t,r)?1:Jw(r,t)?-1:0}catch{let n=glr.default.valid(t),i=glr.default.valid(r);if(n!=null&&i!=null)return Math.sign(glr.default.compare(n,i));throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError})}}function _Yp(e){if(e==="latest"||glr.default.valid(e)!=null)return!0;try{return yJ(e),!0}catch{return!1}}async function Rzi({generatorId:e,currentVersion:t,includeMajor:r,channel:n,organization:i,getToken:o,context:s}){if(n!=null)throw new Error(`SDK Gen API generator version discovery does not support the requested upgrade channel "${n}". Remove --channel to use executable index versions; FDR channel metadata is used only when the ${mnr} feature flag is off for this organization.`);let a=CNe();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=Zv(e);if(c==null)return s.logger.error(`SDK Gen API cannot discover versions for unsupported generator ${e}. Use a canonical first-party SDK generator name.`),{};let u=await o(),l=await Uxs({origin:a,organization:i,token:u,generatorId:e,language:c,currentVersion:t,includeMajor:r});return l.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${l.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:l.compatibleVersion,withheldMajorVersion:l.withheldMajorVersion}}async function hay({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,c=o2t(e);if(a.length===1){let l={type:"singleApi",versions:{}};return await UYp({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{l.versions[d]==null&&(l.versions[d]={});let g=q_e(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await GYp({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:c,context:m});A!=null&&(l.versions[d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),l}let u={type:"multiApi",versions:{}};return await UYp({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(l,p,d,f)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][p]==null&&(u.versions[l][p]={});let m=q_e(d.name);if(m==null){f.logger.debug(`Skipping unknown generator: ${d.name}`);return}let g=await GYp({generatorName:d.name,normalizedGeneratorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:d.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:c,context:f});g!=null&&(u.versions[l][p][d.name]={previousVersion:d.version,latestVersion:g})},generatorFilter:r,groupFilter:n}),u}async function UYp({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 C4({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?ag(n):void 0;for(let u of a.groups)if(!(i!=null&&u.groupName!==i))for(let l of u.generators)c!=null&&l.name!==c||await r(o.workspaceName,u.groupName,l,s)})}))}function VYp(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 c=Bzi({generatorId:s,candidateVersion:a.latestVersion,currentVersion:a.previousVersion})===1;r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function GYp({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:u}){return n==="latest"?"latest":await gay({organization:s,generatorName:ag(e),skipFeatureFlagRequest:a})?(await Rzi({generatorId:ag(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:u})).compatibleVersion:HB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:u})}async function Dzi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await hay({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[u,l]of Object.entries(c.versions))a.push(...VYp(l,u,t.logger));else a.push(...VYp(c.versions,void 0,t.logger))}return a}async function gay({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?ERs({organization:e,generatorName:t})??!1:tOt({organization:e,generatorName:t})}ct();Dt();Ozr();async function a0e({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await H6e(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new T({message:`Failed to resolve latest CLI version: ${Ti(r)}`,code:T.Code.NetworkError})}}var qYp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],kzi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Zn.Info;isLocal;stdoutRedirector=new Pzi;jsonMode=!1;static async create(t,r,{isLocal:n}){let i=await tJt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new Xqt(t,r),this.isLocal=n??!1,this.posthogManager=i;let o=this.getPackageName(),s=this.getPackageVersion(),a=this.getCliName();(o==null||s==null||a==null)&&this.exitProgram(),this.environment={packageName:o,packageVersion:s,cliName:a},this.sentryClient=new Ozi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new Szi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.183.
|
|
5159
|
+
`,n?idt(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function may(e){let r=await new QYp.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new T({message:`Generator ${e} not found`,code:T.Code.ConfigError});return r.body.displayName}ai();lhe();Dt();var glr=ye(Wy(),1);function o2t(e){let t;return()=>(t??=e.runTask(r=>Af(r)),t)}function Bzi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!_Yp(t)||!_Yp(r))throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError});try{return t===r?0:Jw(t,r)?1:Jw(r,t)?-1:0}catch{let n=glr.default.valid(t),i=glr.default.valid(r);if(n!=null&&i!=null)return Math.sign(glr.default.compare(n,i));throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError})}}function _Yp(e){if(e==="latest"||glr.default.valid(e)!=null)return!0;try{return yJ(e),!0}catch{return!1}}async function Rzi({generatorId:e,currentVersion:t,includeMajor:r,channel:n,organization:i,getToken:o,context:s}){if(n!=null)throw new Error(`SDK Gen API generator version discovery does not support the requested upgrade channel "${n}". Remove --channel to use executable index versions; FDR channel metadata is used only when the ${mnr} feature flag is off for this organization.`);let a=CNe();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=Zv(e);if(c==null)return s.logger.error(`SDK Gen API cannot discover versions for unsupported generator ${e}. Use a canonical first-party SDK generator name.`),{};let u=await o(),l=await Uxs({origin:a,organization:i,token:u,generatorId:e,language:c,currentVersion:t,includeMajor:r});return l.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${l.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:l.compatibleVersion,withheldMajorVersion:l.withheldMajorVersion}}async function hay({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,c=o2t(e);if(a.length===1){let l={type:"singleApi",versions:{}};return await UYp({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{l.versions[d]==null&&(l.versions[d]={});let g=q_e(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await GYp({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:c,context:m});A!=null&&(l.versions[d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),l}let u={type:"multiApi",versions:{}};return await UYp({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(l,p,d,f)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][p]==null&&(u.versions[l][p]={});let m=q_e(d.name);if(m==null){f.logger.debug(`Skipping unknown generator: ${d.name}`);return}let g=await GYp({generatorName:d.name,normalizedGeneratorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:d.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:c,context:f});g!=null&&(u.versions[l][p][d.name]={previousVersion:d.version,latestVersion:g})},generatorFilter:r,groupFilter:n}),u}async function UYp({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 C4({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?ag(n):void 0;for(let u of a.groups)if(!(i!=null&&u.groupName!==i))for(let l of u.generators)c!=null&&l.name!==c||await r(o.workspaceName,u.groupName,l,s)})}))}function VYp(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 c=Bzi({generatorId:s,candidateVersion:a.latestVersion,currentVersion:a.previousVersion})===1;r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function GYp({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:u}){return n==="latest"?"latest":await gay({organization:s,generatorName:ag(e),skipFeatureFlagRequest:a})?(await Rzi({generatorId:ag(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:u})).compatibleVersion:HB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:u})}async function Dzi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await hay({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[u,l]of Object.entries(c.versions))a.push(...VYp(l,u,t.logger));else a.push(...VYp(c.versions,void 0,t.logger))}return a}async function gay({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?ERs({organization:e,generatorName:t})??!1:tOt({organization:e,generatorName:t})}ct();Dt();Ozr();async function a0e({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await H6e(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new T({message:`Failed to resolve latest CLI version: ${Ti(r)}`,code:T.Code.NetworkError})}}var qYp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],kzi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Zn.Info;isLocal;stdoutRedirector=new Pzi;jsonMode=!1;static async create(t,r,{isLocal:n}){let i=await tJt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new Xqt(t,r),this.isLocal=n??!1,this.posthogManager=i;let o=this.getPackageName(),s=this.getPackageVersion(),a=this.getCliName();(o==null||s==null||a==null)&&this.exitProgram(),this.environment={packageName:o,packageVersion:s,cliName:a},this.sentryClient=new Ozi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new Szi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.183.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${de.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new Qc(t??(r instanceof Qc?r.failureMessage:r!=null?In(r):void 0))}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof Qc)&&(Nqt({message:t,error:r,logger:this.logger}),wzi(this,r,{...n,message:t}))}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}get isTTY(){return this.ttyAwareLogger.isTTY}writeJsonToStdout(t){this.writeTextToStdout(JSON.stringify(t,null,2)+`
|
|
5160
5160
|
`)}writeTextToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(t),this.jsonMode&&this.stdoutRedirector.redirect()}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish();try{await Promise.all([this.posthogManager.flush(),nes()])}catch{}await this.sentryClient.flush(),await this.automationTelemetryManager.flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable({skipFeatureFlagRequest:!0}),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await LYp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
5161
5161
|
`)||(r+=`
|
|
5162
5162
|
`),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=q9i(t.map(n=>n.type==="docs"?"docs":n.workspaceName??"api"),n=>n.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t,this.automationTelemetryManager.setOrganization(t.config.organization)}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 hlr(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){let s=o instanceof Qc?o.failureMessage??n.getLastFailureMessage():In(o);throw n.failWithoutThrowing(void 0,o),new Qc(s)}finally{n.finish()}return i}instrumentPostHogEvent(t){this.isLocal||this.posthogManager.sendEvent(t)}instrumentPostHogAutomationEvent(t){this.isLocal||this.posthogManager.sendAutomationEvent(t)}captureException(t,r){return this.sentryClient.captureException(t,r)}emitAutomationTelemetryEvent(t,r){this.automationTelemetryManager.emit(t,r)}logger=pI((t,...r)=>this.log(t,...r));stderr=pI((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=t.type==="docs"?"docs":t.workspaceName??"api",n=WYp(r),i=1+(this.longestWorkspaceName!=null?WYp(this.longestWorkspaceName):n).length,o=n.padEnd(i),s=qYp[this.numTasks++%qYp.length],a=de.hex(s)(o);return{...this.constructTaskInit(),logPrefix:a,title:de.hex(s).bold(r)}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===Qf.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:t=>{this.instrumentPostHogEvent(t)},shouldBufferLogs:!1,captureException:(t,r)=>this.sentryClient.captureException(t,r),emitAutomationTelemetryEvent:(t,r)=>this.emitAutomationTelemetryEvent(t,r)}}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=>bw.indexOf(i.level)>=bw.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===Zn.Debug,stderr:r||this.jsonMode})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1,skipFeatureFlagRequest:r=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let n=await a0e({cliEnvironment:this.environment,includePreReleases:t}),i=Jw(n,this.environment.packageVersion);this.logger.debug(`Latest version: ${n}. `+(i?"Upgrade available.":"No upgrade available."));let o={isUpgradeAvailable:i,latestVersion:n},s=await Dzi({project:this.project,cliContext:this,skipFeatureFlagRequest:r});this._isUpgradeAvailable={cliUpgradeInfo:o,generatorUpgradeInfo:s}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1,{nonInteractiveError:n}={}){return this.selectPrompt({message:t,nonInteractiveError:n,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r})}async selectPrompt({message:t,choices:r,default:n,nonInteractiveError:i}){this.assertInteractive(t,i);try{return await dia({message:t,choices:r,default:n,theme:{prefix:de.yellow("?"),style:{answer:o=>de.cyan(o),message:o=>de.bold(o),highlight:o=>de.cyan(o)}}})}catch(o){throw o?.name==="ExitPromptError"&&this.abortCancelledPrompt(),o}}async checkboxPrompt({message:t,choices:r,required:n=!1,validate:i,nonInteractiveError:o}){this.assertInteractive(t,o);try{return await uia({message:t,choices:r,required:n,validate:i==null?void 0:s=>i(s.map(a=>a.value)),theme:{prefix:de.yellow("?"),style:{answer:s=>de.cyan(s),message:s=>de.bold(s),highlight:s=>de.cyan(s)}}})}catch(s){throw s?.name==="ExitPromptError"&&this.abortCancelledPrompt(),s}}async getInput(t){this.assertInteractive(t.message,t.nonInteractiveError);try{return await lia({message:t.message,default:t.default})}catch(r){throw r?.name==="ExitPromptError"&&this.abortCancelledPrompt(),r}}abortCancelledPrompt(){throw this.logger.info(`
|