@zuplo/runtime 6.62.1 → 6.62.3

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/out/esm/index.js CHANGED
@@ -52,7 +52,7 @@ import{a as Ht,d as ke,e as Jx,f as Ea,g as _a,h as Wx,i as Kx}from"./chunk-VRVJ
52
52
 
53
53
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);n.cycles==="ref"&&a(d);continue}if(p.count>1&&n.reused==="ref"){a(d);continue}}let c=s((d,p)=>{let m=this.seen.get(d),f=m.def??m.schema,g={...f};if(m.ref===null)return;let b=m.ref;if(m.ref=null,b){c(b,p);let h=this.seen.get(b).schema;h.$ref&&p.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(h)):(Object.assign(f,h),Object.assign(f,g))}m.isParent||this.override({zodSchema:d,jsonSchema:f})},"flattenRef");for(let d of[...this.seen.entries()].reverse())c(d[0],{target:this.target});let u={...o.def},l=n.external?.defs??{};for(let d of this.seen.entries()){let p=d[1];p.def&&p.defId&&(l[p.defId]=p.def)}!n.external&&Object.keys(l).length>0&&(this.target==="draft-2020-12"?u.$defs=l:u.definitions=l),this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}};s(lp,"toJSONSchema")});var $b={};var Ab=te(()=>{});var Zt={};Nt(Zt,{$ZodAny:()=>ml,$ZodArray:()=>yl,$ZodAsyncError:()=>St,$ZodBase64:()=>ol,$ZodBase64URL:()=>il,$ZodBigInt:()=>rs,$ZodBigIntFormat:()=>ul,$ZodBoolean:()=>ao,$ZodCIDRv4:()=>tl,$ZodCIDRv6:()=>rl,$ZodCUID:()=>Hu,$ZodCUID2:()=>Gu,$ZodCatch:()=>Nl,$ZodCheck:()=>Ae,$ZodCheckBigIntFormat:()=>bu,$ZodCheckEndsWith:()=>_u,$ZodCheckGreaterThan:()=>Qi,$ZodCheckIncludes:()=>Cu,$ZodCheckLengthEquals:()=>Iu,$ZodCheckLessThan:()=>Ki,$ZodCheckLowerCase:()=>ku,$ZodCheckMaxLength:()=>Ru,$ZodCheckMaxSize:()=>wu,$ZodCheckMimeType:()=>$u,$ZodCheckMinLength:()=>Pu,$ZodCheckMinSize:()=>vu,$ZodCheckMultipleOf:()=>hu,$ZodCheckNumberFormat:()=>yu,$ZodCheckOverwrite:()=>Au,$ZodCheckProperty:()=>Ou,$ZodCheckRegex:()=>Su,$ZodCheckSizeEquals:()=>xu,$ZodCheckStartsWith:()=>Eu,$ZodCheckStringFormat:()=>Kr,$ZodCheckUpperCase:()=>Tu,$ZodCustom:()=>jl,$ZodDate:()=>hl,$ZodDefault:()=>_l,$ZodDiscriminatedUnion:()=>wl,$ZodE164:()=>sl,$ZodEmail:()=>ju,$ZodEmoji:()=>qu,$ZodEnum:()=>Il,$ZodError:()=>to,$ZodFile:()=>kl,$ZodFunction:()=>ks,$ZodGUID:()=>Uu,$ZodIPv4:()=>Yu,$ZodIPv6:()=>el,$ZodISODate:()=>Ku,$ZodISODateTime:()=>Wu,$ZodISODuration:()=>Xu,$ZodISOTime:()=>Qu,$ZodIntersection:()=>vl,$ZodJWT:()=>al,$ZodKSUID:()=>Ju,$ZodLazy:()=>zl,$ZodLiteral:()=>Sl,$ZodMap:()=>Rl,$ZodNaN:()=>Ll,$ZodNanoID:()=>Fu,$ZodNever:()=>fl,$ZodNonOptional:()=>$l,$ZodNull:()=>pl,$ZodNullable:()=>El,$ZodNumber:()=>ts,$ZodNumberFormat:()=>cl,$ZodObject:()=>bl,$ZodOptional:()=>Cl,$ZodPipe:()=>uo,$ZodPrefault:()=>Ol,$ZodPromise:()=>Ul,$ZodReadonly:()=>Ml,$ZodRealError:()=>Wr,$ZodRecord:()=>xl,$ZodRegistry:()=>Qr,$ZodSet:()=>Pl,$ZodString:()=>so,$ZodStringFormat:()=>Ce,$ZodSuccess:()=>Al,$ZodSymbol:()=>ll,$ZodTemplateLiteral:()=>Dl,$ZodTransform:()=>Tl,$ZodTuple:()=>xr,$ZodType:()=>ue,$ZodULID:()=>Bu,$ZodURL:()=>Zu,$ZodUUID:()=>zu,$ZodUndefined:()=>dl,$ZodUnion:()=>ns,$ZodUnknown:()=>co,$ZodVoid:()=>gl,$ZodXID:()=>Vu,$brand:()=>Mi,$constructor:()=>T,$input:()=>Rd,$output:()=>xd,Doc:()=>io,JSONSchema:()=>$b,JSONSchemaGenerator:()=>Co,_any:()=>Bd,_array:()=>op,_base64:()=>Rs,_base64url:()=>Ps,_bigint:()=>zd,_boolean:()=>Dd,_catch:()=>Kk,_cidrv4:()=>vs,_cidrv6:()=>xs,_coercedBigint:()=>jd,_coercedBoolean:()=>Ud,_coercedDate:()=>Qd,_coercedNumber:()=>Od,_coercedString:()=>Sd,_cuid:()=>ms,_cuid2:()=>fs,_custom:()=>To,_date:()=>Kd,_default:()=>Vk,_discriminatedUnion:()=>Mk,_e164:()=>Is,_email:()=>is,_emoji:()=>ds,_endsWith:()=>xo,_enum:()=>Zk,_file:()=>sp,_float32:()=>Ad,_float64:()=>Nd,_gt:()=>zt,_gte:()=>We,_guid:()=>fo,_includes:()=>wo,_int:()=>$d,_int32:()=>Ld,_int64:()=>Zd,_intersection:()=>Dk,_ipv4:()=>bs,_ipv6:()=>ws,_isoDate:()=>Td,_isoDateTime:()=>kd,_isoDuration:()=>Ed,_isoTime:()=>Cd,_jwt:()=>Ss,_ksuid:()=>ys,_lazy:()=>eT,_length:()=>en,_literal:()=>Fk,_lowercase:()=>yo,_lt:()=>Ut,_lte:()=>lt,_map:()=>zk,_max:()=>lt,_maxLength:()=>Yr,_maxSize:()=>Xr,_mime:()=>Ro,_min:()=>We,_minLength:()=>Xt,_minSize:()=>Pr,_multipleOf:()=>Rr,_nan:()=>Xd,_nanoid:()=>ps,_nativeEnum:()=>qk,_negative:()=>ep,_never:()=>Jd,_nonnegative:()=>rp,_nonoptional:()=>Jk,_nonpositive:()=>tp,_normalize:()=>Po,_null:()=>Gd,_nullable:()=>Bk,_number:()=>_d,_optional:()=>Gk,_overwrite:()=>jt,_parse:()=>zi,_parseAsync:()=>Zi,_pipe:()=>Qk,_positive:()=>Yd,_promise:()=>tT,_property:()=>np,_readonly:()=>Xk,_record:()=>Uk,_refine:()=>rT,_regex:()=>ho,_safeParse:()=>Fi,_safeParseAsync:()=>Hi,_set:()=>jk,_size:()=>go,_startsWith:()=>vo,_string:()=>Id,_stringbool:()=>ap,_success:()=>Wk,_symbol:()=>Fd,_templateLiteral:()=>Yk,_toLowerCase:()=>So,_toUpperCase:()=>ko,_transform:()=>Hk,_trim:()=>Io,_tuple:()=>ip,_uint32:()=>Md,_uint64:()=>qd,_ulid:()=>gs,_undefined:()=>Hd,_union:()=>Lk,_unknown:()=>Vd,_uppercase:()=>bo,_url:()=>ls,_uuid:()=>ss,_uuidv4:()=>as,_uuidv6:()=>cs,_uuidv7:()=>us,_void:()=>Wd,_xid:()=>hs,clone:()=>rt,config:()=>ze,flattenError:()=>ro,formatError:()=>no,function:()=>up,globalConfig:()=>Vn,globalRegistry:()=>Tt,isValidBase64:()=>nl,isValidBase64URL:()=>ly,isValidJWT:()=>dy,locales:()=>mo,parse:()=>ji,parseAsync:()=>qi,prettifyError:()=>jc,regexes:()=>vr,registry:()=>os,safeParse:()=>qc,safeParseAsync:()=>Fc,toDotPath:()=>Bh,toJSONSchema:()=>lp,treeifyError:()=>zc,util:()=>ee,version:()=>Lu});var Ke=te(()=>{Jr();Gi();Zc();lo();Xi();Mu();me();Wi();Eb();Pd();Nu();_b();cp();Ob();Ab()});var dp=te(()=>{Ke()});var Ts={};Nt(Ts,{ZodISODate:()=>Lb,ZodISODateTime:()=>Nb,ZodISODuration:()=>Db,ZodISOTime:()=>Mb,date:()=>mp,datetime:()=>pp,duration:()=>gp,time:()=>fp});function pp(t){return kd(Nb,t)}function mp(t){return Td(Lb,t)}function fp(t){return Cd(Mb,t)}function gp(t){return Ed(Db,t)}var Nb,Lb,Mb,Db,hp=te(()=>{Ke();Cs();Nb=T("ZodISODateTime",(t,e)=>{Wu.init(t,e),Ee.init(t,e)});s(pp,"datetime");Lb=T("ZodISODate",(t,e)=>{Ku.init(t,e),Ee.init(t,e)});s(mp,"date");Mb=T("ZodISOTime",(t,e)=>{Qu.init(t,e),Ee.init(t,e)});s(fp,"time");Db=T("ZodISODuration",(t,e)=>{Xu.init(t,e),Ee.init(t,e)});s(gp,"duration")});var zb,iT,tn,yp=te(()=>{Ke();Ke();zb=s((t,e)=>{to.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:s(r=>no(t,r),"value")},flatten:{value:s(r=>ro(t,r),"value")},addIssue:{value:s(r=>t.issues.push(r),"value")},addIssues:{value:s(r=>t.issues.push(...r),"value")},isEmpty:{get(){return t.issues.length===0}}})},"initializer"),iT=T("ZodError",zb),tn=T("ZodError",zb,{Parent:Error})});var bp,wp,vp,xp,Rp=te(()=>{Ke();yp();bp=zi(tn),wp=Zi(tn),vp=Fi(tn),xp=Hi(tn)});var Pp={};Nt(Pp,{bigint:()=>lT,boolean:()=>uT,date:()=>dT,number:()=>cT,string:()=>aT});function aT(t){return Sd(Es,t)}function cT(t){return Od(Eo,t)}function uT(t){return Ud(_o,t)}function lT(t){return jd(Oo,t)}function dT(t){return Qd(_s,t)}var jb=te(()=>{Ke();Cs();s(aT,"string");s(cT,"number");s(uT,"boolean");s(lT,"bigint");s(dT,"date")});function Ip(t){return Id(Es,t)}function pT(t){return is(Tp,t)}function mT(t){return fo(Os,t)}function fT(t){return ss(qt,t)}function gT(t){return as(qt,t)}function hT(t){return cs(qt,t)}function yT(t){return us(qt,t)}function bT(t){return ls(Cp,t)}function wT(t){return ds(Ep,t)}function vT(t){return ps(_p,t)}function xT(t){return ms(Op,t)}function RT(t){return fs($p,t)}function PT(t){return gs(Ap,t)}function IT(t){return hs(Np,t)}function ST(t){return ys(Lp,t)}function kT(t){return bs(Mp,t)}function TT(t){return ws(Dp,t)}function CT(t){return vs(Up,t)}function ET(t){return xs(zp,t)}function _T(t){return Rs(jp,t)}function OT(t){return Ps(Zp,t)}function $T(t){return Is(qp,t)}function AT(t){return Ss(Fp,t)}function Zb(t){return _d(Eo,t)}function Sp(t){return $d(rn,t)}function NT(t){return Ad(rn,t)}function LT(t){return Nd(rn,t)}function MT(t){return Ld(rn,t)}function DT(t){return Md(rn,t)}function qb(t){return Dd(_o,t)}function UT(t){return zd(Oo,t)}function zT(t){return Zd(Hp,t)}function jT(t){return qd(Hp,t)}function ZT(t){return Fd(Fb,t)}function qT(t){return Hd(Hb,t)}function Bb(t){return Gd(Gb,t)}function FT(){return Bd(Vb)}function $s(){return Vd(Gp)}function Ms(t){return Jd(Jb,t)}function HT(t){return Wd(Wb,t)}function GT(t){return Kd(_s,t)}function Bp(t,e){return op(Kb,t,e)}function BT(t){let e=t._zod.def.shape;return sw(Object.keys(e))}function VT(t,e){let r={type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},...ee.normalizeParams(e)};return new Ds(r)}function JT(t,e){return new Ds({type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},catchall:Ms(),...ee.normalizeParams(e)})}function WT(t,e){return new Ds({type:"object",get shape(){return ee.assignProp(this,"shape",{...t}),this.shape},catchall:$s(),...ee.normalizeParams(e)})}function Us(t,e){return new Vp({type:"union",options:t,...ee.normalizeParams(e)})}function KT(t,e,r){return new Qb({type:"union",options:e,discriminator:t,...ee.normalizeParams(r)})}function Yb(t,e){return new Xb({type:"intersection",left:t,right:e})}function QT(t,e,r){let n=e instanceof ue,o=n?r:e,i=n?e:null;return new ew({type:"tuple",items:t,rest:i,...ee.normalizeParams(o)})}function tw(t,e,r){return new Jp({type:"record",keyType:t,valueType:e,...ee.normalizeParams(r)})}function XT(t,e,r){return new Jp({type:"record",keyType:Us([t,Ms()]),valueType:e,...ee.normalizeParams(r)})}function YT(t,e,r){return new rw({type:"map",keyType:t,valueType:e,...ee.normalizeParams(r)})}function eC(t,e){return new nw({type:"set",valueType:t,...ee.normalizeParams(e)})}function ow(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new $o({type:"enum",entries:r,...ee.normalizeParams(e)})}function tC(t,e){return new $o({type:"enum",entries:t,...ee.normalizeParams(e)})}function sw(t,e){return new iw({type:"literal",values:Array.isArray(t)?t:[t],...ee.normalizeParams(e)})}function rC(t){return sp(aw,t)}function Wp(t){return new cw({type:"transform",transform:t})}function As(t){return new Kp({type:"optional",innerType:t})}function Ns(t){return new uw({type:"nullable",innerType:t})}function nC(t){return As(Ns(t))}function dw(t,e){return new lw({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function mw(t,e){return new pw({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function fw(t,e){return new Qp({type:"nonoptional",innerType:t,...ee.normalizeParams(e)})}function oC(t){return new gw({type:"success",innerType:t})}function yw(t,e){return new hw({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function iC(t){return Xd(bw,t)}function Ls(t,e){return new Xp({type:"pipe",in:t,out:e})}function vw(t){return new ww({type:"readonly",innerType:t})}function sC(t,e){return new xw({type:"template_literal",parts:t,...ee.normalizeParams(e)})}function Pw(t){return new Rw({type:"lazy",getter:t})}function aC(t){return new Iw({type:"promise",innerType:t})}function Sw(t,e){let r=new Ae({check:"custom",...ee.normalizeParams(e)});return r._zod.check=t,r}function cC(t,e){return To(zs,t??(()=>!0),e)}function kw(t,e={}){return To(zs,t,e)}function Tw(t,e){let r=Sw(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(ee.issue(o,n.value,r._zod.def));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),n.issues.push(ee.issue(i))}},t(n.value,n)),e);return r}function uC(t,e={error:`Input not instance of ${t.name}`}){let r=new zs({type:"custom",check:"custom",fn:s(n=>n instanceof t,"fn"),abort:!0,...ee.normalizeParams(e)});return r._zod.bag.Class=t,r}function dC(t){let e=Pw(()=>Us([Ip(t),Zb(),qb(),Bb(),Bp(e),tw(Ip(),e)]));return e}function pC(t,e){return Ls(Wp(t),e)}var ge,kp,Es,Ee,Tp,Os,qt,Cp,Ep,_p,Op,$p,Ap,Np,Lp,Mp,Dp,Up,zp,jp,Zp,qp,Fp,Eo,rn,_o,Oo,Hp,Fb,Hb,Gb,Vb,Gp,Jb,Wb,_s,Kb,Ds,Vp,Qb,Xb,ew,Jp,rw,nw,$o,iw,aw,cw,Kp,uw,lw,pw,Qp,gw,hw,bw,Xp,ww,xw,Rw,Iw,zs,lC,Cs=te(()=>{Ke();Ke();dp();hp();Rp();hp();jb();ge=T("ZodType",(t,e)=>(ue.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>rt(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>bp(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>vp(t,r,n),t.parseAsync=async(r,n)=>wp(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>xp(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(kw(r,n)),t.superRefine=r=>t.check(Tw(r)),t.overwrite=r=>t.check(jt(r)),t.optional=()=>As(t),t.nullable=()=>Ns(t),t.nullish=()=>As(Ns(t)),t.nonoptional=r=>fw(t,r),t.array=()=>Bp(t),t.or=r=>Us([t,r]),t.and=r=>Yb(t,r),t.transform=r=>Ls(t,Wp(r)),t.default=r=>dw(t,r),t.prefault=r=>mw(t,r),t.catch=r=>yw(t,r),t.pipe=r=>Ls(t,r),t.readonly=()=>vw(t),t.describe=r=>{let n=t.clone();return Tt.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Tt.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Tt.get(t);let n=t.clone();return Tt.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),kp=T("_ZodString",(t,e)=>{so.init(t,e),ge.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(ho(...n)),t.includes=(...n)=>t.check(wo(...n)),t.startsWith=n=>t.check(vo(n)),t.endsWith=n=>t.check(xo(n)),t.min=(...n)=>t.check(Xt(...n)),t.max=(...n)=>t.check(Yr(...n)),t.length=(...n)=>t.check(en(...n)),t.nonempty=(...n)=>t.check(Xt(1,...n)),t.lowercase=n=>t.check(yo(n)),t.uppercase=n=>t.check(bo(n)),t.trim=()=>t.check(Io()),t.normalize=(...n)=>t.check(Po(...n)),t.toLowerCase=()=>t.check(So()),t.toUpperCase=()=>t.check(ko())}),Es=T("ZodString",(t,e)=>{so.init(t,e),kp.init(t,e),t.email=r=>t.check(is(Tp,r)),t.url=r=>t.check(ls(Cp,r)),t.jwt=r=>t.check(Ss(Fp,r)),t.emoji=r=>t.check(ds(Ep,r)),t.guid=r=>t.check(fo(Os,r)),t.uuid=r=>t.check(ss(qt,r)),t.uuidv4=r=>t.check(as(qt,r)),t.uuidv6=r=>t.check(cs(qt,r)),t.uuidv7=r=>t.check(us(qt,r)),t.nanoid=r=>t.check(ps(_p,r)),t.guid=r=>t.check(fo(Os,r)),t.cuid=r=>t.check(ms(Op,r)),t.cuid2=r=>t.check(fs($p,r)),t.ulid=r=>t.check(gs(Ap,r)),t.base64=r=>t.check(Rs(jp,r)),t.base64url=r=>t.check(Ps(Zp,r)),t.xid=r=>t.check(hs(Np,r)),t.ksuid=r=>t.check(ys(Lp,r)),t.ipv4=r=>t.check(bs(Mp,r)),t.ipv6=r=>t.check(ws(Dp,r)),t.cidrv4=r=>t.check(vs(Up,r)),t.cidrv6=r=>t.check(xs(zp,r)),t.e164=r=>t.check(Is(qp,r)),t.datetime=r=>t.check(pp(r)),t.date=r=>t.check(mp(r)),t.time=r=>t.check(fp(r)),t.duration=r=>t.check(gp(r))});s(Ip,"string");Ee=T("ZodStringFormat",(t,e)=>{Ce.init(t,e),kp.init(t,e)}),Tp=T("ZodEmail",(t,e)=>{ju.init(t,e),Ee.init(t,e)});s(pT,"email");Os=T("ZodGUID",(t,e)=>{Uu.init(t,e),Ee.init(t,e)});s(mT,"guid");qt=T("ZodUUID",(t,e)=>{zu.init(t,e),Ee.init(t,e)});s(fT,"uuid");s(gT,"uuidv4");s(hT,"uuidv6");s(yT,"uuidv7");Cp=T("ZodURL",(t,e)=>{Zu.init(t,e),Ee.init(t,e)});s(bT,"url");Ep=T("ZodEmoji",(t,e)=>{qu.init(t,e),Ee.init(t,e)});s(wT,"emoji");_p=T("ZodNanoID",(t,e)=>{Fu.init(t,e),Ee.init(t,e)});s(vT,"nanoid");Op=T("ZodCUID",(t,e)=>{Hu.init(t,e),Ee.init(t,e)});s(xT,"cuid");$p=T("ZodCUID2",(t,e)=>{Gu.init(t,e),Ee.init(t,e)});s(RT,"cuid2");Ap=T("ZodULID",(t,e)=>{Bu.init(t,e),Ee.init(t,e)});s(PT,"ulid");Np=T("ZodXID",(t,e)=>{Vu.init(t,e),Ee.init(t,e)});s(IT,"xid");Lp=T("ZodKSUID",(t,e)=>{Ju.init(t,e),Ee.init(t,e)});s(ST,"ksuid");Mp=T("ZodIPv4",(t,e)=>{Yu.init(t,e),Ee.init(t,e)});s(kT,"ipv4");Dp=T("ZodIPv6",(t,e)=>{el.init(t,e),Ee.init(t,e)});s(TT,"ipv6");Up=T("ZodCIDRv4",(t,e)=>{tl.init(t,e),Ee.init(t,e)});s(CT,"cidrv4");zp=T("ZodCIDRv6",(t,e)=>{rl.init(t,e),Ee.init(t,e)});s(ET,"cidrv6");jp=T("ZodBase64",(t,e)=>{ol.init(t,e),Ee.init(t,e)});s(_T,"base64");Zp=T("ZodBase64URL",(t,e)=>{il.init(t,e),Ee.init(t,e)});s(OT,"base64url");qp=T("ZodE164",(t,e)=>{sl.init(t,e),Ee.init(t,e)});s($T,"e164");Fp=T("ZodJWT",(t,e)=>{al.init(t,e),Ee.init(t,e)});s(AT,"jwt");Eo=T("ZodNumber",(t,e)=>{ts.init(t,e),ge.init(t,e),t.gt=(n,o)=>t.check(zt(n,o)),t.gte=(n,o)=>t.check(We(n,o)),t.min=(n,o)=>t.check(We(n,o)),t.lt=(n,o)=>t.check(Ut(n,o)),t.lte=(n,o)=>t.check(lt(n,o)),t.max=(n,o)=>t.check(lt(n,o)),t.int=n=>t.check(Sp(n)),t.safe=n=>t.check(Sp(n)),t.positive=n=>t.check(zt(0,n)),t.nonnegative=n=>t.check(We(0,n)),t.negative=n=>t.check(Ut(0,n)),t.nonpositive=n=>t.check(lt(0,n)),t.multipleOf=(n,o)=>t.check(Rr(n,o)),t.step=(n,o)=>t.check(Rr(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});s(Zb,"number");rn=T("ZodNumberFormat",(t,e)=>{cl.init(t,e),Eo.init(t,e)});s(Sp,"int");s(NT,"float32");s(LT,"float64");s(MT,"int32");s(DT,"uint32");_o=T("ZodBoolean",(t,e)=>{ao.init(t,e),ge.init(t,e)});s(qb,"boolean");Oo=T("ZodBigInt",(t,e)=>{rs.init(t,e),ge.init(t,e),t.gte=(n,o)=>t.check(We(n,o)),t.min=(n,o)=>t.check(We(n,o)),t.gt=(n,o)=>t.check(zt(n,o)),t.gte=(n,o)=>t.check(We(n,o)),t.min=(n,o)=>t.check(We(n,o)),t.lt=(n,o)=>t.check(Ut(n,o)),t.lte=(n,o)=>t.check(lt(n,o)),t.max=(n,o)=>t.check(lt(n,o)),t.positive=n=>t.check(zt(BigInt(0),n)),t.negative=n=>t.check(Ut(BigInt(0),n)),t.nonpositive=n=>t.check(lt(BigInt(0),n)),t.nonnegative=n=>t.check(We(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(Rr(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});s(UT,"bigint");Hp=T("ZodBigIntFormat",(t,e)=>{ul.init(t,e),Oo.init(t,e)});s(zT,"int64");s(jT,"uint64");Fb=T("ZodSymbol",(t,e)=>{ll.init(t,e),ge.init(t,e)});s(ZT,"symbol");Hb=T("ZodUndefined",(t,e)=>{dl.init(t,e),ge.init(t,e)});s(qT,"_undefined");Gb=T("ZodNull",(t,e)=>{pl.init(t,e),ge.init(t,e)});s(Bb,"_null");Vb=T("ZodAny",(t,e)=>{ml.init(t,e),ge.init(t,e)});s(FT,"any");Gp=T("ZodUnknown",(t,e)=>{co.init(t,e),ge.init(t,e)});s($s,"unknown");Jb=T("ZodNever",(t,e)=>{fl.init(t,e),ge.init(t,e)});s(Ms,"never");Wb=T("ZodVoid",(t,e)=>{gl.init(t,e),ge.init(t,e)});s(HT,"_void");_s=T("ZodDate",(t,e)=>{hl.init(t,e),ge.init(t,e),t.min=(n,o)=>t.check(We(n,o)),t.max=(n,o)=>t.check(lt(n,o));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});s(GT,"date");Kb=T("ZodArray",(t,e)=>{yl.init(t,e),ge.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Xt(r,n)),t.nonempty=r=>t.check(Xt(1,r)),t.max=(r,n)=>t.check(Yr(r,n)),t.length=(r,n)=>t.check(en(r,n))});s(Bp,"array");s(BT,"keyof");Ds=T("ZodObject",(t,e)=>{bl.init(t,e),ge.init(t,e),ee.defineLazy(t,"shape",()=>Object.fromEntries(Object.entries(t._zod.def.shape))),t.keyof=()=>ow(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:$s()}),t.loose=()=>t.clone({...t._zod.def,catchall:$s()}),t.strict=()=>t.clone({...t._zod.def,catchall:Ms()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ee.extend(t,r),t.merge=r=>ee.merge(t,r),t.pick=r=>ee.pick(t,r),t.omit=r=>ee.omit(t,r),t.partial=(...r)=>ee.partial(Kp,t,r[0]),t.required=(...r)=>ee.required(Qp,t,r[0])});s(VT,"object");s(JT,"strictObject");s(WT,"looseObject");Vp=T("ZodUnion",(t,e)=>{ns.init(t,e),ge.init(t,e),t.options=e.options});s(Us,"union");Qb=T("ZodDiscriminatedUnion",(t,e)=>{Vp.init(t,e),wl.init(t,e)});s(KT,"discriminatedUnion");Xb=T("ZodIntersection",(t,e)=>{vl.init(t,e),ge.init(t,e)});s(Yb,"intersection");ew=T("ZodTuple",(t,e)=>{xr.init(t,e),ge.init(t,e),t.rest=r=>t.clone({...t._zod.def,rest:r})});s(QT,"tuple");Jp=T("ZodRecord",(t,e)=>{xl.init(t,e),ge.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});s(tw,"record");s(XT,"partialRecord");rw=T("ZodMap",(t,e)=>{Rl.init(t,e),ge.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});s(YT,"map");nw=T("ZodSet",(t,e)=>{Pl.init(t,e),ge.init(t,e),t.min=(...r)=>t.check(Pr(...r)),t.nonempty=r=>t.check(Pr(1,r)),t.max=(...r)=>t.check(Xr(...r)),t.size=(...r)=>t.check(go(...r))});s(eC,"set");$o=T("ZodEnum",(t,e)=>{Il.init(t,e),ge.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let i={};for(let a of n)if(r.has(a))i[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new $o({...e,checks:[],...ee.normalizeParams(o),entries:i})},t.exclude=(n,o)=>{let i={...e.entries};for(let a of n)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new $o({...e,checks:[],...ee.normalizeParams(o),entries:i})}});s(ow,"_enum");s(tC,"nativeEnum");iw=T("ZodLiteral",(t,e)=>{Sl.init(t,e),ge.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});s(sw,"literal");aw=T("ZodFile",(t,e)=>{kl.init(t,e),ge.init(t,e),t.min=(r,n)=>t.check(Pr(r,n)),t.max=(r,n)=>t.check(Xr(r,n)),t.mime=(r,n)=>t.check(Ro(r,n))});s(rC,"file");cw=T("ZodTransform",(t,e)=>{Tl.init(t,e),ge.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(ee.issue(i,r.value,e));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),a.continue??(a.continue=!0),r.issues.push(ee.issue(a))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});s(Wp,"transform");Kp=T("ZodOptional",(t,e)=>{Cl.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType});s(As,"optional");uw=T("ZodNullable",(t,e)=>{El.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType});s(Ns,"nullable");s(nC,"nullish");lw=T("ZodDefault",(t,e)=>{_l.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});s(dw,"_default");pw=T("ZodPrefault",(t,e)=>{Ol.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType});s(mw,"prefault");Qp=T("ZodNonOptional",(t,e)=>{$l.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType});s(fw,"nonoptional");gw=T("ZodSuccess",(t,e)=>{Al.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType});s(oC,"success");hw=T("ZodCatch",(t,e)=>{Nl.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});s(yw,"_catch");bw=T("ZodNaN",(t,e)=>{Ll.init(t,e),ge.init(t,e)});s(iC,"nan");Xp=T("ZodPipe",(t,e)=>{uo.init(t,e),ge.init(t,e),t.in=e.in,t.out=e.out});s(Ls,"pipe");ww=T("ZodReadonly",(t,e)=>{Ml.init(t,e),ge.init(t,e)});s(vw,"readonly");xw=T("ZodTemplateLiteral",(t,e)=>{Dl.init(t,e),ge.init(t,e)});s(sC,"templateLiteral");Rw=T("ZodLazy",(t,e)=>{zl.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.getter()});s(Pw,"lazy");Iw=T("ZodPromise",(t,e)=>{Ul.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType});s(aC,"promise");zs=T("ZodCustom",(t,e)=>{jl.init(t,e),ge.init(t,e)});s(Sw,"check");s(cC,"custom");s(kw,"refine");s(Tw,"superRefine");s(uC,"_instanceof");lC=ap.bind(null,{Pipe:Xp,Boolean:_o,Unknown:Gp});s(dC,"json");s(pC,"preprocess")});function hC(t){ze({customError:t})}function yC(){return ze().customError}var mC,fC,gC,Cw=te(()=>{Ke();Ke();mC={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"},fC=Object.freeze({status:"aborted"}),gC=fC;s(hC,"setErrorMap");s(yC,"getErrorMap")});var y={};Nt(y,{$brand:()=>Mi,$input:()=>Rd,$output:()=>xd,NEVER:()=>gC,ZodAny:()=>Vb,ZodArray:()=>Kb,ZodBase64:()=>jp,ZodBase64URL:()=>Zp,ZodBigInt:()=>Oo,ZodBigIntFormat:()=>Hp,ZodBoolean:()=>_o,ZodCIDRv4:()=>Up,ZodCIDRv6:()=>zp,ZodCUID:()=>Op,ZodCUID2:()=>$p,ZodCatch:()=>hw,ZodCustom:()=>zs,ZodDate:()=>_s,ZodDefault:()=>lw,ZodDiscriminatedUnion:()=>Qb,ZodE164:()=>qp,ZodEmail:()=>Tp,ZodEmoji:()=>Ep,ZodEnum:()=>$o,ZodError:()=>iT,ZodFile:()=>aw,ZodGUID:()=>Os,ZodIPv4:()=>Mp,ZodIPv6:()=>Dp,ZodIntersection:()=>Xb,ZodIssueCode:()=>mC,ZodJWT:()=>Fp,ZodKSUID:()=>Lp,ZodLazy:()=>Rw,ZodLiteral:()=>iw,ZodMap:()=>rw,ZodNaN:()=>bw,ZodNanoID:()=>_p,ZodNever:()=>Jb,ZodNonOptional:()=>Qp,ZodNull:()=>Gb,ZodNullable:()=>uw,ZodNumber:()=>Eo,ZodNumberFormat:()=>rn,ZodObject:()=>Ds,ZodOptional:()=>Kp,ZodPipe:()=>Xp,ZodPrefault:()=>pw,ZodPromise:()=>Iw,ZodReadonly:()=>ww,ZodRealError:()=>tn,ZodRecord:()=>Jp,ZodSet:()=>nw,ZodString:()=>Es,ZodStringFormat:()=>Ee,ZodSuccess:()=>gw,ZodSymbol:()=>Fb,ZodTemplateLiteral:()=>xw,ZodTransform:()=>cw,ZodTuple:()=>ew,ZodType:()=>ge,ZodULID:()=>Ap,ZodURL:()=>Cp,ZodUUID:()=>qt,ZodUndefined:()=>Hb,ZodUnion:()=>Vp,ZodUnknown:()=>Gp,ZodVoid:()=>Wb,ZodXID:()=>Np,_ZodString:()=>kp,_default:()=>dw,any:()=>FT,array:()=>Bp,base64:()=>_T,base64url:()=>OT,bigint:()=>UT,boolean:()=>qb,catch:()=>yw,check:()=>Sw,cidrv4:()=>CT,cidrv6:()=>ET,clone:()=>rt,coerce:()=>Pp,config:()=>ze,core:()=>Zt,cuid:()=>xT,cuid2:()=>RT,custom:()=>cC,date:()=>GT,discriminatedUnion:()=>KT,e164:()=>$T,email:()=>pT,emoji:()=>wT,endsWith:()=>xo,enum:()=>ow,file:()=>rC,flattenError:()=>ro,float32:()=>NT,float64:()=>LT,formatError:()=>no,function:()=>up,getErrorMap:()=>yC,globalRegistry:()=>Tt,gt:()=>zt,gte:()=>We,guid:()=>mT,includes:()=>wo,instanceof:()=>uC,int:()=>Sp,int32:()=>MT,int64:()=>zT,intersection:()=>Yb,ipv4:()=>kT,ipv6:()=>TT,iso:()=>Ts,json:()=>dC,jwt:()=>AT,keyof:()=>BT,ksuid:()=>ST,lazy:()=>Pw,length:()=>en,literal:()=>sw,locales:()=>mo,looseObject:()=>WT,lowercase:()=>yo,lt:()=>Ut,lte:()=>lt,map:()=>YT,maxLength:()=>Yr,maxSize:()=>Xr,mime:()=>Ro,minLength:()=>Xt,minSize:()=>Pr,multipleOf:()=>Rr,nan:()=>iC,nanoid:()=>vT,nativeEnum:()=>tC,negative:()=>ep,never:()=>Ms,nonnegative:()=>rp,nonoptional:()=>fw,nonpositive:()=>tp,normalize:()=>Po,null:()=>Bb,nullable:()=>Ns,nullish:()=>nC,number:()=>Zb,object:()=>VT,optional:()=>As,overwrite:()=>jt,parse:()=>bp,parseAsync:()=>wp,partialRecord:()=>XT,pipe:()=>Ls,positive:()=>Yd,prefault:()=>mw,preprocess:()=>pC,prettifyError:()=>jc,promise:()=>aC,property:()=>np,readonly:()=>vw,record:()=>tw,refine:()=>kw,regex:()=>ho,regexes:()=>vr,registry:()=>os,safeParse:()=>vp,safeParseAsync:()=>xp,set:()=>eC,setErrorMap:()=>hC,size:()=>go,startsWith:()=>vo,strictObject:()=>JT,string:()=>Ip,stringbool:()=>lC,success:()=>oC,superRefine:()=>Tw,symbol:()=>ZT,templateLiteral:()=>sC,toJSONSchema:()=>lp,toLowerCase:()=>So,toUpperCase:()=>ko,transform:()=>Wp,treeifyError:()=>zc,trim:()=>Io,tuple:()=>QT,uint32:()=>DT,uint64:()=>jT,ulid:()=>PT,undefined:()=>qT,union:()=>Us,unknown:()=>$s,uppercase:()=>bo,url:()=>bT,uuid:()=>fT,uuidv4:()=>gT,uuidv6:()=>hT,uuidv7:()=>yT,void:()=>HT,xid:()=>IT});var Yp=te(()=>{Ke();Cs();dp();yp();Rp();Cw();Ke();Vl();Ke();ze(po())});var em=te(()=>{Yp();Yp()});var Ze=te(()=>{em();em()});var dt,Ie,Yt=te(()=>{dt="2.0";(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ResourceNotFound=-32002]="ResourceNotFound",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(Ie||(Ie={}))});var Ao,Ew,js=te(()=>{Ze();Ao=y.union([y.string(),y.number().int()]),Ew=y.union([Ao,y.null()])});var bC,er,Ow,No=te(()=>{Ze();Yt();bC=y.object({_meta:y.optional(y.object({}).loose())}).loose(),er=y.object({method:y.string(),params:y.optional(bC)}),Ow=y.object({jsonrpc:y.literal(dt),...er.shape}).strict()});var wC,vC,ot,it,$w,Sr=te(()=>{Ze();Yt();js();wC=y.union([y.string(),y.number().int()]),vC=y.object({progressToken:y.optional(wC)}).loose(),ot=y.object({_meta:y.optional(vC)}).loose(),it=y.object({method:y.string(),params:y.optional(ot)}),$w=y.object({jsonrpc:y.literal(dt),id:Ao,...it.shape}).strict()});var pt,fF,Aw,kr=te(()=>{Ze();Yt();js();pt=y.object({_meta:y.optional(y.object({}).loose())}).loose(),fF=pt.strict(),Aw=y.object({jsonrpc:y.literal(dt),id:Ao,result:pt}).strict()});var Et,nr,on=te(()=>{Ze();Et=y.object({name:y.string(),title:y.optional(y.string())}).loose(),nr=y.object({audience:y.optional(y.array(y.enum(["user","assistant"]))),priority:y.optional(y.number().min(0).max(1)),lastModified:y.optional(y.string())}).loose()});var rm,Uw=te(()=>{Ze();rm=y.string()});var or,ir,zw=te(()=>{Ze();Uw();Sr();kr();or=it.extend({params:ot.extend({cursor:y.optional(rm)}).optional()}),ir=pt.extend({nextCursor:y.optional(rm)})});var Zs=te(()=>{zw()});var nm={};Nt(nm,{AudioContentSchema:()=>PC,EmbeddedResourceSchema:()=>IC,ImageContentSchema:()=>RC,TextContentSchema:()=>xC});var xC,RC,PC,IC,om=te(()=>{Ze();on();xC=y.object({type:y.literal("text"),text:y.string(),annotations:y.optional(nr),_meta:y.optional(y.object({}).loose())}).loose(),RC=y.object({type:y.literal("image"),data:y.base64(),mimeType:y.string(),annotations:y.optional(nr),_meta:y.optional(y.object({}).loose())}).loose(),PC=y.object({type:y.literal("audio"),data:y.base64(),mimeType:y.string(),annotations:y.optional(nr),_meta:y.optional(y.object({}).loose())}).loose(),IC=y.lazy(()=>y.object({type:y.literal("resource"),resource:y.union([y.object({uri:y.url(),mimeType:y.optional(y.string()),_meta:y.optional(y.object({}).loose()),text:y.string()}).loose(),y.object({uri:y.url(),mimeType:y.optional(y.string()),_meta:y.optional(y.object({}).loose()),blob:y.base64()}).loose()]),annotations:y.optional(nr),_meta:y.optional(y.object({}).loose())}).loose())});var lm={};Nt(lm,{BlobResourceContentsSchema:()=>Zw,ListResourceTemplatesRequestSchema:()=>cm,ListResourceTemplatesResultSchema:()=>TC,ListResourcesRequestSchema:()=>am,ListResourcesResultSchema:()=>kC,ReadResourceRequestSchema:()=>um,ReadResourceResultSchema:()=>CC,ResourceContentsSchema:()=>im,ResourceLinkSchema:()=>SC,ResourceListChangedNotificationSchema:()=>OC,ResourceSchema:()=>sm,ResourceTemplateSchema:()=>qw,ResourceUpdatedNotificationSchema:()=>$C,SubscribeRequestSchema:()=>EC,TextResourceContentsSchema:()=>jw,UnsubscribeRequestSchema:()=>_C});var im,jw,Zw,sm,SC,qw,am,kC,cm,TC,um,CC,EC,_C,OC,$C,qs=te(()=>{Ze();No();Sr();kr();on();Zs();im=y.object({uri:y.url(),mimeType:y.optional(y.string()),_meta:y.optional(y.object({}).loose())}).loose(),jw=im.extend({text:y.string()}),Zw=im.extend({blob:y.base64()}),sm=Et.extend({uri:y.url(),description:y.optional(y.string()),mimeType:y.optional(y.string()),annotations:y.optional(nr),size:y.optional(y.number()),_meta:y.optional(y.object({}).loose())}),SC=sm.extend({type:y.literal("resource_link")}),qw=Et.extend({uriTemplate:y.string(),description:y.optional(y.string()),mimeType:y.optional(y.string()),annotations:y.optional(nr),_meta:y.optional(y.object({}).loose())}),am=or.extend({method:y.literal("resources/list")}),kC=ir.extend({resources:y.array(sm)}),cm=or.extend({method:y.literal("resources/templates/list")}),TC=ir.extend({resourceTemplates:y.array(qw)}),um=it.extend({method:y.literal("resources/read"),params:ot.extend({uri:y.url()})}),CC=pt.extend({contents:y.array(y.union([jw,Zw]))}),EC=it.extend({method:y.literal("resources/subscribe"),params:ot.extend({uri:y.url()})}),_C=it.extend({method:y.literal("resources/unsubscribe"),params:ot.extend({uri:y.url()})}),OC=er.extend({method:y.literal("notifications/resources/list_changed")}),$C=er.extend({method:y.literal("notifications/resources/updated"),params:y.object({uri:y.url()}).loose()})});Function.prototype.toString=function(){return"[native code]"};var ui=globalThis,Lg=ui.caches;if(Lg){let t=Lg.open;ui.caches.open=function(e){let r=P.instance.deploymentName??P.instance.build.BUILD_ID;return t.call(this,`${r}-${e}`)},delete ui.caches.default,Object.freeze(ui.caches)}var li=new Set,Mg=new Set;function R(t){Mg.has(t)||(Mg.add(t),li.add(t))}s(R,"trackFeature");function Dg(){let t=[...li];return li.clear(),t}s(Dg,"getUnsentFeatures");function Ug(t){for(let e of t)li.add(e)}s(Ug,"restoreFeatures");function je(t,e){t.has("Authorization")||t.set("Authorization",`Bearer ${P.instance.authApiJWT}`),t.set("zp-rid",e??`global-${crypto.randomUUID()}`),t.set("zp-dn",P.instance.deploymentName??"unknown"),t.set("User-Agent",P.instance.systemUserAgent),t.set("zp-compat-date",P.instance.build.COMPATIBILITY_DATE??"none")}s(je,"setZuploHeaders");var Lr=class extends Error{static{s(this,"ApiError")}type;title;status;detail;instance;constructor(e,r){super(e.title,r);let{type:n,title:o,status:i,detail:a,instance:c}=e;this.name="ApiProblemError",this.type=n,this.title=o,this.status=i,this.detail=a,this.instance=c}};function Qx(t){return t!=null&&typeof t=="object"&&"type"in t&&"title"in t&&"status"in t&&typeof t.type=="string"&&typeof t.title=="string"&&typeof t.status=="number"}s(Qx,"isProblemDetails");async function Xx(t,e={}){R("utility.zuplo-api-services");let{method:r="GET",data:n}=e,o=new URL(t,P.instance.zuploEdgeApiUrl),i=new Headers(e.headers);je(i),i.set("Content-Type","application/json");let a={method:r,headers:i};n&&(a.body=JSON.stringify(n));let c=await j.fetch(o,a),u;try{if(!c.ok){if(u=await c.clone().json(),Qx(u))throw new Lr(u);let l={type:`https://zup.fail/http-status/${c.status}`,title:`HTTP ${c.status}`,status:c.status,detail:JSON.stringify(u)||"Request failed"};throw new Lr(l)}if(c.status===204)return;u=await c.clone().json()}catch(l){if(l instanceof Lr)throw l;let d={type:"https://zup.fail/unknown-error",title:"Internal Server Error",status:500,detail:l instanceof Error?l.message:String(l)};throw new Lr(d,{cause:l})}return u}s(Xx,"apiServices");var zg=new Map,Oa=class{static{s(this,"LruTtlCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let r=this.#n.get(e);if(!r)return;let n=Date.now();if(n>r.expiresAt){this.delete(e);return}r.lastUsed=n;let o=this.#r.indexOf(e);return o>=0&&(this.#r.splice(o,1),this.#r.push(e)),this.#o(),r?.data}put(e,r,n){if(n<=0)return;let o=this.#r.indexOf(e),i=o>=0;if(i)this.#r.splice(o,1);else if(this.#n.size>=this.#e){let u=this.#r.shift();u&&this.#n.delete(u)}let a=Date.now(),c={created:i?this.#n.get(e).created:a,lastUsed:a,expiresAt:a+n*1e3,data:r};this.#r.push(e),this.#n.set(e,c)}delete(e){let r=this.#r.indexOf(e);r>=0&&this.#r.splice(r,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();e>this.#t+1e4&&(this.purge(),this.#t=e)}purge(){let e=Date.now(),r=[];this.#n.forEach((n,o)=>{e>n.expiresAt&&r.push(o)}),r.forEach(n=>this.delete(n))}},ht=class{static{s(this,"MemoryCache")}constructor(e,r={maxSize:1e3}){this.name=e;let n=zg.get(e);n||(n=new Oa(r),zg.set(e,n)),this.#e=n}name;#e;get(e){return this.#e.get(e)}put(e,r,n){return this.#e.put(e,r,n)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var $a="__zuplo-expiry-header",Cn=class{static{s(this,"ZoneCache")}constructor(e,r){this.#t=e,this.#e=r}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let r=await this.#r(),n=this.#o(e),o=await r.match(n);if(!o)return;let i=o.headers.get($a);if(!i){try{await r.delete(n)}catch(u){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",u),await this.deleteFallback(e)}return}let a=parseInt(i,10);if(Date.now()>=a){try{await r.delete(n)}catch(u){this.logDebug("Handled failure to delete with CF cache because of expiration",u),await this.deleteFallback(e)}return}return await o.json()}catch(r){this.logDebug(r)}}async put(e,r,n){let o=new Headers({"cache-control":`s-maxage=${n}, must-revalidate`,"content-type":"application/json"});o.set($a,`${Date.now()+n*1e3}`);let i=await this.#r(),a=this.#o(e),c=new Response(JSON.stringify(r),{headers:o});await i.put(a,c)}async delete(e){let r=await this.#r(),n=this.#o(e);try{await r.delete(n)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let r=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});r.set($a,`${Date.now()}`);let n=await this.#r(),o=this.#o(e),i=new Response("",{headers:r});await n.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var be=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,r,n){let o=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=n?new ht(o,n):new ht(o),this.#n=new Cn(o,r),this.#r=r}#e;#t;#n;#r;async get(e){let r=this.#t.get(e);if(r)return r;let n=await this.#n.get(e);if(n){let o=Math.floor((n.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,n.data,o),n.data}}put(e,r,n){this.#t.put(e,r,n);let o={data:r,expires:Date.now()+n*1e3},i=this.#n.put(e,o,n).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}async delete(e){this.#t.delete(e),await this.#n.delete(e)}};var Aa="__zuplo-expiry-header",Na=class{static{s(this,"StreamingZoneCache")}constructor(e,r){this.#t=e,this.#e=r}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://streaming-zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let r=await this.#r(),n=this.#o(e),o=await r.match(n);if(!o)return;let i=o.headers.get(Aa);if(!i){await r.delete(n).catch(c=>{this.logDebug(`StreamingZoneCache: error deleting missing expiry entry ${e}`,c)});return}let a=parseInt(i,10);if(Date.now()>=a){await r.delete(n).catch(c=>{this.logDebug(`StreamingZoneCache: error deleting expired entry ${e}`,c)});return}return o.body??void 0}catch(r){this.logDebug(`get(${e}) failed`,r);return}}async put(e,r,n){let o=new Headers({"cache-control":`s-maxage=${n}, must-revalidate`});o.set(Aa,`${Date.now()+n*1e3}`);let i=new Response(r,{headers:o}),a=await this.#r(),c=this.#o(e);await a.put(c,i)}async delete(e){try{await(await this.#r()).delete(this.#o(e))}catch(r){this.logDebug(`delete(${e}) fallback needed`,r),await this.deleteFallback(e)}}async deleteFallback(e){let r=new Headers({"Cache-Control":"s-maxage=0, must-revalidate",[Aa]:`${Date.now()}`}),n=new Response("",{headers:r}),o=await this.#r(),i=this.#o(e);await o.put(i,n)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`StreamingZoneCache(${this.#t}):`,...e):"log"in this.#e&&this.#e.log.debug(`StreamingZoneCache(${this.#t}):`,...e)}};var pe=class t{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}get(e){return t.get(e,this.#t)}static get(e,r){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(r)}set(e,r){t.set(e,this.#t,r)}static set(e,r,n){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(r,n),t.#e.set(e,o)}};import{trace as VR}from"@opentelemetry/api";import{SpanStatusCode as pR,trace as mR}from"@opentelemetry/api";import{SpanStatusCode as fi,trace as gi}from"@opentelemetry/api";var jg=s(t=>(e,r)=>t(e,r),"globalRequestHandlerProxy");function Zg(t){jg=t}s(Zg,"setTelemetryInitFunction");var qg=s(t=>jg(t),"proxyHandler");var Gt=class{static{s(this,"RuntimePlugin")}},$e=class extends Gt{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e){}},di=class extends $e{static{s(this,"MeteringPlugin")}},En=class extends Gt{static{s(this,"TelemetryPlugin")}};var _n=class t{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=s(async e=>{let r=e.problem,n=JSON.stringify(r,null,2);return new Response(n,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(R("runtime.problem-response-formatter"),t.problemResponseFormat=(r,n,o)=>{try{return e(r,n,o)}catch(i){throw new F("Error in custom 'problemResponseFormat'",{cause:i})}})}},mr=class{static{s(this,"ProblemResponseFormatter")}static async format(e,r,n){return await _n.problemResponseFormat(e,r,n)}};function pi(t){for(let e in t){let r=t[e];r&&typeof r=="object"&&pi(r)}return Object.freeze(t)}s(pi,"deepFreeze");var de=class t extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;#n;constructor(e,r,n){super(e,r);let o=r?.params;this.#n=n,o?this.#t=o:e instanceof t?this.#t=e.#t:this.#t={};let i=r?.user;i?this.user=i:e instanceof t&&(this.user=e.user)}get originalRequest(){return this.#n??null}get query(){if(this.#e===void 0){let e={},r=new URL(this.url).searchParams;for(let[n,o]of r.entries())e[n]=o;this.#e=e}return pi(this.#e)}get params(){return pi(this.#t)}user};var za={},yt=[],La=[],Ma=[],Da=[],Ua=[];var mi={addPlugin(t){yt.push(t)},addRequestHook(t){La.push(t)},addResponseSendingHook(t){Ma.push(t)},addResponseSendingFinalHook(t){Da.push(t)},addPreRoutingHook(t){Ua.push(t)}},Hg=s(async(t,e)=>{if(La.length===0)return t;let r=gi.getTracer("extension");return r.startActiveSpan("hook:onRequest",async n=>{try{let o=t;for(let i of La){let a=await r.startActiveSpan(i.name,async c=>{let u=await i(o,e);if(u instanceof de||u instanceof Response)return c.end(),u;{let l=new w(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw c.end(),c.recordException(l),c.setStatus({code:fi.ERROR}),l}});if(a instanceof de)o=a;else return a}return o}finally{n.end()}})},"invokeOnRequestExtensions"),Gg=s(async(t,e,r)=>{if(Ma.length===0)return t;let n=gi.getTracer("extension");return n.startActiveSpan("hook:onResponseSending",async o=>{try{let i=t;for(let a of Ma)await n.startActiveSpan(a.name,async c=>{let u=await a(t,e,r);if(u instanceof Response)i=u,c.end();else{let l=new w(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw c.recordException(l),c.setStatus({code:fi.ERROR}),c.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Bg=s(async(t,e,r)=>{if(Da.length===0)return;let n=gi.getTracer("extension");return n.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of Da)await n.startActiveSpan(i.name,async a=>{try{await i(t,e,r)}catch(c){throw a.recordException(c),a.setStatus({code:fi.ERROR}),a.end(),c}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Vg=s(async t=>{if(Ua.length===0)return t;let e=gi.getTracer("extension");return e.startActiveSpan("hook:preRouting",async r=>{try{let n=t;for(let o of Ua)n=await e.startActiveSpan(o.name,async a=>{try{let c=await o(n);if(c instanceof Request)return c;{let u=new F(`Invalid state - the PreRouting hook must return a Request. Received ${typeof c}.`);throw a.recordException(u),a.setStatus({code:fi.ERROR}),u}}finally{a.end()}});return n}finally{r.end()}})},"invokePreRoutingHooks"),Fg=!1;async function Jg(t){if(!Fg){t&&(R("runtime.extensions"),await t(mi)),za.value=mi;for(let e of yt)if(e instanceof En){let{requestHandlerProxy:r}=e.instrument({accountName:P.instance.build.ACCOUNT_NAME,projectName:P.instance.build.PROJECT_NAME,buildId:P.instance.build.BUILD_ID,zuploVersion:P.instance.build.ZUPLO_VERSION,compatibilityDate:P.instance.build.COMPATIBILITY_DATE,instanceId:P.instance.instanceId,environmentType:P.instance.loggingEnvironmentType,environmentStage:P.instance.loggingEnvironmentStage,deploymentName:P.instance.deploymentName});Zg(r)}await Promise.all(yt.map(async e=>{e instanceof $e&&await e.initialize(mi)})),_n.setProblemResponseFormat(mi.problemResponseFormat),Fg=!0}}s(Jg,"initializeRuntime");var ja={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Za(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(ja.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(ja.Json)||!e?JSON.stringify(t):t}s(Za,"serialize");function Mr(t){let{developerPortal:e}=we.instance.runtimeSettings;return e.enabled&&e.basePath&&t.pathname.startsWith(e.basePath)||t.pathname.startsWith("/__zuplo/")||t.pathname.startsWith("/__/zuplo/")}s(Mr,"isSystemRoute");var hi=(L=>(L[L.CONTINUE=100]="CONTINUE",L[L.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",L[L.PROCESSING=102]="PROCESSING",L[L.EARLY_HINTS=103]="EARLY_HINTS",L[L.OK=200]="OK",L[L.CREATED=201]="CREATED",L[L.ACCEPTED=202]="ACCEPTED",L[L.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",L[L.NO_CONTENT=204]="NO_CONTENT",L[L.RESET_CONTENT=205]="RESET_CONTENT",L[L.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",L[L.MULTI_STATUS=207]="MULTI_STATUS",L[L.ALREADY_REPORTED=208]="ALREADY_REPORTED",L[L.IM_USED=226]="IM_USED",L[L.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",L[L.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",L[L.FOUND=302]="FOUND",L[L.SEE_OTHER=303]="SEE_OTHER",L[L.NOT_MODIFIED=304]="NOT_MODIFIED",L[L.USE_PROXY=305]="USE_PROXY",L[L.SWITCH_PROXY=306]="SWITCH_PROXY",L[L.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",L[L.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",L[L.BAD_REQUEST=400]="BAD_REQUEST",L[L.UNAUTHORIZED=401]="UNAUTHORIZED",L[L.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",L[L.FORBIDDEN=403]="FORBIDDEN",L[L.NOT_FOUND=404]="NOT_FOUND",L[L.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",L[L.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",L[L.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",L[L.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",L[L.CONFLICT=409]="CONFLICT",L[L.GONE=410]="GONE",L[L.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",L[L.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",L[L.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",L[L.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",L[L.URI_TOO_LONG=414]="URI_TOO_LONG",L[L.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",L[L.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",L[L.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",L[L.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",L[L.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",L[L.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",L[L.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",L[L.LOCKED=423]="LOCKED",L[L.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",L[L.TOO_EARLY=425]="TOO_EARLY",L[L.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",L[L.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",L[L.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",L[L.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",L[L.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",L[L.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",L[L.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",L[L.BAD_GATEWAY=502]="BAD_GATEWAY",L[L.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",L[L.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",L[L.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",L[L.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",L[L.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",L[L.LOOP_DETECTED=508]="LOOP_DETECTED",L[L.NOT_EXTENDED=510]="NOT_EXTENDED",L[L.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",L))(hi||{}),Wg={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var Yx={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},qa=Yx;function eR(t){return`${new URL(t.url).pathname}`}s(eR,"instance");function tR(t,e){let r={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:P.instance.build.BUILD_ID},n=t.headers.get(Nr);return n&&(r.rayId=n),r}s(tR,"trace");var rR=s((t,e,r,n,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:eR(e),trace:tR(e,r),...n},additionalHeaders:o,statusText:qa[t.status]}),"merge"),Fa=class{static{s(this,"HttpProblemsBase")}static format=s((e,r,n)=>"problem"in e?mr.format(e,r,n):mr.format({problem:e},r,n),"format");static getProblemFromStatus(e,r){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Wg[e],...r}}},D=class t extends Fa{static{s(this,"HttpProblems")}static#e(e,r,n,o,i){let a=rR(t.getProblemFromStatus(e),r,n,o,i);return mr.format(a,r,n)}static continue=s((e,r,n,o)=>this.#e(200,e,r,n,o),"continue");static switchingProtocols=s((e,r,n,o)=>this.#e(101,e,r,n,o),"switchingProtocols");static processing=s((e,r,n,o)=>this.#e(102,e,r,n,o),"processing");static earlyHints=s((e,r,n,o)=>this.#e(103,e,r,n,o),"earlyHints");static ok=s((e,r,n,o)=>this.#e(200,e,r,n,o),"ok");static created=s((e,r,n,o)=>this.#e(201,e,r,n,o),"created");static accepted=s((e,r,n,o)=>this.#e(202,e,r,n,o),"accepted");static nonAuthoritativeInformation=s((e,r,n,o)=>this.#e(203,e,r,n,o),"nonAuthoritativeInformation");static noContent=s((e,r,n,o)=>this.#e(204,e,r,n,o),"noContent");static resetContent=s((e,r,n,o)=>this.#e(205,e,r,n,o),"resetContent");static partialContent=s((e,r,n,o)=>this.#e(206,e,r,n,o),"partialContent");static multiStatus=s((e,r,n,o)=>this.#e(207,e,r,n,o),"multiStatus");static alreadyReported=s((e,r,n,o)=>this.#e(208,e,r,n,o),"alreadyReported");static imUsed=s((e,r,n,o)=>this.#e(226,e,r,n,o),"imUsed");static multipleChoices=s((e,r,n,o)=>this.#e(300,e,r,n,o),"multipleChoices");static movedPermanently=s((e,r,n,o)=>this.#e(301,e,r,n,o),"movedPermanently");static found=s((e,r,n,o)=>this.#e(302,e,r,n,o),"found");static seeOther=s((e,r,n,o)=>this.#e(303,e,r,n,o),"seeOther");static notModified=s((e,r,n,o)=>this.#e(304,e,r,n,o),"notModified");static useProxy=s((e,r,n,o)=>this.#e(305,e,r,n,o),"useProxy");static switchProxy=s((e,r,n,o)=>this.#e(306,e,r,n,o),"switchProxy");static temporaryRedirect=s((e,r,n,o)=>this.#e(307,e,r,n,o),"temporaryRedirect");static permanentRedirect=s((e,r,n,o)=>this.#e(308,e,r,n,o),"permanentRedirect");static badRequest=s((e,r,n,o)=>this.#e(400,e,r,n,o),"badRequest");static unauthorized=s((e,r,n,o)=>this.#e(401,e,r,n,o),"unauthorized");static paymentRequired=s((e,r,n,o)=>this.#e(402,e,r,n,o),"paymentRequired");static forbidden=s((e,r,n,o)=>this.#e(403,e,r,n,o),"forbidden");static notFound=s((e,r,n,o)=>this.#e(404,e,r,n,o),"notFound");static methodNotAllowed=s((e,r,n,o)=>this.#e(405,e,r,n,o),"methodNotAllowed");static notAcceptable=s((e,r,n,o)=>this.#e(406,e,r,n,o),"notAcceptable");static proxyAuthenticationRequired=s((e,r,n,o)=>this.#e(407,e,r,n,o),"proxyAuthenticationRequired");static requestTimeout=s((e,r,n,o)=>this.#e(408,e,r,n,o),"requestTimeout");static conflict=s((e,r,n,o)=>this.#e(409,e,r,n,o),"conflict");static gone=s((e,r,n,o)=>this.#e(410,e,r,n,o),"gone");static lengthRequired=s((e,r,n,o)=>this.#e(411,e,r,n,o),"lengthRequired");static preconditionFailed=s((e,r,n,o)=>this.#e(412,e,r,n,o),"preconditionFailed");static contentTooLarge=s((e,r,n,o)=>this.#e(413,e,r,n,o),"contentTooLarge");static uriTooLong=s((e,r,n,o)=>this.#e(414,e,r,n,o),"uriTooLong");static unsupportedMediaType=s((e,r,n,o)=>this.#e(415,e,r,n,o),"unsupportedMediaType");static rangeNotSatisfiable=s((e,r,n,o)=>this.#e(416,e,r,n,o),"rangeNotSatisfiable");static expectationFailed=s((e,r,n,o)=>this.#e(417,e,r,n,o),"expectationFailed");static imATeapot=s((e,r,n,o)=>this.#e(418,e,r,n,o),"imATeapot");static misdirectedRequest=s((e,r,n,o)=>this.#e(421,e,r,n,o),"misdirectedRequest");static unprocessableContent=s((e,r,n,o)=>this.#e(422,e,r,n,o),"unprocessableContent");static locked=s((e,r,n,o)=>this.#e(423,e,r,n,o),"locked");static failedDependency=s((e,r,n,o)=>this.#e(424,e,r,n,o),"failedDependency");static tooEarly=s((e,r,n,o)=>this.#e(425,e,r,n,o),"tooEarly");static upgradeRequired=s((e,r,n,o)=>this.#e(426,e,r,n,o),"upgradeRequired");static preconditionRequired=s((e,r,n,o)=>this.#e(428,e,r,n,o),"preconditionRequired");static tooManyRequests=s((e,r,n,o)=>this.#e(429,e,r,n,o),"tooManyRequests");static requestHeaderFieldsTooLarge=s((e,r,n,o)=>this.#e(431,e,r,n,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=s((e,r,n,o)=>this.#e(451,e,r,n,o),"unavailableForLegalReasons");static internalServerError=s((e,r,n,o)=>this.#e(500,e,r,n,o),"internalServerError");static notImplemented=s((e,r,n,o)=>this.#e(501,e,r,n,o),"notImplemented");static badGateway=s((e,r,n,o)=>this.#e(502,e,r,n,o),"badGateway");static serviceUnavailable=s((e,r,n,o)=>this.#e(503,e,r,n,o),"serviceUnavailable");static gatewayTimeout=s((e,r,n,o)=>this.#e(504,e,r,n,o),"gatewayTimeout");static httpVersionNotSupported=s((e,r,n,o)=>this.#e(505,e,r,n,o),"httpVersionNotSupported");static variantAlsoNegotiates=s((e,r,n,o)=>this.#e(506,e,r,n,o),"variantAlsoNegotiates");static insufficientStorage=s((e,r,n,o)=>this.#e(507,e,r,n,o),"insufficientStorage");static loopDetected=s((e,r,n,o)=>this.#e(508,e,r,n,o),"loopDetected");static notExtended=s((e,r,n,o)=>this.#e(510,e,r,n,o),"notExtended");static networkAuthenticationRequired=s((e,r,n,o)=>this.#e(511,e,r,n,o),"networkAuthenticationRequired")};var{toString:nR}=Object.prototype,{propertyIsEnumerable:oR}=Object.prototype;function Ha(t){return nR.call(t)}s(Ha,"toString");function Ye(t){return typeof t=="string"}s(Ye,"isString");function Dr(t){return Ye(t)&&t!==""}s(Dr,"isNonEmptyString");function Kg(t){return Ha(t)==="[object RegExp]"}s(Kg,"isRegexp");function Qg(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>oR.call(t,e))]}s(Qg,"getOwnEnumerableKeys");function fr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}s(fr,"isObject");function Ga(t){return typeof t=="number"&&!Number.isNaN(t)}s(Ga,"isNumber");function Ba(t){return t===!0||t===!1}s(Ba,"isBoolean");function Xg(t){return typeof t>"u"}s(Xg,"isUndefined");function Yg(t){return Xg(t)||t===null}s(Yg,"isUndefinedOrNull");function On(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}s(On,"isErrorLike");var iR=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),sR=new Map(iR);var aR=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Va=Symbol(".toJSON was called"),cR=s(t=>{t[Va]=!0;let e=t.toJSON();return delete t[Va],e},"toJSON"),uR=s(t=>sR.get(t)??Error,"getErrorConstructor"),eh=s(({from:t,seen:e,to:r,forceEnumerable:n,maxDepth:o,depth:i,useToJSON:a,serialize:c})=>{if(!r)if(Array.isArray(t))r=[];else if(!c&&On(t)){let l=uR(t.name);r=new l}else r={};if(e.push(t),i>=o)return r;if(a&&typeof t.toJSON=="function"&&t[Va]!==!0)return cR(t);let u=s(l=>eh({from:l,seen:[...e],forceEnumerable:n,maxDepth:o,depth:i,useToJSON:a,serialize:c}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){r[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){r[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){r[l]=d;continue}if(!e.includes(t[l])){i++,r[l]=u(t[l]);continue}r[l]="[Circular]"}}for(let{property:l,enumerable:d}of aR)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(r,l,{value:On(t[l])?u(t[l]):t[l],enumerable:n?!0:d,configurable:!0,writable:!0});return r},"destroyCircular");function gr(t,e){let r=e?.maxDepth??Number.POSITIVE_INFINITY,n=e?.useToJSON??!0;return typeof t=="object"&&t!==null?eh({from:t,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:n,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}s(gr,"serializeError");var lR=/file:\/\/\/(.*?)\/dist\//g,dR="at async Event.respondWith";function Ja(t){return typeof t!="string"?t:t.split(`
54
54
  `).filter(e=>!e.trim().startsWith("at async file")).map((e,r)=>{let n=e.replaceAll(lR,"").replaceAll(dR,"").trim();return r===0||n.length===0?n:` ${n}`}).filter(e=>e.length>0).join(`
55
- `)}s(Ja,"cleanStack");function xt(t,e,r,n){e.log.error(r,n);let o={};if(P.instance.isLocalDevelopment||P.instance.isWorkingCopy)if(n instanceof F&&n.extensionMembers)o=n.extensionMembers;else if(n.cause){let i=gr(n.cause);"stack"in i&&(i.stack=Ja(i.stack)),o={cause:i}}else{let i=gr(n);"stack"in i&&(i.stack=Ja(i.stack)),o={cause:i}}return D.internalServerError(t,e,{detail:n.message,...o})}s(xt,"errorHandler");var De=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=s(e=>async(r,n)=>mR.getTracer("pipeline").startActiveSpan(`handler:${n.route.handler.export}`,async i=>{try{return await e(r,n)}catch(a){let c=xt(r,n,"Error executing request handler.",a);return i.setStatus({code:pR.ERROR}),c}finally{i.end()}}),"#errorWrappedHandler");#t=s(({processors:e,handler:r})=>async(n,o)=>{let i=Fe.getContextExtensions(o),a=[...e],c=s(async g=>{let b=a.pop();if(!b){let x=await this.#e(async v=>{let C=await r(v,o);return fR(C)})(g,o);try{await i.onHandlerResponse(x,g,o)}catch(v){return xt(n,o,"Error invoking 'context.onHandlerResponse' hook",v)}return x}return b(n,o,c)},"nextPipe"),l=await c(n),d=new URL(n.url);if(Mr(d)&&P.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new $n(n,l);o.dispatchEvent(p);let m=i.latestRequest,f;try{f=await p.mutableResponse}catch(g){return xt(n,o,"Error retrieving mutableResponse",g)}try{f=await i.onResponseSending(f,m,o)}catch(g){return xt(n,o,"Error invoking 'context.onResponseSending' hook",g)}try{f=await Gg(f,m,o)}catch(g){return xt(n,o,"Error invoking 'context.onResponseSending' hook",g)}o.dispatchEvent(new An(n,f));try{await i.onResponseSendingFinal(l,m,o)}catch(g){throw o.log.error("Error invoking 'runtime.onResponseSending' hook",g),g}try{await Bg(l,m,o)}catch(g){throw o.log.error("Error invoking 'runtime.onResponseSending' hook",g),g}return f},"#toZuploPipeline")};function fR(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Za(t),{headers:{"content-type":"application/json"}})}s(fR,"resultToResponse");var Rt=class extends Gt{static{s(this,"MetricsPlugin")}};var Q=class t{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let r=t.#e.get(e);if(!r){let n=`No system logger found for context with requestId '${e.requestId}'`;throw j.console.error(n),new le(n)}return r}static addLogger(e,r){t.#e.set(e,r)}};var ce=class{static{s(this,"BatchDispatch")}constructor(e,r,n,o){this.#t=e,this.#i=r,this.#r=n,this.#n=o??j.console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=s(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(r=>{setTimeout(()=>{if(this.#o.length>0){let n=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(n).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{r()})}},this.#i)}))},"enqueue");waitUntilFlushed=s(async()=>{if(this.#e)return this.#e},"waitUntilFlushed");get queueSize(){return this.#o.length}};async function Te(t,e,r){for(let n=0;n<=t.retries;n++){try{let o=j.fetch(e,r);if(n===t.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;t.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status})}catch(o){if(n===t.retries)throw o;t.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,error:o})}await new Promise(o=>setTimeout(o,t.retryDelayMs*2**n))}throw new w("An unknown error occurred, ensure retries is not negative")}s(Te,"fetchRetry");var yi=class{static{s(this,"ZuploMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new ce("zuplo-metrics-transport",10,this.dispatchFunction,Q.getLogger(e))}pushMetrics(e,r){this.#t.enqueue(e),r.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let{remoteLogURL:r,deploymentName:n}=P.instance,{ACCOUNT_NAME:o,PROJECT_NAME:i}=P.instance.build,a=e.map(p=>{let m=Object.assign({},p);return delete m.requestContentLength,delete m.responseContentLength,m}),c=Dg(),u={metadata:{timestamp:new Date,accountName:o,projectName:i,deploymentName:n},metrics:a,features:c},l=new Headers({"content-type":"application/json"});je(l);let d=await Te({retries:3,retryDelayMs:1e3,logger:j.console},`${r}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(u),headers:l});if(!d.ok){let p=await d.text();Q.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),Ug(c)}}catch(r){Q.getLogger(this.#e).error("Failed to send Zuplo metrics.",r)}},"dispatchFunction")};var Ur="SYSTEM_IGNORED";var Ue=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:r,methods:n,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=r,this.methods=n,this.corsPolicy=i,this.handler={export:Ur,module:Ur},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;metadata;raw(){return{}}};var Wa="x-real-ip",gR="true-client-ip",hR="cf-connecting-ip",yR="x-forwarded-for";function ct(t){let e=t.headers,r=e.get(Wa)??e.get(gR)??e.get(hR);if(r)return r;let n=e.get(yR);if(n){let o=n.split(/,\s*/).map(i=>i.trim()).find(i=>i.length>0);if(o)return o}}s(ct,"getClientIp");var He=s(async(t,e,r)=>{let n=new Date,o=Date.now(),i=await r(t),a=t.headers.get(Nr)??void 0,c=ct(t),u=e.incomingRequestProperties,l;e.route instanceof Ue&&(l=e.route.systemRouteName);let d=Fe.getContextExtensions(e).latestRequest,p={timestamp:n,statusCode:i.status,durationMs:Date.now()-o,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:i.headers.get("content-length")?Number(i.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:l,contextId:e.contextId,parentContextId:e.parentContext?.contextId,requestId:e.requestId,parentRequestId:e.parentContext?.requestId,method:t.method,asn:u.asn,asOrganization:u.asOrganization,colo:u.colo,continent:u.continent,country:u.country,city:u.city,latitude:u.latitude,longitude:u.longitude,rayId:a,instanceId:P.instance.instanceId,userSub:d.user?.sub,clientIp:c},m=[];return!P.instance.isLocalDevelopment&&P.instance.remoteLogURL&&P.instance.remoteLogToken&&P.instance.loggingId&&m.push(new yi(e)),yt.forEach(f=>{if(f instanceof Rt){let g=f.getTransport();m.push(g)}}),m.forEach(f=>{f.pushMetrics(p,e)}),i},"metricsProcessor");var Ka=s(t=>{let e=s(async(o,i)=>{let a=new URL(o.url),c=P.instance.build,u={buildId:c.BUILD_ID,zuploVersion:c.ZUPLO_VERSION,compatibilityDate:c.COMPATIBILITY_DATE,apiVersion:c.API_VERSION,gitSha:c.GIT_SHA,timestamp:c.TIMESTAMP,isProduction:c.ENVIRONMENT_TYPE==="PRODUCTION"};if(a.searchParams.get("system_log")==="true"&&Q.getLogger(i).error("Test System Log",u),a.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(u,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new De({processors:[He],handler:e}),n=new Ue({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(n,r.execute)},"registerBuildRoute");var bi=class{static{s(this,"BoundedSet")}limit;items;constructor(e){this.limit=e,this.items=new Map}add(e){if(this.items.has(e))this.items.delete(e);else if(this.items.size>=this.limit){let r=this.items.keys().next().value;r&&this.items.delete(r)}this.items.set(e,!0)}has(e){return this.items.has(e)}values(){return Array.from(this.items.keys())}size(){return this.items.size}};var th=new Map;function Pt(t){if(Array.isArray(t)&&!t.some(o=>typeof o!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new w("Malformed input string");let e=th.get(t);if(e)return e;let r=t.split(","),n=[];for(let o of r){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),c=parseInt(i[1],10);for(let u=a;u<=c;u++)n.push(u)}else n.push(parseInt(o,10))}return th.set(t,n),n}s(Pt,"statusCodesStringToNumberArray");function Lt(t,e,r){if(!e.startsWith("."))throw new w(`Invalid ${r} - must start with '.' - '${e}' does not`);let n=e.split(".").splice(1),o=t;return n.forEach(i=>{if(o===void 0)throw new F(`Error applying ${r} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Lt,"getValueFromRequestUser");function rh(t,e){if(!e.startsWith("."))throw new w(`Invalid selector. must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),n=t;return r.forEach(o=>{if(n===void 0)throw new F(`Error applying'${e}', reading '${o}'`);if(n&&typeof n=="object")n=Reflect.get(n,o);else throw new F(`Error applying'${e}', reading '${o}'`)}),`${n}`}s(rh,"selectPropertyUsingJsonPath");function Mt(t){if(Array.isArray(t)){if(t.includes(r=>typeof r!="string"))throw new w("Received an array that contains non-string values.");return t}if(Ye(t))return t.includes(",")?t.split(",").map(r=>r.trim()).filter(r=>r!==","&&r!==""):[t];throw new w(`Expected type of string, received type '${typeof t}'`)}s(Mt,"parseValueToStringArray");function nh(t){if(t==null)return[];if(!Array.isArray(t))throw new w(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(r=>{if(!fr(r))throw new w(`Invalid custom cors policy is set. Expected an object, received '${typeof r}'`);if(!Dr(r.name))throw new w("Value of 'name' on custom cors policies must be a non-empty string.");if(r.maxAge!==void 0&&!Ga(r.maxAge))throw new w(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof r.maxAge}'`);if(r.allowCredentials!==void 0&&!Ba(r.allowCredentials))throw new w("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let n=Qa(r,"allowedHeaders"),o=Qa(r,"allowedMethods"),i=Qa(r,"exposeHeaders"),a;try{a=Mt(r.allowedOrigins)}catch(u){throw new w(`Value of 'allowedOrigins' on custom cors policies is invalid. ${u.message} If using an environment variable, check that it is set correctly.`)}return{name:r.name,allowCredentials:typeof r.allowCredentials=="boolean"?String(r.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:n?n.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof r.maxAge=="number"?r.maxAge.toString():void 0}})}s(nh,"parseCorsPolicies");function Qa(t,e){let r;if(t[e]!==void 0)try{r=Mt(t[e])}catch(n){throw new w(`Value of '${e}' on custom cors policies is invalid. ${n.message} If using an environment variable, check that it is set correctly.`)}return r}s(Qa,"parseOptionalProperty");var Xa=new Map,bR=s((t,e,r)=>{for(let n of t){let o=n.trim().toLowerCase();if(o==="*")return e;if(o.includes("*.")){let a=o.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*\\\./g,"[^.]+\\.");if(new RegExp(`^${a}$`).test(r))return e}else{let i=o.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${i}$`).test(r))return e}}},"testMatchinOrigin"),wi=s((t,e,r)=>{if(r===null)return;let n=r.trim().toLowerCase(),o=Xa.get(t);if(o?.has(n))return r;let i=bR(e,r,n);return i&&(o||Xa.set(t,new bi(20)),Xa.get(t)?.add(n)),i},"findMatchingOrigin"),vi=s((t,e)=>{let r={"access-control-allow-origin":e};t.allowedHeaders&&(r["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(r["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(r["access-control-expose-headers"]=t.exposeHeaders);let n=t.allowCredentials;n&&(r["access-control-allow-credentials"]=n);let o=t.maxAge?.toString()??void 0;return o&&(r["access-control-max-age"]=o),r},"generateCorsHeaders"),xi=s((t,e)=>{if(!t)return!1;let{developerPortal:r}=e;return r.enabled&&r.type==="zudoku"&&r.urls?r.urls.urls.includes(t):!1},"isDevPortalOrigin");var Ya=s((t,e,r)=>{let n=s(async(a,c)=>{let u=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return D.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});if(xi(p,e)){let b={"access-control-allow-origin":p,"access-control-allow-methods":l,"access-control-allow-headers":d??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"};return new Response(void 0,{status:200,statusText:"OK",headers:b})}let m=t.lookup(u,l);if(!m)return D.notFound(a,c);let f=m.routeConfiguration,g=wR({requestedMethod:l,requestedHeaders:d,requestedOrigin:p,routeConfig:f,customPolicies:r});return g.isValid?new Response(void 0,{status:200,statusText:"OK",headers:g.headers}):(g.error&&c.log.warn(g.error),D.notFound(a,c))},"optionsHandler"),o=new De({processors:[He],handler:n}),i=new Ue({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),wR=s(({requestedMethod:t,requestedHeaders:e,requestedOrigin:r,routeConfig:n,customPolicies:o})=>{let i={isValid:!1,headers:{}};if(n.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":r,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(n.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${n.pathPattern}'`};let a=o?.find(l=>l.name===n.corsPolicy);if(!a)throw new w(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let c=wi(a.name,a.allowedOrigins,r);return c?{isValid:!0,headers:vi(a,c)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${r}'`}},"validateAndBuildResponseHeaders");var oh=s(t=>{let e=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new De({processors:[He],handler:e}),n=new Ue({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(n,r.execute)},"registerNoRoutes");var Bt=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.mcp=e.mcp,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.metadata=e.metadata,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;metadata;custom;mcp;methods;handler;corsPolicy;policies};var vR=new Ue({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),ih=s(t=>{let e=s(async(n,o)=>{let i=za.value?.notFoundHandler;if(i){let l=new URL(n.url);return i(n,o,{get routesMatchedByPathOnly(){return t.lookupByPathOnly(l.pathname).map(p=>p.routeConfiguration).filter(p=>p instanceof Bt)}})}let a=new URL(n.url);return t.lookupByPathOnly(a.pathname).filter(l=>l.routeConfiguration.handler?.export==="mcpServerHandler").length>0&&n.method!=="POST"?D.methodNotAllowed(n,o):D.notFound(n,o)},"notFoundHandler"),r=new De({processors:[He],handler:e});t.addRoute(vR,r.execute)},"registerNotMatchedHandler");var xR=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],sh=s(t=>{xR.forEach(e=>t.delete(e))},"stripCorsHeaders"),zr=s(async(t,e,r)=>{let n=await r(t);if(P.instance.isDeno&&n.status===101&&[...n.headers.keys()].length===0&&!n.body)return n;let o=e.route,i=t.headers.get("origin"),a=xi(i,we.instance.runtimeSettings);if((!o.corsPolicy||o.corsPolicy==="none")&&!a){let p=new Headers(n.headers);return sh(p),new Response(n.body,{status:n.status,statusText:n.statusText,headers:p,webSocket:n.webSocket})}if(!(n instanceof Response))throw new le(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof n}'`);let c=RR(o,we.instance.routeData.corsPolicies,a),u=PR(i,c),l=new Headers(n.headers);return sh(l),Object.entries(u).forEach(([p,m])=>{l.set(p,m)}),new Response(n.body,{status:n.status,statusText:n.statusText,headers:l,webSocket:n.webSocket})},"corsProcessor"),RR=s((t,e,r)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};if(r)return{name:"dev-portal-anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(o=>o.name===t.corsPolicy);if(n===void 0)throw new w(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),PR=s((t,e)=>{let r=wi(e.name,e.allowedOrigins,t);return r?vi(e,r):{}},"getCorsHeaders");var ec=s(t=>{let e=s(async()=>new Response(JSON.stringify({buildId:P.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new De({processors:[zr],handler:e}),n=new Ue({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(n,r.execute)},"registerPingRoute");import{SpanStatusCode as ah,trace as ch}from"@opentelemetry/api";var Dt={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var Ri=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,r){if(!Ye(r))throw new F(`The name of a policy must be a string. Received '${r}' of type '${typeof r}'`);this.options=e,this.policyName=r,this.policyType=Object.getPrototypeOf(this).constructor.name}},Re=class extends Ri{static{s(this,"InboundPolicy")}},Vt=class extends Ri{static{s(this,"OutboundPolicy")}};var nc=class extends Re{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.policyType=e.name,this.#e=e}handler(e,r){return this.#e(e,r,this.options,this.policyName)}},oc=class extends Vt{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.policyType=e.name,this.#e=e}handler(e,r,n){return this.#e(e,r,n,this.options,this.policyName)}},tc=new Map;function Nn(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.inbound??[],n=t.path),r.filter(i=>!tc.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new w(`Invalid state - no Policy with the name '${i}' ${n&&`on route '${n}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export];if(typeof c!="function")throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof module '${typeof c}')`);let u;if(typeof c!="function")throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof module '${typeof c}')`);if(c.prototype instanceof Re)u=new c(a.handler.options,a.name);else if(typeof c=="function")u=new nc(c,a.handler.options,a.name);else throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new w(`Invalid state - invalid handler on policy '${i}' on route '${n}' (typeof handler '${typeof u.handler}')`);tc.set(a.name,u)}),r.map(i=>{let a=tc.get(i);if(a===void 0)throw new F("Internal error. Policy not found in cache.");return a})}s(Nn,"getInboundPolicyInstances");var rc=new Map;function Ln(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.outbound??[],n=t.path),r.filter(i=>!rc.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new w(`Invalid state - no Policy with the name '${i}' on route '${n}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export],u;if(typeof c!="function")throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof module '${typeof c}')`);if(c.prototype instanceof Vt)u=new c(a.handler.options??{},a.name);else if(typeof c=="function")u=new oc(c,a.handler.options??{},a.name);else throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new w(`Invalid state - invalid handler on policy '${i}' on route '${n}'`);rc.set(a.name,u)}),r.map(i=>{let a=rc.get(i);if(a===void 0)throw new F("Internal error. Policy not found in cache.");return a})}s(Ln,"getOutboundPolicyInstances");var ic=s(t=>async(e,r)=>{let n=Fe.getContextExtensions(r),o=ch.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{try{let a=[...t],c=e;for(;a.length>0;){let u=a.shift();if(!u)return c;let l=await o.startActiveSpan(`policy:${u.policyName}`,async d=>{let p=await u.handler(c,r);if(p instanceof Request||p instanceof de||p instanceof Response)return d.end(),p instanceof Response||p instanceof de?p:new de(p);{let m=new w(`Invalid state - invalid handler on policy '${u.policyName}' on route '${r.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:ah.ERROR}),d.recordException(m),m}});if(l instanceof de)c=l;else if(l instanceof Request)c=new de(l);else if(l instanceof Response)return l;n.latestRequest=c}return c}finally{i.end()}})},"toStackedInboundHandler"),sc=s(t=>async(e,r,n)=>{let o=ch.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...t],c=e;for(;a.length>0;){let u=a.shift();if(!u)return c;c=await o.startActiveSpan(`policy:${u.policyName}`,async d=>{try{d.setAttribute(Dt.PolicyName,u.policyName),d.setAttribute(Dt.PolicyType,u.policyType);let p=await u.handler(c,r,n);if(p instanceof Response)return p;{let m=new w(`Invalid state - invalid handler on policy '${u.policyName}' on route '${n.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:ah.ERROR}),d.recordException(m),m}}finally{d.end()}})}return c}finally{i.end()}})},"toStackedOutboundHandler"),Pi=s(async(t,e,r)=>{let n=Nn(e.route,we.instance.routeData.policies),o=Ln(e.route,we.instance.routeData.policies);return lh({request:t,context:e,inboundPolicies:n,outboundPolicies:o,next:r})},"policyProcessor");function uh({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(n,o,i)=>lh({request:n,context:o,inboundPolicies:t,outboundPolicies:e,next:i}),"policyProcessor")}s(uh,"createInternalPolicyProcessor");async function lh({request:t,context:e,inboundPolicies:r,outboundPolicies:n,next:o}){let i=ic(r);try{let a=await i(t,e);if(a instanceof Response)return a;let c=await o(a),u=sc(n),l;return P.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?l=u(c,t,e):l=c.ok?u(c,t,e):c,l}catch(a){return xt(t,e,"Error executing policies",a)}}s(lh,"executePolicyProcessor");var fh=Vx(mh(),1);function gh(t,e){try{let r=/v\d+(-\d+)?/g,o=(0,fh.parse)(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&r.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(gh,"devPortalBaseURL");var hh="/__zuplo/dev-portal",NR="dev-portal-id",LR="dev-portal-host",MR="zp-account",DR="zp-project",UR="dev-portal-build",zR=`
55
+ `)}s(Ja,"cleanStack");function xt(t,e,r,n){e.log.error(r,n);let o={};if(P.instance.isLocalDevelopment||P.instance.isWorkingCopy)if(n instanceof F&&n.extensionMembers)o=n.extensionMembers;else if(n.cause){let i=gr(n.cause);"stack"in i&&(i.stack=Ja(i.stack)),o={cause:i}}else{let i=gr(n);"stack"in i&&(i.stack=Ja(i.stack)),o={cause:i}}return D.internalServerError(t,e,{detail:n.message,...o})}s(xt,"errorHandler");var De=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=s(e=>async(r,n)=>mR.getTracer("pipeline").startActiveSpan(`handler:${n.route.handler.export}`,async i=>{try{return await e(r,n)}catch(a){let c=xt(r,n,"Error executing request handler.",a);return i.setStatus({code:pR.ERROR}),c}finally{i.end()}}),"#errorWrappedHandler");#t=s(({processors:e,handler:r})=>async(n,o)=>{let i=Fe.getContextExtensions(o),a=[...e],c=s(async g=>{let b=a.pop();if(!b){let x=await this.#e(async v=>{let C=await r(v,o);return fR(C)})(g,o);try{await i.onHandlerResponse(x,g,o)}catch(v){return xt(n,o,"Error invoking 'context.onHandlerResponse' hook",v)}return x}return b(n,o,c)},"nextPipe"),l=await c(n),d=new URL(n.url);if(Mr(d)&&P.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new $n(n,l);o.dispatchEvent(p);let m=i.latestRequest,f;try{f=await p.mutableResponse}catch(g){return xt(n,o,"Error retrieving mutableResponse",g)}try{f=await i.onResponseSending(f,m,o)}catch(g){return xt(n,o,"Error invoking 'context.onResponseSending' hook",g)}try{f=await Gg(f,m,o)}catch(g){return xt(n,o,"Error invoking 'context.onResponseSending' hook",g)}o.dispatchEvent(new An(n,f));try{await i.onResponseSendingFinal(l,m,o)}catch(g){throw o.log.error("Error invoking 'runtime.onResponseSending' hook",g),g}try{await Bg(l,m,o)}catch(g){throw o.log.error("Error invoking 'runtime.onResponseSending' hook",g),g}return f},"#toZuploPipeline")};function fR(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Za(t),{headers:{"content-type":"application/json"}})}s(fR,"resultToResponse");var Rt=class extends Gt{static{s(this,"MetricsPlugin")}};var Q=class t{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let r=t.#e.get(e);if(!r){let n=`No system logger found for context with requestId '${e.requestId}'`;throw j.console.error(n),new le(n)}return r}static addLogger(e,r){t.#e.set(e,r)}};var ce=class{static{s(this,"BatchDispatch")}constructor(e,r,n,o){this.#t=e,this.#i=r,this.#r=n,this.#n=o??j.console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=s(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(r=>{setTimeout(()=>{if(this.#o.length>0){let n=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(n).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{r()})}},this.#i)}))},"enqueue");waitUntilFlushed=s(async()=>{if(this.#e)return this.#e},"waitUntilFlushed");get queueSize(){return this.#o.length}};async function Te(t,e,r){for(let n=0;n<=t.retries;n++){try{let o=j.fetch(e,r);if(n===t.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;t.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status})}catch(o){if(n===t.retries)throw o;t.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,error:o})}await new Promise(o=>setTimeout(o,t.retryDelayMs*2**n))}throw new w("An unknown error occurred, ensure retries is not negative")}s(Te,"fetchRetry");var yi=class{static{s(this,"ZuploMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new ce("zuplo-metrics-transport",10,this.dispatchFunction,Q.getLogger(e))}pushMetrics(e,r){this.#t.enqueue(e),r.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let{remoteLogURL:r,deploymentName:n}=P.instance,{ACCOUNT_NAME:o,PROJECT_NAME:i}=P.instance.build,a=e.map(p=>{let m=Object.assign({},p);return delete m.requestContentLength,delete m.responseContentLength,m}),c=Dg(),u={metadata:{timestamp:new Date,accountName:o,projectName:i,deploymentName:n},metrics:a,features:c},l=new Headers({"content-type":"application/json"});je(l);let d=await Te({retries:3,retryDelayMs:1e3,logger:j.console},`${r}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(u),headers:l});if(!d.ok){let p=await d.text();Q.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),Ug(c)}}catch(r){Q.getLogger(this.#e).error("Failed to send Zuplo metrics.",r)}},"dispatchFunction")};var Ur="SYSTEM_IGNORED";var Ue=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:r,methods:n,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=r,this.methods=n,this.corsPolicy=i,this.handler={export:Ur,module:Ur},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;metadata;raw(){return{}}};var Wa="x-real-ip",gR="true-client-ip",hR="cf-connecting-ip",yR="x-forwarded-for";function ct(t){let e=t.headers,r=e.get(Wa)??e.get(gR)??e.get(hR);if(r)return r;let n=e.get(yR);if(n){let o=n.split(/,\s*/).map(i=>i.trim()).find(i=>i.length>0);if(o)return o}}s(ct,"getClientIp");var He=s(async(t,e,r)=>{let n=new Date,o=Date.now(),i=await r(t),a=t.headers.get(Nr)??void 0,c=ct(t),u=e.incomingRequestProperties,l;e.route instanceof Ue&&(l=e.route.systemRouteName);let d=Fe.getContextExtensions(e).latestRequest,p={timestamp:n,statusCode:i.status,durationMs:Date.now()-o,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:i.headers.get("content-length")?Number(i.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:l,contextId:e.contextId,parentContextId:e.parentContext?.contextId,requestId:e.requestId,parentRequestId:e.parentContext?.requestId,method:t.method,asn:u.asn,asOrganization:u.asOrganization,colo:u.colo,continent:u.continent,country:u.country,city:u.city,latitude:u.latitude,longitude:u.longitude,rayId:a,instanceId:P.instance.instanceId,userSub:d.user?.sub,clientIp:c},m=[];return!P.instance.isLocalDevelopment&&P.instance.remoteLogURL&&P.instance.remoteLogToken&&P.instance.loggingId&&m.push(new yi(e)),yt.forEach(f=>{if(f instanceof Rt){let g=f.getTransport();m.push(g)}}),m.forEach(f=>{f.pushMetrics(p,e)}),i},"metricsProcessor");var Ka=s(t=>{let e=s(async(o,i)=>{let a=new URL(o.url),c=P.instance.build,u={buildId:c.BUILD_ID,zuploVersion:c.ZUPLO_VERSION,compatibilityDate:c.COMPATIBILITY_DATE,apiVersion:c.API_VERSION,gitSha:c.GIT_SHA,timestamp:c.TIMESTAMP,isProduction:c.ENVIRONMENT_TYPE==="PRODUCTION"};if(a.searchParams.get("system_log")==="true"&&Q.getLogger(i).error("Test System Log",u),a.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(u,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new De({processors:[He],handler:e}),n=new Ue({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(n,r.execute)},"registerBuildRoute");var bi=class{static{s(this,"BoundedSet")}limit;items;constructor(e){this.limit=e,this.items=new Map}add(e){if(this.items.has(e))this.items.delete(e);else if(this.items.size>=this.limit){let r=this.items.keys().next().value;r&&this.items.delete(r)}this.items.set(e,!0)}has(e){return this.items.has(e)}values(){return Array.from(this.items.keys())}size(){return this.items.size}};var th=new Map;function Pt(t){if(Array.isArray(t)&&!t.some(o=>typeof o!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new w("Malformed input string");let e=th.get(t);if(e)return e;let r=t.split(","),n=[];for(let o of r){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),c=parseInt(i[1],10);for(let u=a;u<=c;u++)n.push(u)}else n.push(parseInt(o,10))}return th.set(t,n),n}s(Pt,"statusCodesStringToNumberArray");function Lt(t,e,r){if(!e.startsWith("."))throw new w(`Invalid ${r} - must start with '.' - '${e}' does not`);let n=e.split(".").splice(1),o=t;return n.forEach(i=>{if(o===void 0)throw new F(`Error applying ${r} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Lt,"getValueFromRequestUser");function rh(t,e){if(!e.startsWith("."))throw new w(`Invalid selector. must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),n=t;return r.forEach(o=>{if(n===void 0)throw new F(`Error applying'${e}', reading '${o}'`);if(n&&typeof n=="object")n=Reflect.get(n,o);else throw new F(`Error applying'${e}', reading '${o}'`)}),`${n}`}s(rh,"selectPropertyUsingJsonPath");function Mt(t){if(Array.isArray(t)){if(t.includes(r=>typeof r!="string"))throw new w("Received an array that contains non-string values.");return t}if(Ye(t))return t.includes(",")?t.split(",").map(r=>r.trim()).filter(r=>r!==","&&r!==""):[t];throw new w(`Expected type of string, received type '${typeof t}'`)}s(Mt,"parseValueToStringArray");function nh(t){if(t==null)return[];if(!Array.isArray(t))throw new w(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(r=>{if(!fr(r))throw new w(`Invalid custom cors policy is set. Expected an object, received '${typeof r}'`);if(!Dr(r.name))throw new w("Value of 'name' on custom cors policies must be a non-empty string.");if(r.maxAge!==void 0&&!Ga(r.maxAge))throw new w(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof r.maxAge}'`);if(r.allowCredentials!==void 0&&!Ba(r.allowCredentials))throw new w("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let n=Qa(r,"allowedHeaders"),o=Qa(r,"allowedMethods"),i=Qa(r,"exposeHeaders"),a;try{a=Mt(r.allowedOrigins)}catch(u){throw new w(`Value of 'allowedOrigins' on custom cors policies is invalid. ${u.message} If using an environment variable, check that it is set correctly.`)}return{name:r.name,allowCredentials:typeof r.allowCredentials=="boolean"?String(r.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:n?n.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof r.maxAge=="number"?r.maxAge.toString():void 0}})}s(nh,"parseCorsPolicies");function Qa(t,e){let r;if(t[e]!==void 0)try{r=Mt(t[e])}catch(n){throw new w(`Value of '${e}' on custom cors policies is invalid. ${n.message} If using an environment variable, check that it is set correctly.`)}return r}s(Qa,"parseOptionalProperty");var Xa=new Map,bR=s((t,e,r)=>{for(let n of t){let o=n.trim().toLowerCase();if(o==="*")return e;if(o.includes("*.")){let a=o.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*\\\./g,"[^.]+\\.");if(new RegExp(`^${a}$`).test(r))return e}else{let i=o.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${i}$`).test(r))return e}}},"testMatchinOrigin"),wi=s((t,e,r)=>{if(r===null)return;let n=r.trim().toLowerCase(),o=Xa.get(t);if(o?.has(n))return r;let i=bR(e,r,n);return i&&(o||Xa.set(t,new bi(20)),Xa.get(t)?.add(n)),i},"findMatchingOrigin"),vi=s((t,e)=>{let r={"access-control-allow-origin":e};t.allowedHeaders&&(r["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(r["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(r["access-control-expose-headers"]=t.exposeHeaders);let n=t.allowCredentials;n&&(r["access-control-allow-credentials"]=n);let o=t.maxAge?.toString()??void 0;return o&&(r["access-control-max-age"]=o),r},"generateCorsHeaders"),xi=s((t,e)=>{if(!t)return!1;let{developerPortal:r}=e;return r.enabled&&r.type==="zudoku"&&r.urls?r.urls.urls.includes(t):!1},"isDevPortalOrigin");var Ya=s((t,e,r)=>{let n=s(async(a,c)=>{let u=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return D.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});if(xi(p,e)){let b={"access-control-allow-origin":p,"access-control-allow-methods":l,"access-control-allow-headers":d??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"};return new Response(void 0,{status:200,statusText:"OK",headers:b})}let m=t.lookup(u,l);if(!m)return D.notFound(a,c);let f=m.routeConfiguration,g=wR({requestedMethod:l,requestedHeaders:d,requestedOrigin:p,routeConfig:f,customPolicies:r});return g.isValid?new Response(void 0,{status:200,statusText:"OK",headers:g.headers}):(g.error&&c.log.warn(g.error),D.notFound(a,c))},"optionsHandler"),o=new De({processors:[He],handler:n}),i=new Ue({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(i,o.execute)},"registerCorsRoute"),wR=s(({requestedMethod:t,requestedHeaders:e,requestedOrigin:r,routeConfig:n,customPolicies:o})=>{let i={isValid:!1,headers:{}};if(n.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":r,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(n.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${n.pathPattern}'`};let a=o?.find(l=>l.name===n.corsPolicy);if(!a)throw new w(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let c=wi(a.name,a.allowedOrigins,r);return c?{isValid:!0,headers:vi(a,c)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${r}'`}},"validateAndBuildResponseHeaders");var oh=s(t=>{let e=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new De({processors:[He],handler:e}),n=new Ue({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(n,r.execute)},"registerNoRoutes");var Bt=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.mcp=e.mcp,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.metadata=e.metadata,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;metadata;custom;mcp;methods;handler;corsPolicy;policies};var vR=new Ue({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),ih=s(t=>{let e=s(async(n,o)=>{let i=za.value?.notFoundHandler;if(i){let l=new URL(n.url);return i(n,o,{get routesMatchedByPathOnly(){return t.lookupByPathOnly(l.pathname).map(p=>p.routeConfiguration).filter(p=>p instanceof Bt)}})}let a=new URL(n.url);return t.lookupByPathOnly(a.pathname).filter(l=>l.routeConfiguration.handler?.export==="mcpServerHandler").length>0&&n.method!=="POST"?D.methodNotAllowed(n,o):D.notFound(n,o)},"notFoundHandler"),r=new De({processors:[He],handler:e});t.addRoute(vR,r.execute)},"registerNotMatchedHandler");var xR=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],sh=s(t=>{xR.forEach(e=>t.delete(e))},"stripCorsHeaders"),zr=s(async(t,e,r)=>{let n=await r(t);if(P.instance.isDeno&&n.status===101&&[...n.headers.keys()].length===0&&!n.body)return n;let o=e.route,i=t.headers.get("origin"),a=xi(i,we.instance.runtimeSettings);if((!o.corsPolicy||o.corsPolicy==="none")&&!a){let p=new Headers(n.headers);return sh(p),new Response(n.body,{status:n.status,statusText:n.statusText,headers:p,webSocket:n.webSocket})}if(!(n instanceof Response))throw new le(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof n}'`);let c=RR(o,we.instance.routeData.corsPolicies,a),u=PR(i,c),l=new Headers(n.headers);return sh(l),Object.entries(u).forEach(([p,m])=>{l.set(p,m)}),new Response(n.body,{status:n.status,statusText:n.statusText,headers:l,webSocket:n.webSocket})},"corsProcessor"),RR=s((t,e,r)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};if(r)return{name:"dev-portal-anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(o=>o.name===t.corsPolicy);if(n===void 0)throw new w(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),PR=s((t,e)=>{let r=wi(e.name,e.allowedOrigins,t);return r?vi(e,r):{}},"getCorsHeaders");var ec=s(t=>{let e=s(async()=>new Response(JSON.stringify({buildId:P.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new De({processors:[zr],handler:e}),n=new Ue({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(n,r.execute)},"registerPingRoute");import{SpanStatusCode as ah,trace as ch}from"@opentelemetry/api";var Dt={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var Ri=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,r){if(!Ye(r))throw new F(`The name of a policy must be a string. Received '${r}' of type '${typeof r}'`);this.options=e,this.policyName=r,this.policyType=Object.getPrototypeOf(this).constructor.name}},Re=class extends Ri{static{s(this,"InboundPolicy")}},Vt=class extends Ri{static{s(this,"OutboundPolicy")}};var nc=class extends Re{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.policyType=e.name,this.#e=e}handler(e,r){return this.#e(e,r,this.options,this.policyName)}},oc=class extends Vt{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.policyType=e.name,this.#e=e}handler(e,r,n){return this.#e(e,r,n,this.options,this.policyName)}},tc=new Map;function Nn(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.inbound??[],n=t.path),r.filter(i=>!tc.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new w(`Invalid state - no Policy with the name '${i}' ${n&&`on route '${n}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export];if(typeof c!="function")throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof module '${typeof c}')`);let u;if(typeof c!="function")throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof module '${typeof c}')`);if(c.prototype instanceof Re)u=new c(a.handler.options,a.name);else if(typeof c=="function")u=new nc(c,a.handler.options,a.name);else throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new w(`Invalid state - invalid handler on policy '${i}' on route '${n}' (typeof handler '${typeof u.handler}')`);tc.set(a.name,u)}),r.map(i=>{let a=tc.get(i);if(a===void 0)throw new F("Internal error. Policy not found in cache.");return a})}s(Nn,"getInboundPolicyInstances");var rc=new Map;function Ln(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.outbound??[],n=t.path),r.filter(i=>!rc.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new w(`Invalid state - no Policy with the name '${i}' on route '${n}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export],u;if(typeof c!="function")throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof module '${typeof c}')`);if(c.prototype instanceof Vt)u=new c(a.handler.options??{},a.name);else if(typeof c=="function")u=new oc(c,a.handler.options??{},a.name);else throw new w(`Invalid state - invalid policy '${i}' on route '${n}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new w(`Invalid state - invalid handler on policy '${i}' on route '${n}'`);rc.set(a.name,u)}),r.map(i=>{let a=rc.get(i);if(a===void 0)throw new F("Internal error. Policy not found in cache.");return a})}s(Ln,"getOutboundPolicyInstances");var ic=s(t=>async(e,r)=>{let n=Fe.getContextExtensions(r),o=ch.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{try{let a=[...t],c=e;for(;a.length>0;){let u=a.shift();if(!u)return c;let l=await o.startActiveSpan(`policy:${u.policyName}`,async d=>{let p=await u.handler(c,r);if(p instanceof Request||p instanceof de||p instanceof Response){if(d.end(),p instanceof Response||p instanceof de)return p;{let m=c.user;return new de(p,{user:m})}}else{let m=new w(`Invalid state - invalid handler on policy '${u.policyName}' on route '${r.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:ah.ERROR}),d.recordException(m),m}});if(l instanceof de)c=l;else if(l instanceof Request){let d=c.user;c=new de(l,{user:d})}else if(l instanceof Response)return l;n.latestRequest=c}return c}finally{i.end()}})},"toStackedInboundHandler"),sc=s(t=>async(e,r,n)=>{let o=ch.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...t],c=e;for(;a.length>0;){let u=a.shift();if(!u)return c;c=await o.startActiveSpan(`policy:${u.policyName}`,async d=>{try{d.setAttribute(Dt.PolicyName,u.policyName),d.setAttribute(Dt.PolicyType,u.policyType);let p=await u.handler(c,r,n);if(p instanceof Response)return p;{let m=new w(`Invalid state - invalid handler on policy '${u.policyName}' on route '${n.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:ah.ERROR}),d.recordException(m),m}}finally{d.end()}})}return c}finally{i.end()}})},"toStackedOutboundHandler"),Pi=s(async(t,e,r)=>{let n=Nn(e.route,we.instance.routeData.policies),o=Ln(e.route,we.instance.routeData.policies);return lh({request:t,context:e,inboundPolicies:n,outboundPolicies:o,next:r})},"policyProcessor");function uh({inboundPolicies:t=[],outboundPolicies:e=[]}){return s(async(n,o,i)=>lh({request:n,context:o,inboundPolicies:t,outboundPolicies:e,next:i}),"policyProcessor")}s(uh,"createInternalPolicyProcessor");async function lh({request:t,context:e,inboundPolicies:r,outboundPolicies:n,next:o}){let i=ic(r);try{let a=await i(t,e);if(a instanceof Response)return a;let c=await o(a),u=sc(n),l;return P.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?l=u(c,t,e):l=c.ok?u(c,t,e):c,l}catch(a){return xt(t,e,"Error executing policies",a)}}s(lh,"executePolicyProcessor");var fh=Vx(mh(),1);function gh(t,e){try{let r=/v\d+(-\d+)?/g,o=(0,fh.parse)(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&r.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}s(gh,"devPortalBaseURL");var hh="/__zuplo/dev-portal",NR="dev-portal-id",LR="dev-portal-host",MR="zp-account",DR="zp-project",UR="dev-portal-build",zR=`
56
56
  <!DOCTYPE html>
57
57
  <html lang="en">
58
58
  <head>