@debugkit/cli 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -3
- package/dist/cli.js +1990 -1506
- package/dist/lambda/index.mjs +3 -3
- package/package.json +4 -4
package/dist/lambda/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var Ot=Object.defineProperty;var Ct=(s,e)=>{for(var t in e)Ot(s,t,{get:e[t],enumerable:!0})};import{DynamoDBClient as Tr}from"@aws-sdk/client-dynamodb";import{DynamoDBDocumentClient as Ir}from"@aws-sdk/lib-dynamodb";import{BatchWriteCommand as lr,GetCommand as He,PutCommand as dr,QueryCommand as qe,UpdateCommand as B}from"@aws-sdk/lib-dynamodb";var u={};Ct(u,{BRAND:()=>rs,DIRTY:()=>G,EMPTY_PATH:()=>Dt,INVALID:()=>h,NEVER:()=>Ls,OK:()=>S,ParseStatus:()=>w,Schema:()=>x,ZodAny:()=>H,ZodArray:()=>z,ZodBigInt:()=>J,ZodBoolean:()=>Q,ZodBranded:()=>we,ZodCatch:()=>ue,ZodDate:()=>X,ZodDefault:()=>ce,ZodDiscriminatedUnion:()=>Ie,ZodEffects:()=>$,ZodEnum:()=>ie,ZodError:()=>I,ZodFirstPartyTypeKind:()=>y,ZodFunction:()=>Oe,ZodIntersection:()=>re,ZodIssueCode:()=>d,ZodLazy:()=>ne,ZodLiteral:()=>ae,ZodMap:()=>ve,ZodNaN:()=>xe,ZodNativeEnum:()=>oe,ZodNever:()=>P,ZodNull:()=>te,ZodNullable:()=>j,ZodNumber:()=>Y,ZodObject:()=>R,ZodOptional:()=>O,ZodParsedType:()=>f,ZodPipeline:()=>Se,ZodPromise:()=>q,ZodReadonly:()=>le,ZodRecord:()=>Re,ZodSchema:()=>x,ZodSet:()=>_e,ZodString:()=>K,ZodSymbol:()=>ge,ZodTransformer:()=>$,ZodTuple:()=>U,ZodType:()=>x,ZodUndefined:()=>ee,ZodUnion:()=>se,ZodUnknown:()=>L,ZodVoid:()=>ye,addIssueToContext:()=>p,any:()=>ps,array:()=>gs,bigint:()=>os,boolean:()=>mt,coerce:()=>Zs,custom:()=>dt,date:()=>cs,datetimeRegex:()=>ut,defaultErrorMap:()=>V,discriminatedUnion:()=>xs,effect:()=>$s,enum:()=>Rs,function:()=>Es,getErrorMap:()=>fe,getParsedType:()=>D,instanceof:()=>as,intersection:()=>ks,isAborted:()=>Ee,isAsync:()=>me,isDirty:()=>Te,isValid:()=>W,late:()=>ns,lazy:()=>Ts,literal:()=>Is,makeIssue:()=>be,map:()=>Ss,nan:()=>is,nativeEnum:()=>Os,never:()=>ms,null:()=>ds,nullable:()=>Ps,number:()=>ft,object:()=>ys,objectUtil:()=>Ve,oboolean:()=>Vs,onumber:()=>Ms,optional:()=>Ns,ostring:()=>js,pipeline:()=>Us,preprocess:()=>Ds,promise:()=>Cs,quotelessJson:()=>$t,record:()=>ws,set:()=>As,setErrorMap:()=>Pt,strictObject:()=>vs,string:()=>pt,symbol:()=>us,transformer:()=>$s,tuple:()=>bs,undefined:()=>ls,union:()=>_s,unknown:()=>fs,util:()=>b,void:()=>hs});var b;(function(s){s.assertEqual=n=>{};function e(n){}s.assertIs=e;function t(n){throw new Error}s.assertNever=t,s.arrayToEnum=n=>{let a={};for(let i of n)a[i]=i;return a},s.getValidEnumValues=n=>{let a=s.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(let o of a)i[o]=n[o];return s.objectValues(i)},s.objectValues=n=>s.objectKeys(n).map(function(a){return n[a]}),s.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let a=[];for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},s.find=(n,a)=>{for(let i of n)if(a(i))return i},s.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function r(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}s.joinValues=r,s.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(b||(b={}));var Ve;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(Ve||(Ve={}));var f=b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),D=s=>{switch(typeof s){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(s)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(s)?f.array:s===null?f.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?f.promise:typeof Map<"u"&&s instanceof Map?f.map:typeof Set<"u"&&s instanceof Set?f.set:typeof Date<"u"&&s instanceof Date?f.date:f.object;default:return f.unknown}};var d=b.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$t=s=>JSON.stringify(s,null,2).replace(/"([^"]+)":/g,"$1:"),I=class s extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(a){return a.message},r={_errors:[]},n=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)r._errors.push(t(i));else{let o=r,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(t(i))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return n(this),r}static assert(e){if(!(e instanceof s))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,b.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let n of this.issues)if(n.path.length>0){let a=n.path[0];t[a]=t[a]||[],t[a].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};I.create=s=>new I(s);var Nt=(s,e)=>{let t;switch(s.code){case d.invalid_type:s.received===f.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case d.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,b.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:t=`Unrecognized key(s) in object: ${b.joinValues(s.keys,", ")}`;break;case d.invalid_union:t="Invalid input";break;case d.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${b.joinValues(s.options)}`;break;case d.invalid_enum_value:t=`Invalid enum value. Expected ${b.joinValues(s.options)}, received '${s.received}'`;break;case d.invalid_arguments:t="Invalid function arguments";break;case d.invalid_return_type:t="Invalid function return type";break;case d.invalid_date:t="Invalid date";break;case d.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(t=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?t=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?t=`Invalid input: must end with "${s.validation.endsWith}"`:b.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case d.too_small:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:t="Invalid input";break;case d.too_big:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?t=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:t="Invalid input";break;case d.custom:t="Invalid input";break;case d.invalid_intersection_types:t="Intersection results could not be merged";break;case d.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case d.not_finite:t="Number must be finite";break;default:t=e.defaultError,b.assertNever(s)}return{message:t}},V=Nt;var nt=V;function Pt(s){nt=s}function fe(){return nt}var be=s=>{let{data:e,path:t,errorMaps:r,issueData:n}=s,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let o="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)o=l(i,{data:e,defaultError:o}).message;return{...n,path:a,message:o}},Dt=[];function p(s,e){let t=fe(),r=be({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===V?void 0:V].filter(n=>!!n)});s.common.issues.push(r)}var w=class s{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let n of t){if(n.status==="aborted")return h;n.status==="dirty"&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let n of t){let a=await n.key,i=await n.value;r.push({key:a,value:i})}return s.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return h;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(r[a.value]=i.value)}return{status:e.value,value:r}}},h=Object.freeze({status:"aborted"}),G=s=>({status:"dirty",value:s}),S=s=>({status:"valid",value:s}),Ee=s=>s.status==="aborted",Te=s=>s.status==="dirty",W=s=>s.status==="valid",me=s=>typeof Promise<"u"&&s instanceof Promise;var m;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e?.message})(m||(m={}));var C=class{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},at=(s,e)=>{if(W(e))return{success:!0,data:e.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new I(s.common.issues);return this._error=t,this._error}}};function _(s){if(!s)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:n}=s;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,o)=>{let{message:c}=s;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??r??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??t??o.defaultError}},description:n}}var x=class{get description(){return this._def.description}_getType(e){return D(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:D(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w,ctx:{common:e.parent.common,data:e.data,parsedType:D(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(me(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)},n=this._parseSync({data:e,path:r.path,parent:r});return at(r,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return W(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>W(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)},n=this._parse({data:e,path:r.path,parent:r}),a=await(me(n)?n:Promise.resolve(n));return at(r,a)}refine(e,t){let r=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{let i=e(n),o=()=>a.addIssue({code:d.custom,...r(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof t=="function"?t(r,n):t),!1))}_refinement(e){return new $({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return O.create(this,this._def)}nullable(){return j.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return z.create(this)}promise(){return q.create(this,this._def)}or(e){return se.create([this,e],this._def)}and(e){return re.create(this,e,this._def)}transform(e){return new $({..._(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ce({..._(this._def),innerType:this,defaultValue:t,typeName:y.ZodDefault})}brand(){return new we({typeName:y.ZodBranded,type:this,..._(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ue({..._(this._def),innerType:this,catchValue:t,typeName:y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Se.create(this,e)}readonly(){return le.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ut=/^c[^\s-]{8,}$/i,jt=/^[0-9a-z]+$/,Mt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Vt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Zt=/^[a-z0-9_-]{21}$/i,Lt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Bt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ft="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ze,Wt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Kt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ht=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,qt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Gt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Yt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ot="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Jt=new RegExp(`^${ot}$`);function ct(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);let t=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Qt(s){return new RegExp(`^${ct(s)}$`)}function ut(s){let e=`${ot}T${ct(s)}`,t=[];return t.push(s.local?"Z?":"Z"),s.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Xt(s,e){return!!((e==="v4"||!e)&&Wt.test(s)||(e==="v6"||!e)&&Ht.test(s))}function es(s,e){if(!Lt.test(s))return!1;try{let[t]=s.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(r));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function ts(s,e){return!!((e==="v4"||!e)&&Kt.test(s)||(e==="v6"||!e)&&qt.test(s))}var K=class s extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.string,received:a.parsedType}),h}let r=new w,n;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(n=this._getOrReturnCtx(e,n),i?p(n,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&p(n,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")Bt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"email",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")Ze||(Ze=new RegExp(Ft,"u")),Ze.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"emoji",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")Vt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"uuid",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")Zt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"nanoid",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")Ut.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")jt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid2",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")Mt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ulid",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),p(n,{validation:"url",code:d.invalid_string,message:a.message}),r.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"regex",code:d.invalid_string,message:a.message}),r.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),r.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:{startsWith:a.value},message:a.message}),r.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?ut(a).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?Jt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?Qt(a).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?zt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:d.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?Xt(e.data,a.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ip",code:d.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?es(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"jwt",code:d.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?ts(e.data,a.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cidr",code:d.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?Gt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:d.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?Yt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64url",code:d.invalid_string,message:a.message}),r.dirty()):b.assertNever(a);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(n=>e.test(n),{validation:t,code:d.invalid_string,...m.errToObj(r)})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...m.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...m.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new s({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new s({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new s({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};K.create=s=>new K({checks:[],typeName:y.ZodString,coerce:s?.coerce??!1,..._(s)});function ss(s,e){let t=(s.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,n=t>r?t:r,a=Number.parseInt(s.toFixed(n).replace(".","")),i=Number.parseInt(e.toFixed(n).replace(".",""));return a%i/10**n}var Y=class s extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.number,received:a.parsedType}),h}let r,n=new w;for(let a of this._def.checks)a.kind==="int"?b.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:d.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?ss(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:d.not_finite,message:a.message}),n.dirty()):b.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,r,n){return new s({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&b.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Y.create=s=>new Y({checks:[],typeName:y.ZodNumber,coerce:s?.coerce||!1,..._(s)});var J=class s extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let r,n=new w;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):b.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.bigint,received:t.parsedType}),h}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,r,n){return new s({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};J.create=s=>new J({checks:[],typeName:y.ZodBigInt,coerce:s?.coerce??!1,..._(s)});var Q=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.boolean,received:r.parsedType}),h}return S(e.data)}};Q.create=s=>new Q({typeName:y.ZodBoolean,coerce:s?.coerce||!1,..._(s)});var X=class s extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.date,received:a.parsedType}),h}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_date}),h}let r=new w,n;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):b.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};X.create=s=>new X({checks:[],coerce:s?.coerce||!1,typeName:y.ZodDate,..._(s)});var ge=class extends x{_parse(e){if(this._getType(e)!==f.symbol){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.symbol,received:r.parsedType}),h}return S(e.data)}};ge.create=s=>new ge({typeName:y.ZodSymbol,..._(s)});var ee=class extends x{_parse(e){if(this._getType(e)!==f.undefined){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.undefined,received:r.parsedType}),h}return S(e.data)}};ee.create=s=>new ee({typeName:y.ZodUndefined,..._(s)});var te=class extends x{_parse(e){if(this._getType(e)!==f.null){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.null,received:r.parsedType}),h}return S(e.data)}};te.create=s=>new te({typeName:y.ZodNull,..._(s)});var H=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return S(e.data)}};H.create=s=>new H({typeName:y.ZodAny,..._(s)});var L=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return S(e.data)}};L.create=s=>new L({typeName:y.ZodUnknown,..._(s)});var P=class extends x{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.never,received:t.parsedType}),h}};P.create=s=>new P({typeName:y.ZodNever,..._(s)});var ye=class extends x{_parse(e){if(this._getType(e)!==f.undefined){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.void,received:r.parsedType}),h}return S(e.data)}};ye.create=s=>new ye({typeName:y.ZodVoid,..._(s)});var z=class s extends x{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==f.array)return p(t,{code:d.invalid_type,expected:f.array,received:t.parsedType}),h;if(n.exactLength!==null){let i=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(i||o)&&(p(t,{code:i?d.too_big:d.too_small,minimum:o?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(p(t,{code:d.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(p(t,{code:d.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>n.type._parseAsync(new C(t,i,t.path,o)))).then(i=>w.mergeArray(r,i));let a=[...t.data].map((i,o)=>n.type._parseSync(new C(t,i,t.path,o)));return w.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new s({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new s({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new s({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}};z.create=(s,e)=>new z({type:s,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,..._(e)});function he(s){if(s instanceof R){let e={};for(let t in s.shape){let r=s.shape[t];e[t]=O.create(he(r))}return new R({...s._def,shape:()=>e})}else return s instanceof z?new z({...s._def,type:he(s.element)}):s instanceof O?O.create(he(s.unwrap())):s instanceof j?j.create(he(s.unwrap())):s instanceof U?U.create(s.items.map(e=>he(e))):s}var R=class s extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=b.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let l=this._getOrReturnCtx(e);return p(l,{code:d.invalid_type,expected:f.object,received:l.parsedType}),h}let{status:r,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof P&&this._def.unknownKeys==="strip"))for(let l in n.data)i.includes(l)||o.push(l);let c=[];for(let l of i){let g=a[l],k=n.data[l];c.push({key:{status:"valid",value:l},value:g._parse(new C(n,k,n.path,l)),alwaysSet:l in n.data})}if(this._def.catchall instanceof P){let l=this._def.unknownKeys;if(l==="passthrough")for(let g of o)c.push({key:{status:"valid",value:g},value:{status:"valid",value:n.data[g]}});else if(l==="strict")o.length>0&&(p(n,{code:d.unrecognized_keys,keys:o}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let g of o){let k=n.data[g];c.push({key:{status:"valid",value:g},value:l._parse(new C(n,k,n.path,g)),alwaysSet:g in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let l=[];for(let g of c){let k=await g.key,A=await g.value;l.push({key:k,value:A,alwaysSet:g.alwaysSet})}return l}).then(l=>w.mergeObjectSync(r,l)):w.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new s({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let n=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:m.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new s({...this._def,unknownKeys:"strip"})}passthrough(){return new s({...this._def,unknownKeys:"passthrough"})}extend(e){return new s({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new s({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new s({...this._def,catchall:e})}pick(e){let t={};for(let r of b.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new s({...this._def,shape:()=>t})}omit(e){let t={};for(let r of b.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new s({...this._def,shape:()=>t})}deepPartial(){return he(this)}partial(e){let t={};for(let r of b.objectKeys(this.shape)){let n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new s({...this._def,shape:()=>t})}required(e){let t={};for(let r of b.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof O;)a=a._def.innerType;t[r]=a}return new s({...this._def,shape:()=>t})}keyof(){return lt(b.objectKeys(this.shape))}};R.create=(s,e)=>new R({shape:()=>s,unknownKeys:"strip",catchall:P.create(),typeName:y.ZodObject,..._(e)});R.strictCreate=(s,e)=>new R({shape:()=>s,unknownKeys:"strict",catchall:P.create(),typeName:y.ZodObject,..._(e)});R.lazycreate=(s,e)=>new R({shape:s,unknownKeys:"strip",catchall:P.create(),typeName:y.ZodObject,..._(e)});var se=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new I(o.ctx.common.issues));return p(t,{code:d.invalid_union,unionErrors:i}),h}if(t.common.async)return Promise.all(r.map(async a=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a,i=[];for(let c of r){let l={...t,common:{...t.common,issues:[]},parent:null},g=c._parseSync({data:t.data,path:t.path,parent:l});if(g.status==="valid")return g;g.status==="dirty"&&!a&&(a={result:g,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(c=>new I(c));return p(t,{code:d.invalid_union,unionErrors:o}),h}}get options(){return this._def.options}};se.create=(s,e)=>new se({options:s,typeName:y.ZodUnion,..._(e)});var Z=s=>s instanceof ne?Z(s.schema):s instanceof $?Z(s.innerType()):s instanceof ae?[s.value]:s instanceof ie?s.options:s instanceof oe?b.objectValues(s.enum):s instanceof ce?Z(s._def.innerType):s instanceof ee?[void 0]:s instanceof te?[null]:s instanceof O?[void 0,...Z(s.unwrap())]:s instanceof j?[null,...Z(s.unwrap())]:s instanceof we||s instanceof le?Z(s.unwrap()):s instanceof ue?Z(s._def.innerType):[],Ie=class s extends x{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return p(t,{code:d.invalid_type,expected:f.object,received:t.parsedType}),h;let r=this.discriminator,n=t.data[r],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),h)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let n=new Map;for(let a of t){let i=Z(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,a)}}return new s({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,..._(r)})}};function Le(s,e){let t=D(s),r=D(e);if(s===e)return{valid:!0,data:s};if(t===f.object&&r===f.object){let n=b.objectKeys(e),a=b.objectKeys(s).filter(o=>n.indexOf(o)!==-1),i={...s,...e};for(let o of a){let c=Le(s[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(t===f.array&&r===f.array){if(s.length!==e.length)return{valid:!1};let n=[];for(let a=0;a<s.length;a++){let i=s[a],o=e[a],c=Le(i,o);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else return t===f.date&&r===f.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}var re=class extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(a,i)=>{if(Ee(a)||Ee(i))return h;let o=Le(a.value,i.value);return o.valid?((Te(a)||Te(i))&&t.dirty(),{status:t.value,value:o.data}):(p(r,{code:d.invalid_intersection_types}),h)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};re.create=(s,e,t)=>new re({left:s,right:e,typeName:y.ZodIntersection,..._(t)});var U=class s extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.array)return p(r,{code:d.invalid_type,expected:f.array,received:r.parsedType}),h;if(r.data.length<this._def.items.length)return p(r,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),h;!this._def.rest&&r.data.length>this._def.items.length&&(p(r,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...r.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new C(r,i,r.path,o)):null}).filter(i=>!!i);return r.common.async?Promise.all(a).then(i=>w.mergeArray(t,i)):w.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new s({...this._def,rest:e})}};U.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new U({items:s,typeName:y.ZodTuple,rest:null,..._(e)})};var Re=class s extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.object)return p(r,{code:d.invalid_type,expected:f.object,received:r.parsedType}),h;let n=[],a=this._def.keyType,i=this._def.valueType;for(let o in r.data)n.push({key:a._parse(new C(r,o,r.path,o)),value:i._parse(new C(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?w.mergeObjectAsync(t,n):w.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof x?new s({keyType:e,valueType:t,typeName:y.ZodRecord,..._(r)}):new s({keyType:K.create(),valueType:e,typeName:y.ZodRecord,..._(t)})}},ve=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.map)return p(r,{code:d.invalid_type,expected:f.map,received:r.parsedType}),h;let n=this._def.keyType,a=this._def.valueType,i=[...r.data.entries()].map(([o,c],l)=>({key:n._parse(new C(r,o,r.path,[l,"key"])),value:a._parse(new C(r,c,r.path,[l,"value"]))}));if(r.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,g=await c.value;if(l.status==="aborted"||g.status==="aborted")return h;(l.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(l.value,g.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let c of i){let l=c.key,g=c.value;if(l.status==="aborted"||g.status==="aborted")return h;(l.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(l.value,g.value)}return{status:t.value,value:o}}}};ve.create=(s,e,t)=>new ve({valueType:e,keyType:s,typeName:y.ZodMap,..._(t)});var _e=class s extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.set)return p(r,{code:d.invalid_type,expected:f.set,received:r.parsedType}),h;let n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(p(r,{code:d.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&r.data.size>n.maxSize.value&&(p(r,{code:d.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());let a=this._def.valueType;function i(c){let l=new Set;for(let g of c){if(g.status==="aborted")return h;g.status==="dirty"&&t.dirty(),l.add(g.value)}return{status:t.value,value:l}}let o=[...r.data.values()].map((c,l)=>a._parse(new C(r,c,r.path,l)));return r.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,t){return new s({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new s({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};_e.create=(s,e)=>new _e({valueType:s,minSize:null,maxSize:null,typeName:y.ZodSet,..._(e)});var Oe=class s extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return p(t,{code:d.invalid_type,expected:f.function,received:t.parsedType}),h;function r(o,c){return be({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,fe(),V].filter(l=>!!l),issueData:{code:d.invalid_arguments,argumentsError:c}})}function n(o,c){return be({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,fe(),V].filter(l=>!!l),issueData:{code:d.invalid_return_type,returnTypeError:c}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof q){let o=this;return S(async function(...c){let l=new I([]),g=await o._def.args.parseAsync(c,a).catch(E=>{throw l.addIssue(r(c,E)),l}),k=await Reflect.apply(i,this,g);return await o._def.returns._def.type.parseAsync(k,a).catch(E=>{throw l.addIssue(n(k,E)),l})})}else{let o=this;return S(function(...c){let l=o._def.args.safeParse(c,a);if(!l.success)throw new I([r(c,l.error)]);let g=Reflect.apply(i,this,l.data),k=o._def.returns.safeParse(g,a);if(!k.success)throw new I([n(g,k.error)]);return k.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new s({...this._def,args:U.create(e).rest(L.create())})}returns(e){return new s({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new s({args:e||U.create([]).rest(L.create()),returns:t||L.create(),typeName:y.ZodFunction,..._(r)})}},ne=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ne.create=(s,e)=>new ne({getter:s,typeName:y.ZodLazy,..._(e)});var ae=class extends x{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),h}return{status:"valid",value:e.data}}get value(){return this._def.value}};ae.create=(s,e)=>new ae({value:s,typeName:y.ZodLiteral,..._(e)});function lt(s,e){return new ie({values:s,typeName:y.ZodEnum,..._(e)})}var ie=class s extends x{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return p(t,{expected:b.joinValues(r),received:t.parsedType,code:d.invalid_type}),h}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return p(t,{received:t.data,code:d.invalid_enum_value,options:r}),h}return S(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return s.create(e,{...this._def,...t})}exclude(e,t=this._def){return s.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};ie.create=lt;var oe=class extends x{_parse(e){let t=b.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==f.string&&r.parsedType!==f.number){let n=b.objectValues(t);return p(r,{expected:b.joinValues(n),received:r.parsedType,code:d.invalid_type}),h}if(this._cache||(this._cache=new Set(b.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=b.objectValues(t);return p(r,{received:r.data,code:d.invalid_enum_value,options:n}),h}return S(e.data)}get enum(){return this._def.values}};oe.create=(s,e)=>new oe({values:s,typeName:y.ZodNativeEnum,..._(e)});var q=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return p(t,{code:d.invalid_type,expected:f.promise,received:t.parsedType}),h;let r=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return S(r.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};q.create=(s,e)=>new q({type:s,typeName:y.ZodPromise,..._(e)});var $=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{p(r,i),i.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){let i=n.transform(r.data,a);if(r.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return h;let c=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return c.status==="aborted"?h:c.status==="dirty"?G(c.value):t.value==="dirty"?G(c.value):c});{if(t.value==="aborted")return h;let o=this._def.schema._parseSync({data:i,path:r.path,parent:r});return o.status==="aborted"?h:o.status==="dirty"?G(o.value):t.value==="dirty"?G(o.value):o}}if(n.type==="refinement"){let i=o=>{let c=n.refinement(o,a);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?h:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?h:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!W(i))return h;let o=n.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>W(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):h);b.assertNever(n)}};$.create=(s,e,t)=>new $({schema:s,typeName:y.ZodEffects,effect:e,..._(t)});$.createWithPreprocess=(s,e,t)=>new $({schema:e,effect:{type:"preprocess",transform:s},typeName:y.ZodEffects,..._(t)});var O=class extends x{_parse(e){return this._getType(e)===f.undefined?S(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};O.create=(s,e)=>new O({innerType:s,typeName:y.ZodOptional,..._(e)});var j=class extends x{_parse(e){return this._getType(e)===f.null?S(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};j.create=(s,e)=>new j({innerType:s,typeName:y.ZodNullable,..._(e)});var ce=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===f.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ce.create=(s,e)=>new ce({innerType:s,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});var ue=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return me(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new I(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new I(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};ue.create=(s,e)=>new ue({innerType:s,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});var xe=class extends x{_parse(e){if(this._getType(e)!==f.nan){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.nan,received:r.parsedType}),h}return{status:"valid",value:e.data}}};xe.create=s=>new xe({typeName:y.ZodNaN,..._(s)});var rs=Symbol("zod_brand"),we=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},Se=class s extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?h:a.status==="dirty"?(t.dirty(),G(a.value)):this._def.out._parseAsync({data:a.value,path:r.path,parent:r})})();{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?h:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new s({in:e,out:t,typeName:y.ZodPipeline})}},le=class extends x{_parse(e){let t=this._def.innerType._parse(e),r=n=>(W(n)&&(n.value=Object.freeze(n.value)),n);return me(t)?t.then(n=>r(n)):r(t)}unwrap(){return this._def.innerType}};le.create=(s,e)=>new le({innerType:s,typeName:y.ZodReadonly,..._(e)});function it(s,e){let t=typeof s=="function"?s(e):typeof s=="string"?{message:s}:s;return typeof t=="string"?{message:t}:t}function dt(s,e={},t){return s?H.create().superRefine((r,n)=>{let a=s(r);if(a instanceof Promise)return a.then(i=>{if(!i){let o=it(e,r),c=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=it(e,r),o=i.fatal??t??!0;n.addIssue({code:"custom",...i,fatal:o})}}):H.create()}var ns={object:R.lazycreate},y;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(y||(y={}));var as=(s,e={message:`Input not instance of ${s.name}`})=>dt(t=>t instanceof s,e),pt=K.create,ft=Y.create,is=xe.create,os=J.create,mt=Q.create,cs=X.create,us=ge.create,ls=ee.create,ds=te.create,ps=H.create,fs=L.create,ms=P.create,hs=ye.create,gs=z.create,ys=R.create,vs=R.strictCreate,_s=se.create,xs=Ie.create,ks=re.create,bs=U.create,ws=Re.create,Ss=ve.create,As=_e.create,Es=Oe.create,Ts=ne.create,Is=ae.create,Rs=ie.create,Os=oe.create,Cs=q.create,$s=$.create,Ns=O.create,Ps=j.create,Ds=$.createWithPreprocess,Us=Se.create,js=()=>pt().optional(),Ms=()=>ft().optional(),Vs=()=>mt().optional(),Zs={string:(s=>K.create({...s,coerce:!0})),number:(s=>Y.create({...s,coerce:!0})),boolean:(s=>Q.create({...s,coerce:!0})),bigint:(s=>J.create({...s,coerce:!0})),date:(s=>X.create({...s,coerce:!0}))};var Ls=h;function zs(s,e){let t=s.split(/[.+-]/),r=e.split(/[.+-]/);for(let n=0;n<Math.max(t.length,r.length);n++){let a=t[n]??"",i=r[n]??"",o=/^\d+$/.test(a)&&/^\d+$/.test(i)?Number(a)-Number(i):a.localeCompare(i);if(o)return o}return 0}function ht(s){let e=s.version||"unknown";return s.update?`${e}+${s.update.slice(0,12)}`:e}function ze(s,e,t,r){return s&&e?zs(e,s)>=0:!!t&&r>t}var Bs=/^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/,Fs=/^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/,Ws=[/node_modules/,/\bnative\b/,/\[native code\]/,/InternalBytecode/],Ks=/\.(?:js)?bundle\b/;function Hs(s){return s.replace(/^address at /,"")}function gt(s){if(!s)return[];let e=[];for(let t of s.split(`
|
|
2
|
-
`)){let r=Bs.exec(t)??Fs.exec(t);if(!r)continue;let[,n,a,i,o]=r,c=Hs(a??"");if(e.push({fn:n||void 0,file:c,line:Number(i),col:Number(o),inApp:Ks.test(c)?!/^(?:anonymous|eval|global code)$/.test(n??""):!Ws.some(l=>l.test(c))}),e.length>=100)break}return e}var qs=u.string().min(1).max(64).regex(/^[a-z0-9_]+(\.[a-z0-9_]+)*$/,"flow must be dotted lowercase, e.g. auth.login"),Gs=u.record(u.string().max(200)).optional(),Be=u.string().datetime({offset:!0}),Ys=u.object({model:u.string().optional(),manufacturer:u.string().optional(),brand:u.string().optional(),type:u.enum(["phone","tablet","desktop","tv","unknown"]).default("unknown"),isEmulator:u.boolean().optional(),memoryMb:u.number().optional(),screen:u.object({width:u.number(),height:u.number(),scale:u.number().optional()}).optional()}),Js=u.object({name:u.string(),version:u.string().optional()}),Qs=u.object({id:u.string().min(1),version:u.string().optional(),build:u.string().optional(),update:u.string().max(100).optional(),environment:u.string().default("production")}),Xs=u.object({name:u.string(),version:u.string().optional(),engine:u.string().optional()}),er=u.object({type:u.enum(["wifi","cellular","ethernet","none","unknown"]).default("unknown"),effectiveType:u.string().optional(),isConnected:u.boolean().optional()}),tr=u.object({app:Qs,device:Ys.default({}),os:Js,runtime:Xs,network:er.optional(),locale:u.string().optional(),timezone:u.string().optional()}),sr=u.object({ts:Be,category:u.enum(["navigation","network","ui","log","event","custom"]),message:u.string().max(500),level:u.enum(["debug","info","warning","error"]).default("info"),data:u.record(u.union([u.string(),u.number(),u.boolean(),u.null()])).optional()}),rr=u.object({fn:u.string().optional(),file:u.string().optional(),line:u.number().optional(),col:u.number().optional(),inApp:u.boolean().optional()}),nr=u.enum(["low","medium","high","critical"]),Ce=u.object({id:u.string().min(8).max(64),ts:Be,flow:qs.optional(),step:u.string().max(64).optional(),tags:Gs}),ar=Ce.extend({type:u.literal("error"),handled:u.boolean().default(!0),severity:nr.optional(),error:u.object({name:u.string().max(200).default("Error"),message:u.string().max(2e3),stack:u.string().max(2e4).optional(),frames:u.array(rr).max(100).optional()}),breadcrumbs:u.array(sr).max(50).optional(),request:u.object({method:u.string().max(10),url:u.string().max(500),status:u.number().int().optional(),durationMs:u.number().optional()}).optional()}),ir=Ce.extend({type:u.literal("event"),name:u.string().min(1).max(100),outcome:u.enum(["success","failure","abandoned"]).optional(),props:u.record(u.union([u.string(),u.number(),u.boolean(),u.null()])).optional()}),or=Ce.extend({type:u.literal("session"),status:u.enum(["started","errored","crashed"])}),cr=Ce.extend({type:u.literal("metric"),name:u.literal("http"),key:u.string().min(1).max(300),count:u.number().int().min(1).max(1e6),errors:u.number().int().min(0).max(1e6),buckets:u.array(u.number().int().min(0)).length(13)}),ur=u.discriminatedUnion("type",[ar,ir,or,cr]),vt=u.object({schema:u.literal(1).default(1),sdk:u.object({name:u.string(),version:u.string()}),context:tr,user:u.object({id:u.string().optional(),anonymousId:u.string()}).optional(),session:u.object({id:u.string(),startedAt:Be}),events:u.array(ur).min(1).max(100)});function $e(s){let e=new Map;for(let t of s){let r=Fe(t),n=e.get(r)??{app:t.app,day:t.day,dimension:t.dimension,key:t.key,errors:0,events:0};t.kind==="error"?n.errors+=t.by:n.events+=t.by,e.set(r,n)}return[...e.values()]}var Fe=s=>`${s.day}__${s.dimension}__${encodeURIComponent(s.key)}`;var We=1,Ke=3650,_t=7;var Ne=class{constructor(e,t){this.doc=e;this.opts=t}doc;opts;get table(){return this.opts.table}async registerApp(e){await this.doc.send(new dr({TableName:this.table,Item:{pk:"APPS",sk:e}}))}async writeEvents(e,t={}){let r=t.retentionDays??this.opts.retentionDays??30,n=i=>Math.floor(Date.parse(i.receivedAt)/1e3)+r*86400,a=e.flatMap(i=>{let o=`${i.event.ts}#${i.event.id}`,c={...i,ttl:n(i)},l=[{pk:`APP#${i.app}#EV#${i.day}`,sk:o,...c}];return i.fingerprint&&l.push({pk:`APP#${i.app}#ISSUEEV#${i.fingerprint}`,sk:o,...c}),l});for(let i=0;i<a.length;i+=25){let o={[this.table]:a.slice(i,i+25).map(c=>({PutRequest:{Item:c}}))};for(let c=0;o&&Object.keys(o).length&&c<5;c++)o=(await this.doc.send(new lr({RequestItems:o}))).UnprocessedItems,o&&Object.keys(o).length&&await new Promise(g=>setTimeout(g,50*2**c))}}async upsertIssues(e){let t={created:[],regressed:[]};return await Promise.all(e.map(async r=>{(await this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},UpdateExpression:"ADD #count :by SET app = :app, fingerprint = :fp, title = :title, flow = :flow, culprit = :culprit, firstSeen = if_not_exists(firstSeen, :first)",ExpressionAttributeNames:{"#count":"count"},ExpressionAttributeValues:{":by":r.by,":app":r.app,":fp":r.fingerprint,":title":r.title,":flow":r.flow??null,":culprit":r.culprit??null,":first":r.firstTs},ReturnValues:"UPDATED_OLD"}))).Attributes?.count===void 0&&t.created.push(r.fingerprint),await this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},UpdateExpression:"SET lastSeen = :ts, lastEvent = :ev, lastVersion = :v, firstVersion = if_not_exists(firstVersion, :v)",ConditionExpression:"attribute_not_exists(lastSeen) OR lastSeen < :ts",ExpressionAttributeValues:{":ts":r.ts,":ev":r.lastEvent,":v":r.version??null}})).catch(i=>{if(i.name!=="ConditionalCheckFailedException")throw i});let a=(await this.doc.send(new He({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},ProjectionExpression:"#s, resolvedIn, resolvedAt",ExpressionAttributeNames:{"#s":"status"}}))).Item;a?.status==="resolved"&&ze(a.resolvedIn,r.version,a.resolvedAt,r.ts)&&await this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},UpdateExpression:"SET #s = :r, regressedAt = :ts",ConditionExpression:"#s = :resolved",ExpressionAttributeNames:{"#s":"status"},ExpressionAttributeValues:{":r":"regressed",":ts":r.ts,":resolved":"resolved"}})).then(()=>t.regressed.push(r.fingerprint)).catch(i=>{if(i.name!=="ConditionalCheckFailedException")throw i}),await this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},UpdateExpression:"SET firstSeen = :first",ConditionExpression:"firstSeen > :first",ExpressionAttributeValues:{":first":r.firstTs}})).catch(i=>{if(i.name!=="ConditionalCheckFailedException")throw i})})),t}async incrementRollups(e){await Promise.all($e(e).map(t=>this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${t.app}#ROLLUP#${t.dimension}`,sk:`${t.day}#${t.key}`},UpdateExpression:`ADD errors :e, events :v SET app = :app, #day = :day, dimension = :dim, #key = :key${t.dimension==="issueHour"?", #ttl = :ttl":""}`,ExpressionAttributeNames:{"#day":"day","#key":"key",...t.dimension==="issueHour"?{"#ttl":"ttl"}:{}},ExpressionAttributeValues:{":e":t.errors,":v":t.events,":app":t.app,":day":t.day,":dim":t.dimension,":key":t.key,...t.dimension==="issueHour"?{":ttl":Math.floor(Date.parse(`${t.day}:00:00Z`)/1e3)+_t*86400}:{}}}))))}async markUsers(e,t){await Promise.all(t.map(r=>this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${e}#USERS#${r.scope}`,sk:r.member},UpdateExpression:"SET lastDay = :d",ConditionExpression:"attribute_not_exists(lastDay) OR lastDay < :d",ExpressionAttributeValues:{":d":r.day}})).catch(n=>{if(n.name!=="ConditionalCheckFailedException")throw n})))}async countUsers(e,t,r){let n=0,a;do{let i=await this.doc.send(new qe({TableName:this.table,KeyConditionExpression:"pk = :pk",FilterExpression:"lastDay >= :d",ExpressionAttributeValues:{":pk":`APP#${e}#USERS#${t}`,":d":r},Select:"COUNT",ExclusiveStartKey:a}));n+=i.Count??0,a=i.LastEvaluatedKey}while(a);return n}async setIssueStatus(e,t,r){let n=r.status==="resolved",a=await this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${e}#ISSUE`,sk:t},UpdateExpression:n?"SET #s = :s, resolvedAt = :at, resolvedIn = :in REMOVE regressedAt":"SET #s = :s REMOVE resolvedIn, resolvedAt, regressedAt",ConditionExpression:"attribute_exists(pk)",ExpressionAttributeNames:{"#s":"status"},ExpressionAttributeValues:n?{":s":r.status,":at":new Date().toISOString(),":in":r.resolvedIn??null}:{":s":r.status},ReturnValues:"ALL_NEW"})).catch(i=>{if(i.name==="ConditionalCheckFailedException")return null;throw i});return a?.Attributes?de(a.Attributes):null}async getSettings(e){let t=await this.doc.send(new He({TableName:this.table,Key:{pk:`APP#${e}#SETTINGS`,sk:"app"}}));return t.Item?de(t.Item):null}async putSettings(e,t){let r=Object.fromEntries(Object.entries({...t,updatedAt:new Date().toISOString()}).filter(([,i])=>i!==void 0)),n=Object.keys(r),a=await this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${e}#SETTINGS`,sk:"app"},UpdateExpression:`SET ${n.map((i,o)=>`#n${o} = :v${o}`).join(", ")}`,ExpressionAttributeNames:Object.fromEntries(n.map((i,o)=>[`#n${o}`,i])),ExpressionAttributeValues:Object.fromEntries(n.map((i,o)=>[`:v${o}`,r[i]])),ReturnValues:"ALL_NEW"}));return de(a.Attributes??r)}async restampExpiry(e,t,{cursor:r}={}){let n=r?Number(r):0,a=0;for(let i=0;i<30&&n<=3650;i++,n++){let o=new Date(Date.now()-n*864e5).toISOString().slice(0,10),c=await this.queryAll({pk:`APP#${e}#EV#${o}`});for(let l of c){let g=Math.floor(Date.parse(l.receivedAt)/1e3)+t*86400,k=[{pk:l.pk,sk:l.sk},...l.fingerprint?[{pk:`APP#${e}#ISSUEEV#${l.fingerprint}`,sk:l.sk}]:[]];await Promise.all(k.map(A=>this.doc.send(new B({TableName:this.table,Key:A,UpdateExpression:"SET #t = :t",ConditionExpression:"attribute_exists(pk)",ExpressionAttributeNames:{"#t":"ttl"},ExpressionAttributeValues:{":t":g}})).catch(E=>{if(E.name!=="ConditionalCheckFailedException")throw E}))),a++}if(c.length){n++;break}}return{updated:a,cursor:n<=3650?String(n):void 0}}async listApps(){return(await this.queryAll({pk:"APPS"})).map(e=>e.sk).sort()}async listIssues(e,{limit:t=200}={}){return(await this.queryAll({pk:`APP#${e}#ISSUE`})).sort((n,a)=>a.lastSeen.localeCompare(n.lastSeen)).slice(0,t).map(de)}async getIssue(e,t){let r=await this.doc.send(new He({TableName:this.table,Key:{pk:`APP#${e}#ISSUE`,sk:t}}));return r.Item?de(r.Item):null}async getRollups(e,t,r,n){return(await this.queryAll({pk:`APP#${e}#ROLLUP#${t}`,between:[`${r}#`,`${n}#\uFFFF`]})).map(i=>de(i))}async listIssueEvents(e,t,{limit:r=50}={}){return((await this.doc.send(new qe({TableName:this.table,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":`APP#${e}#ISSUEEV#${t}`},ScanIndexForward:!1,Limit:r}))).Items??[]).map(a=>de(a))}async queryAll({pk:e,between:t}){let r=[],n;do{let a=await this.doc.send(new qe({TableName:this.table,KeyConditionExpression:t?"pk = :pk AND sk BETWEEN :a AND :b":"pk = :pk",ExpressionAttributeValues:t?{":pk":e,":a":t[0],":b":t[1]}:{":pk":e},ExclusiveStartKey:n}));r.push(...a.Items??[]),n=a.LastEvaluatedKey}while(n);return r}};function de(s){let{pk:e,sk:t,ttl:r,...n}=s;return n}import{createHash as wr}from"crypto";import{timingSafeEqual as mr}from"crypto";var Ae=/^https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9/_-]{10,200}$/,Pe=new Map,pr=36e5,fr=(s,e)=>fetch(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(3e3)});async function Ge(s,e,t,r,n=fr){let a=r?.alerts;if(!e||!a?.slackWebhookUrl||!Ae.test(a.slackWebhookUrl))return 0;let i=new Set(r?.criticalFlows??[]),o=[...a.newIssues!==!1?e.created.map(l=>({fp:l,kind:"new"})):[],...a.regressions!==!1?e.regressed.map(l=>({fp:l,kind:"regressed"})):[]].filter(({fp:l})=>!a.onlyCriticalFlows||i.has(t.get(l)?.flow??"")).filter(({fp:l,kind:g})=>{let k=`${s}|${l}|${g}`,A=Pe.get(k);return A&&Date.now()-A<pr?!1:(Pe.set(k,Date.now()),!0)}).slice(0,10);Pe.size>5e3&&Pe.clear();let c=0;for(let{fp:l,kind:g}of o){let k=t.get(l);if(!k)continue;let A=a.dashboardUrl?`${a.dashboardUrl.replace(/\/+$/,"")}/issues/${l}?app=${encodeURIComponent(s)}`:void 0,E=[k.culprit&&`\`${k.culprit}\``,k.flow&&`flow \`${k.flow}\`${i.has(k.flow)?" (critical)":""}`,k.version&&`version ${k.version}`].filter(Boolean).join(" \xB7 "),Me=`${g==="new"?":new: New issue":":rotating_light: Regressed"} in *${s}*: ${A?`<${A}|${k.title}>`:k.title}${E?`
|
|
3
|
-
${E}`:""}`;try{await n(a.slackWebhookUrl,{text:Me}),c++}catch(pe){console.error("[deBug] Slack alert failed",pe)}}return c}var Ye=30,hr=6e4,Je=new Map;async function De(s,e){let t=Je.get(e);if(t&&Date.now()-t.at<hr)return t.settings;let r;try{r=await s.getSettings(e)}catch{r=null}return Je.set(e,{at:Date.now(),settings:r}),r}async function Ue(s,e,t){return(await De(s,e))?.retentionDays??t??Ye}function xt(s){return s?.alerts?.slackWebhookUrl?{...s,alerts:{...s.alerts,slackWebhookUrl:`https://hooks.slack.com/\u2026${s.alerts.slackWebhookUrl.slice(-4)}`}}:s}var gr=/^[a-z0-9_]+(\.[a-z0-9_]+)*$/;function yr(s,e){let t={};if(s.retentionDays!==void 0){let r=Number(s.retentionDays);if(!Number.isInteger(r)||r<We||r>Ke)return`retentionDays must be a whole number from ${We} to ${Ke}`;t.retentionDays=r}if(s.criticalFlows!==void 0){if(!Array.isArray(s.criticalFlows)||s.criticalFlows.length>30||!s.criticalFlows.every(r=>typeof r=="string"&&r.length<=64&&gr.test(r)))return"criticalFlows must be up to 30 dotted lowercase flow names, like checkout.payment";t.criticalFlows=[...new Set(s.criticalFlows)]}if(s.alerts!==void 0){let r=s.alerts;if(!r||typeof r!="object")return"alerts must be an object";let n={},a=r.slackWebhookUrl;if(typeof a=="string"&&a.includes("\u2026"))n.slackWebhookUrl=e?.alerts?.slackWebhookUrl;else if(a===""||a===null||a===void 0)n.slackWebhookUrl=void 0;else if(typeof a=="string"&&Ae.test(a))n.slackWebhookUrl=a;else return"slackWebhookUrl must be a Slack incoming-webhook URL (https://hooks.slack.com/services/\u2026)";for(let i of["newIssues","regressions","onlyCriticalFlows"])typeof r[i]=="boolean"&&(n[i]=r[i]);if(typeof r.dashboardUrl=="string"&&r.dashboardUrl){if(!/^https?:\/\/[^\s]{3,300}$/.test(r.dashboardUrl))return"dashboardUrl must be an http(s) URL";n.dashboardUrl=r.dashboardUrl}t.alerts=n}return Object.keys(t).length?t:"nothing to change"}function vr(s,e){let t=Buffer.from((s??"").replace(/^Bearer\s+/i,"")),r=Buffer.from(e);return t.length===r.length&&mr(t,r)}var _r=/^[a-z0-9][a-z0-9._-]{0,63}$/i;async function Qe(s,e){if(!e.adminToken||e.adminToken.length<16)return{status:404,body:{ok:!1,error:"admin routes are off (set DEBUG_ADMIN_TOKEN)"}};if(!vr(s.authorization,e.adminToken))return{status:401,body:{ok:!1,error:"unauthorized"}};let t={};if(s.method!=="GET"&&s.body)try{t=JSON.parse(s.body)}catch{return{status:400,body:{ok:!1,error:"invalid json"}}}let r=String((s.method==="GET"?s.query?.app:t.app)??"");if(!_r.test(r))return{status:400,body:{ok:!1,error:"app is required"}};let n=s.path.replace(/\/+$/,"").replace(/^.*\/admin/,"");if(n==="/settings"&&s.method==="GET"){let a=await e.store.getSettings(r);return{status:200,body:{ok:!0,settings:xt(a),retentionDays:a?.retentionDays??e.retentionDays??Ye}}}if(n==="/settings"&&(s.method==="PUT"||s.method==="POST")){let a=await e.store.getSettings(r),i=yr(t,a);if(typeof i=="string")return{status:400,body:{ok:!1,error:i}};let o=await e.store.putSettings(r,i);return Je.delete(r),{status:200,body:{ok:!0,settings:xt(o),retentionDays:o.retentionDays??e.retentionDays??Ye}}}if(n==="/alert-test"&&s.method==="POST"){let a=(await e.store.getSettings(r))?.alerts?.slackWebhookUrl;if(!a||!Ae.test(a))return{status:400,body:{ok:!1,error:"No Slack webhook is set for this app"}};let i=await fetch(a,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:`:white_check_mark: deBug alerts for *${r}* are working.`}),signal:AbortSignal.timeout(5e3)}).catch(o=>o);return i instanceof Error||!i.ok?{status:502,body:{ok:!1,error:`Slack didn't accept it: ${i instanceof Error?i.message:i.status}`}}:{status:200,body:{ok:!0}}}if(n==="/restamp"&&s.method==="POST"){let a=await Ue(e.store,r,e.retentionDays),i=await e.store.restampExpiry(r,a,{cursor:typeof t.cursor=="string"?t.cursor:void 0});return{status:200,body:{ok:!0,retentionDays:a,...i}}}if(n==="/issue"&&(s.method==="PUT"||s.method==="POST")){let a=String(t.fingerprint??""),i=String(t.status??"");if(!/^[a-f0-9]{8,64}$/.test(a))return{status:400,body:{ok:!1,error:"fingerprint is required"}};if(i!=="open"&&i!=="resolved"&&i!=="ignored")return{status:400,body:{ok:!1,error:"status must be open, resolved or ignored"}};let o=typeof t.resolvedIn=="string"&&t.resolvedIn.trim()?t.resolvedIn.trim().slice(0,100):void 0,c=await e.store.setIssueStatus(r,a,{status:i,resolvedIn:i==="resolved"?o:void 0});return c?{status:200,body:{ok:!0,status:c.status,resolvedIn:c.resolvedIn??null}}:{status:404,body:{ok:!1,error:"no such issue"}}}return{status:404,body:{ok:!1,error:"not found"}}}var xr={"Africa/Johannesburg":"ZA","Africa/Lagos":"NG","Africa/Nairobi":"KE","Africa/Cairo":"EG","Africa/Casablanca":"MA","Africa/Accra":"GH","Africa/Harare":"ZW","Africa/Lusaka":"ZM","Africa/Maputo":"MZ","Africa/Windhoek":"NA","Africa/Gaborone":"BW","Africa/Kampala":"UG","Africa/Dar_es_Salaam":"TZ","Africa/Addis_Ababa":"ET","Africa/Kigali":"RW","Africa/Algiers":"DZ","Africa/Tunis":"TN","Africa/Abidjan":"CI","Africa/Dakar":"SN","Africa/Luanda":"AO","Europe/London":"GB","Europe/Dublin":"IE","Europe/Paris":"FR","Europe/Berlin":"DE","Europe/Madrid":"ES","Europe/Rome":"IT","Europe/Amsterdam":"NL","Europe/Brussels":"BE","Europe/Lisbon":"PT","Europe/Stockholm":"SE","Europe/Oslo":"NO","Europe/Copenhagen":"DK","Europe/Helsinki":"FI","Europe/Warsaw":"PL","Europe/Zurich":"CH","Europe/Vienna":"AT","Europe/Athens":"GR","Europe/Istanbul":"TR","Europe/Moscow":"RU","Europe/Kyiv":"UA","Europe/Kiev":"UA","Europe/Prague":"CZ","Europe/Budapest":"HU","Europe/Bucharest":"RO","America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","America/Phoenix":"US","America/Anchorage":"US","Pacific/Honolulu":"US","America/Detroit":"US","America/Toronto":"CA","America/Vancouver":"CA","America/Edmonton":"CA","America/Halifax":"CA","America/Mexico_City":"MX","America/Sao_Paulo":"BR","America/Argentina/Buenos_Aires":"AR","America/Bogota":"CO","America/Lima":"PE","America/Santiago":"CL","Asia/Dubai":"AE","Asia/Riyadh":"SA","Asia/Qatar":"QA","Asia/Jerusalem":"IL","Asia/Kolkata":"IN","Asia/Calcutta":"IN","Asia/Karachi":"PK","Asia/Dhaka":"BD","Asia/Bangkok":"TH","Asia/Jakarta":"ID","Asia/Singapore":"SG","Asia/Kuala_Lumpur":"MY","Asia/Manila":"PH","Asia/Ho_Chi_Minh":"VN","Asia/Hong_Kong":"HK","Asia/Shanghai":"CN","Asia/Tokyo":"JP","Asia/Seoul":"KR","Asia/Taipei":"TW","Australia/Sydney":"AU","Australia/Melbourne":"AU","Australia/Brisbane":"AU","Australia/Perth":"AU","Australia/Adelaide":"AU","Pacific/Auckland":"NZ","Indian/Mauritius":"MU"};function Xe(s){let e=s.timezone?xr[s.timezone]:void 0;return e||(/[-_]([A-Z]{2})(?:\b|$)/.exec(s.locale??"")?.[1]??"unknown")}import{createHash as kr}from"crypto";function br(s){return s.replace(/https?:\/\/\S+/g,"<url>").replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,"<uuid>").replace(/\b[0-9a-f]{16,}\b/gi,"<hex>").replace(/[\w.+-]+@[\w-]+\.[\w.]+/g,"<email>").replace(/\d+(\.\d+)?/g,"<n>").replace(/(["'`]).*?\1/g,"<str>").trim().slice(0,300)}function kt(s){if(!s)return"";let e=s.replace(/\/\/&.*$/,"").replace(/[?#].*$/,"").replace(/^[a-z]+:\/\/[^/]+/i,"");if(/\.(?:js)?bundle$/.test(e))return e.replace(/^.*\//,"");for(let t of["/src/","/lib/","/app/"]){let r=e.lastIndexOf(t);if(r>=0){e=e.slice(r+1);break}}return e.replace(/\.[0-9a-f]{6,}\./g,".")}function bt(s){return s?.find(e=>e.inApp!==!1&&e.file)??s?.[0]}function wt(s){let e=bt(s.error.frames);if(!e)return;let t=kt(e.file)+(e.line?`:${e.line}`:"");return e.fn?`${e.fn} (${t})`:t}function St(s){let e=bt(s.error.frames),t=s.request,r=t?`${t.method.toUpperCase()} ${t.url} ${t.status?`${Math.floor(t.status/100)}xx`:"failed"}`:e?`${e.fn??"?"}@${kt(e.file)}`:br(s.error.message);return kr("sha256").update([s.error.name,r,s.flow??""].join("|")).digest("hex").slice(0,24)}function At(s){return`${s.error.name}: ${s.error.message}`.slice(0,200)}function Tt(s){let e={};for(let t of(s??"").split(",").map(r=>r.trim()).filter(Boolean)){let[r,n]=t.split(":");r&&n&&(e[r]=n)}return e}var Et=s=>s.slice(0,10);function Sr(s,e){let t=Date.parse(s),r=e.getTime();return Number.isNaN(t)||t>r+5*6e4||t<r-7*864e5?e.toISOString():new Date(t).toISOString()}function Ar(s){return{...s,os:{...s.os,name:s.os.name.toLowerCase()},runtime:{...s.runtime,name:s.runtime.name.toLowerCase()}}}async function It(s,e,t){let r=t.now?.()??new Date;if(!e||!t.keys[e])return{status:401,body:{ok:!1,error:"invalid ingest key"}};if(Buffer.byteLength(s)>(t.maxBytes??512*1024))return{status:413,body:{ok:!1,error:"payload too large"}};let n;try{n=JSON.parse(s)}catch{return{status:400,body:{ok:!1,error:"invalid json"}}}let a=vt.safeParse(n);if(!a.success)return{status:400,body:{ok:!1,error:"invalid envelope",issues:a.error.flatten()}};let i=a.data,o=i.context.app.id;if(t.keys[e]!==o&&t.keys[e]!=="*")return{status:403,body:{ok:!1,error:`key not allowed for app ${o}`}};let c=Ar(i.context),l=r.toISOString(),g=[],k=[],A=new Map,E=new Set;for(let st of i.events){let v={...st,ts:Sr(st.ts,r)};v.type==="error"&&!v.error.frames?.length&&v.error.stack&&(v.error.frames=gt(v.error.stack));let F=Et(v.ts);if(v.type==="session"){k.push({app:o,day:F,dimension:"session",key:`${c.app.version||"unknown"}|${v.status}`,kind:"event",by:1}),E.add("app"),v.status==="started"&&k.push({app:o,day:F,dimension:"release",key:ht(c.app),kind:"event",by:1}),v.status==="crashed"&&E.add("crash");continue}if(E.add("app"),v.type==="metric"){k.push({app:o,day:F,dimension:"requests",key:v.key,kind:"event",by:v.count}),v.errors&&k.push({app:o,day:F,dimension:"requests",key:v.key,kind:"error",by:v.errors}),v.buckets.forEach((T,ke)=>T&&k.push({app:o,day:F,dimension:"latency",key:`${v.key}|${ke}`,kind:"event",by:T}));continue}let rt=v.type==="error"?"error":"event",N=(T,ke)=>k.push({app:o,day:F,dimension:T,key:ke||"unknown",kind:rt,by:1}),M;if(v.type==="error"){M=St(v);let T=A.get(M),ke={app:o,day:F,fingerprint:M,event:v,context:c,user:i.user,sessionId:i.session.id,receivedAt:l};A.set(M,{app:o,fingerprint:M,title:At(v),culprit:wt(v),flow:v.flow,by:(T?.by??0)+1,ts:T&&T.ts>v.ts?T.ts:v.ts,firstTs:T&&T.firstTs<v.ts?T.firstTs:v.ts,lastEvent:T&&T.ts>v.ts?T.lastEvent:ke,version:c.app.version}),E.add(`issue:${M}`),N("issue",M),v.request&&N("endpoint",`${v.request.method.toUpperCase()} ${v.request.url}`),k.push({app:o,day:v.ts.slice(0,13),dimension:"issueHour",key:M,kind:rt,by:1})}N("total","all"),N("flow",v.flow??"untagged"),N("os",`${c.os.name} ${c.os.version??""}`.trim()),N("appVersion",c.app.version),N("deviceModel",c.device.model),v.type==="event"&&v.outcome&&v.flow&&(N("flowOutcome",`${v.flow}|${v.outcome}`),v.step&&N("flowStep",`${v.flow}|${v.step}|${v.outcome}`)),v.type==="error"&&(N("network",c.network?.type),N("country",Xe(c))),g.push({app:o,day:F,fingerprint:M,event:v,context:c,user:i.user,sessionId:i.session.id,receivedAt:l})}await t.store.registerApp(o);let Me=g.length?await Ue(t.store,o,t.retentionDays):void 0,[,pe]=await Promise.all([g.length?t.store.writeEvents(g,{retentionDays:Me}):void 0,t.store.upsertIssues([...A.values()]),t.store.incrementRollups(k),Er(t.store,o,i.user?.id??i.user?.anonymousId??i.session.id,E,Et(l))]);return pe&&(pe.created.length||pe.regressed.length)&&await Ge(o,pe,A,await De(t.store,o)),{status:202,body:{ok:!0,accepted:i.events.length}}}var je=new Set;async function Er(s,e,t,r,n){if(!r.size)return;let a=wr("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24),i=[];for(let o of r){let c=`${e}|${o}|${a}|${n}`;je.has(c)||(je.add(c),i.push({scope:o,member:a,day:n}))}je.size>5e4&&je.clear(),i.length&&await s.markUsers(e,i)}var et={"access-control-allow-origin":"*","access-control-allow-methods":"POST, OPTIONS","access-control-allow-headers":"content-type, x-debug-key","access-control-max-age":"86400"};function Rt(s){return async e=>{let t=e.requestContext?.http?.method??e.httpMethod??"POST",r=e.rawPath??e.requestContext?.http?.path??e.path??"/";if(r.startsWith("/admin")){let i=Object.fromEntries(Object.entries(e.headers??{}).map(([c,l])=>[c.toLowerCase(),l])),o=e.isBase64Encoded?Buffer.from(e.body??"","base64").toString("utf8"):e.body??"";try{let c=await Qe({method:t,path:r,query:e.queryStringParameters??{},body:o,authorization:i.authorization},{store:s.store,adminToken:s.adminToken,retentionDays:s.retentionDays});return{statusCode:c.status,headers:{"content-type":"application/json"},body:JSON.stringify(c.body)}}catch(c){return console.error("[deBug] admin request failed",c),{statusCode:500,headers:{"content-type":"application/json"},body:JSON.stringify({ok:!1,error:"internal"})}}}if(t==="OPTIONS")return{statusCode:204,headers:et,body:""};if(t!=="POST")return tt(405,{ok:!1,error:"method not allowed"});let n=Object.fromEntries(Object.entries(e.headers??{}).map(([i,o])=>[i.toLowerCase(),o])),a=e.isBase64Encoded?Buffer.from(e.body??"","base64").toString("utf8"):e.body??"";try{let i=await It(a,n["x-debug-key"],s);return tt(i.status,i.body)}catch(i){return console.error("[deBug] ingest failed",i),tt(500,{ok:!1,error:"internal"})}}}var tt=(s,e)=>({statusCode:s,headers:{...et,"content-type":"application/json"},body:JSON.stringify(e)});var Rr=Ir.from(new Tr({}),{marshallOptions:{removeUndefinedValues:!0}}),Gn=Rt({store:new Ne(Rr,{table:process.env.DEBUG_TABLE??"debugkit"}),keys:Tt(process.env.DEBUG_INGEST_KEYS),retentionDays:Number(process.env.DEBUG_RETENTION_DAYS)||void 0,adminToken:process.env.DEBUG_ADMIN_TOKEN});export{Gn as handler};
|
|
1
|
+
var Lt=Object.defineProperty;var Zt=(s,e)=>{for(var t in e)Lt(s,t,{get:e[t],enumerable:!0})};import{DynamoDBClient as Lr}from"@aws-sdk/client-dynamodb";import{DynamoDBDocumentClient as Zr}from"@aws-sdk/lib-dynamodb";import{BatchWriteCommand as br,GetCommand as Ee,PutCommand as Qe,QueryCommand as De,UpdateCommand as V}from"@aws-sdk/lib-dynamodb";var l={};Zt(l,{BRAND:()=>fs,DIRTY:()=>J,EMPTY_PATH:()=>Wt,INVALID:()=>g,NEVER:()=>Js,OK:()=>S,ParseStatus:()=>A,Schema:()=>b,ZodAny:()=>Y,ZodArray:()=>W,ZodBigInt:()=>X,ZodBoolean:()=>ee,ZodBranded:()=>Ae,ZodCatch:()=>de,ZodDate:()=>te,ZodDefault:()=>le,ZodDiscriminatedUnion:()=>Ce,ZodEffects:()=>N,ZodEnum:()=>ce,ZodError:()=>R,ZodFirstPartyTypeKind:()=>y,ZodFunction:()=>Ne,ZodIntersection:()=>ie,ZodIssueCode:()=>d,ZodLazy:()=>ae,ZodLiteral:()=>oe,ZodMap:()=>_e,ZodNaN:()=>xe,ZodNativeEnum:()=>ue,ZodNever:()=>M,ZodNull:()=>re,ZodNullable:()=>U,ZodNumber:()=>Q,ZodObject:()=>O,ZodOptional:()=>C,ZodParsedType:()=>f,ZodPipeline:()=>Se,ZodPromise:()=>G,ZodReadonly:()=>pe,ZodRecord:()=>$e,ZodSchema:()=>b,ZodSet:()=>be,ZodString:()=>q,ZodSymbol:()=>ye,ZodTransformer:()=>N,ZodTuple:()=>j,ZodType:()=>b,ZodUndefined:()=>se,ZodUnion:()=>ne,ZodUnknown:()=>F,ZodVoid:()=>ve,addIssueToContext:()=>p,any:()=>ks,array:()=>Es,bigint:()=>ys,boolean:()=>bt,coerce:()=>Gs,custom:()=>yt,date:()=>vs,datetimeRegex:()=>ht,defaultErrorMap:()=>B,discriminatedUnion:()=>Os,effect:()=>Bs,enum:()=>Vs,function:()=>Ds,getErrorMap:()=>me,getParsedType:()=>D,instanceof:()=>hs,intersection:()=>Cs,isAborted:()=>Re,isAsync:()=>he,isDirty:()=>Oe,isValid:()=>K,late:()=>ms,lazy:()=>js,literal:()=>Us,makeIssue:()=>we,map:()=>Ps,nan:()=>gs,nativeEnum:()=>Ls,never:()=>As,null:()=>xs,nullable:()=>Fs,number:()=>_t,object:()=>Ts,objectUtil:()=>Fe,oboolean:()=>Ys,onumber:()=>qs,optional:()=>zs,ostring:()=>Ks,pipeline:()=>Hs,preprocess:()=>Ws,promise:()=>Zs,quotelessJson:()=>Bt,record:()=>Ns,set:()=>Ms,setErrorMap:()=>Ft,strictObject:()=>Is,string:()=>vt,symbol:()=>_s,transformer:()=>Bs,tuple:()=>$s,undefined:()=>bs,union:()=>Rs,unknown:()=>ws,util:()=>k,void:()=>Ss});var k;(function(s){s.assertEqual=n=>{};function e(n){}s.assertIs=e;function t(n){throw new Error}s.assertNever=t,s.arrayToEnum=n=>{let i={};for(let a of n)i[a]=a;return i},s.getValidEnumValues=n=>{let i=s.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),a={};for(let o of i)a[o]=n[o];return s.objectValues(a)},s.objectValues=n=>s.objectKeys(n).map(function(i){return n[i]}),s.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&i.push(a);return i},s.find=(n,i)=>{for(let a of n)if(i(a))return a},s.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function r(n,i=" | "){return n.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}s.joinValues=r,s.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(k||(k={}));var Fe;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(Fe||(Fe={}));var f=k.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),D=s=>{switch(typeof s){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(s)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(s)?f.array:s===null?f.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?f.promise:typeof Map<"u"&&s instanceof Map?f.map:typeof Set<"u"&&s instanceof Set?f.set:typeof Date<"u"&&s instanceof Date?f.date:f.object;default:return f.unknown}};var d=k.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Bt=s=>JSON.stringify(s,null,2).replace(/"([^"]+)":/g,"$1:"),R=class s extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},r={_errors:[]},n=i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(n);else if(a.code==="invalid_return_type")n(a.returnTypeError);else if(a.code==="invalid_arguments")n(a.argumentsError);else if(a.path.length===0)r._errors.push(t(a));else{let o=r,c=0;for(;c<a.path.length;){let u=a.path[c];c===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return n(this),r}static assert(e){if(!(e instanceof s))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,k.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];t[i]=t[i]||[],t[i].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};R.create=s=>new R(s);var zt=(s,e)=>{let t;switch(s.code){case d.invalid_type:s.received===f.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case d.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,k.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:t=`Unrecognized key(s) in object: ${k.joinValues(s.keys,", ")}`;break;case d.invalid_union:t="Invalid input";break;case d.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${k.joinValues(s.options)}`;break;case d.invalid_enum_value:t=`Invalid enum value. Expected ${k.joinValues(s.options)}, received '${s.received}'`;break;case d.invalid_arguments:t="Invalid function arguments";break;case d.invalid_return_type:t="Invalid function return type";break;case d.invalid_date:t="Invalid date";break;case d.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(t=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?t=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?t=`Invalid input: must end with "${s.validation.endsWith}"`:k.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case d.too_small:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:t="Invalid input";break;case d.too_big:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?t=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:t="Invalid input";break;case d.custom:t="Invalid input";break;case d.invalid_intersection_types:t="Intersection results could not be merged";break;case d.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case d.not_finite:t="Number must be finite";break;default:t=e.defaultError,k.assertNever(s)}return{message:t}},B=zt;var lt=B;function Ft(s){lt=s}function me(){return lt}var we=s=>{let{data:e,path:t,errorMaps:r,issueData:n}=s,i=[...t,...n.path||[]],a={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let o="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)o=u(a,{data:e,defaultError:o}).message;return{...n,path:i,message:o}},Wt=[];function p(s,e){let t=me(),r=we({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===B?void 0:B].filter(n=>!!n)});s.common.issues.push(r)}var A=class s{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let n of t){if(n.status==="aborted")return g;n.status==="dirty"&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let n of t){let i=await n.key,a=await n.value;r.push({key:i,value:a})}return s.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:i,value:a}=n;if(i.status==="aborted"||a.status==="aborted")return g;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||n.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}},g=Object.freeze({status:"aborted"}),J=s=>({status:"dirty",value:s}),S=s=>({status:"valid",value:s}),Re=s=>s.status==="aborted",Oe=s=>s.status==="dirty",K=s=>s.status==="valid",he=s=>typeof Promise<"u"&&s instanceof Promise;var m;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e?.message})(m||(m={}));var $=class{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},dt=(s,e)=>{if(K(e))return{success:!0,data:e.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new R(s.common.issues);return this._error=t,this._error}}};function _(s){if(!s)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:n}=s;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(a,o)=>{let{message:c}=s;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??r??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??t??o.defaultError}},description:n}}var b=class{get description(){return this._def.description}_getType(e){return D(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:D(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new A,ctx:{common:e.parent.common,data:e.data,parsedType:D(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(he(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)},n=this._parseSync({data:e,path:r.path,parent:r});return dt(r,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return K(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>K(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)},n=this._parse({data:e,path:r.path,parent:r}),i=await(he(n)?n:Promise.resolve(n));return dt(r,i)}refine(e,t){let r=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,i)=>{let a=e(n),o=()=>i.addIssue({code:d.custom,...r(n)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof t=="function"?t(r,n):t),!1))}_refinement(e){return new N({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return C.create(this,this._def)}nullable(){return U.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return W.create(this)}promise(){return G.create(this,this._def)}or(e){return ne.create([this,e],this._def)}and(e){return ie.create(this,e,this._def)}transform(e){return new N({..._(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new le({..._(this._def),innerType:this,defaultValue:t,typeName:y.ZodDefault})}brand(){return new Ae({typeName:y.ZodBranded,type:this,..._(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new de({..._(this._def),innerType:this,catchValue:t,typeName:y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Se.create(this,e)}readonly(){return pe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ht=/^c[^\s-]{8,}$/i,Kt=/^[0-9a-z]+$/,qt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Yt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Gt=/^[a-z0-9_-]{21}$/i,Jt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Qt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Xt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,es="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",We,ts=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ss=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,rs=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ns=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,is=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,as=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ft="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",os=new RegExp(`^${ft}$`);function mt(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);let t=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function cs(s){return new RegExp(`^${mt(s)}$`)}function ht(s){let e=`${ft}T${mt(s)}`,t=[];return t.push(s.local?"Z?":"Z"),s.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function us(s,e){return!!((e==="v4"||!e)&&ts.test(s)||(e==="v6"||!e)&&rs.test(s))}function ls(s,e){if(!Jt.test(s))return!1;try{let[t]=s.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(r));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function ds(s,e){return!!((e==="v4"||!e)&&ss.test(s)||(e==="v6"||!e)&&ns.test(s))}var q=class s extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let i=this._getOrReturnCtx(e);return p(i,{code:d.invalid_type,expected:f.string,received:i.parsedType}),g}let r=new A,n;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(n=this._getOrReturnCtx(e,n),a?p(n,{code:d.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&p(n,{code:d.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Xt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"email",code:d.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")We||(We=new RegExp(es,"u")),We.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"emoji",code:d.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Yt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"uuid",code:d.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Gt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"nanoid",code:d.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Ht.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid",code:d.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Kt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid2",code:d.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")qt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ulid",code:d.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),p(n,{validation:"url",code:d.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"regex",code:d.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?ht(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?os.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?cs(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Qt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:d.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?us(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ip",code:d.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?ls(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"jwt",code:d.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?ds(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cidr",code:d.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?is.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:d.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?as.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64url",code:d.invalid_string,message:i.message}),r.dirty()):k.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(n=>e.test(n),{validation:t,code:d.invalid_string,...m.errToObj(r)})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...m.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...m.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new s({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new s({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new s({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};q.create=s=>new q({checks:[],typeName:y.ZodString,coerce:s?.coerce??!1,..._(s)});function ps(s,e){let t=(s.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,n=t>r?t:r,i=Number.parseInt(s.toFixed(n).replace(".","")),a=Number.parseInt(e.toFixed(n).replace(".",""));return i%a/10**n}var Q=class s extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let i=this._getOrReturnCtx(e);return p(i,{code:d.invalid_type,expected:f.number,received:i.parsedType}),g}let r,n=new A;for(let i of this._def.checks)i.kind==="int"?k.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:d.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?ps(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:d.not_finite,message:i.message}),n.dirty()):k.assertNever(i);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,r,n){return new s({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&k.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Q.create=s=>new Q({checks:[],typeName:y.ZodNumber,coerce:s?.coerce||!1,..._(s)});var X=class s extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let r,n=new A;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):k.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.bigint,received:t.parsedType}),g}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,r,n){return new s({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};X.create=s=>new X({checks:[],typeName:y.ZodBigInt,coerce:s?.coerce??!1,..._(s)});var ee=class extends b{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.boolean,received:r.parsedType}),g}return S(e.data)}};ee.create=s=>new ee({typeName:y.ZodBoolean,coerce:s?.coerce||!1,..._(s)});var te=class s extends b{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let i=this._getOrReturnCtx(e);return p(i,{code:d.invalid_type,expected:f.date,received:i.parsedType}),g}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return p(i,{code:d.invalid_date}),g}let r=new A,n;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):k.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};te.create=s=>new te({checks:[],coerce:s?.coerce||!1,typeName:y.ZodDate,..._(s)});var ye=class extends b{_parse(e){if(this._getType(e)!==f.symbol){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.symbol,received:r.parsedType}),g}return S(e.data)}};ye.create=s=>new ye({typeName:y.ZodSymbol,..._(s)});var se=class extends b{_parse(e){if(this._getType(e)!==f.undefined){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.undefined,received:r.parsedType}),g}return S(e.data)}};se.create=s=>new se({typeName:y.ZodUndefined,..._(s)});var re=class extends b{_parse(e){if(this._getType(e)!==f.null){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.null,received:r.parsedType}),g}return S(e.data)}};re.create=s=>new re({typeName:y.ZodNull,..._(s)});var Y=class extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return S(e.data)}};Y.create=s=>new Y({typeName:y.ZodAny,..._(s)});var F=class extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return S(e.data)}};F.create=s=>new F({typeName:y.ZodUnknown,..._(s)});var M=class extends b{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.never,received:t.parsedType}),g}};M.create=s=>new M({typeName:y.ZodNever,..._(s)});var ve=class extends b{_parse(e){if(this._getType(e)!==f.undefined){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.void,received:r.parsedType}),g}return S(e.data)}};ve.create=s=>new ve({typeName:y.ZodVoid,..._(s)});var W=class s extends b{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==f.array)return p(t,{code:d.invalid_type,expected:f.array,received:t.parsedType}),g;if(n.exactLength!==null){let a=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(a||o)&&(p(t,{code:a?d.too_big:d.too_small,minimum:o?n.exactLength.value:void 0,maximum:a?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(p(t,{code:d.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(p(t,{code:d.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>n.type._parseAsync(new $(t,a,t.path,o)))).then(a=>A.mergeArray(r,a));let i=[...t.data].map((a,o)=>n.type._parseSync(new $(t,a,t.path,o)));return A.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new s({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new s({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new s({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}};W.create=(s,e)=>new W({type:s,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,..._(e)});function ge(s){if(s instanceof O){let e={};for(let t in s.shape){let r=s.shape[t];e[t]=C.create(ge(r))}return new O({...s._def,shape:()=>e})}else return s instanceof W?new W({...s._def,type:ge(s.element)}):s instanceof C?C.create(ge(s.unwrap())):s instanceof U?U.create(ge(s.unwrap())):s instanceof j?j.create(s.items.map(e=>ge(e))):s}var O=class s extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=k.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let u=this._getOrReturnCtx(e);return p(u,{code:d.invalid_type,expected:f.object,received:u.parsedType}),g}let{status:r,ctx:n}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof M&&this._def.unknownKeys==="strip"))for(let u in n.data)a.includes(u)||o.push(u);let c=[];for(let u of a){let h=i[u],x=n.data[u];c.push({key:{status:"valid",value:u},value:h._parse(new $(n,x,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof M){let u=this._def.unknownKeys;if(u==="passthrough")for(let h of o)c.push({key:{status:"valid",value:h},value:{status:"valid",value:n.data[h]}});else if(u==="strict")o.length>0&&(p(n,{code:d.unrecognized_keys,keys:o}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let h of o){let x=n.data[h];c.push({key:{status:"valid",value:h},value:u._parse(new $(n,x,n.path,h)),alwaysSet:h in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let u=[];for(let h of c){let x=await h.key,E=await h.value;u.push({key:x,value:E,alwaysSet:h.alwaysSet})}return u}).then(u=>A.mergeObjectSync(r,u)):A.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new s({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let n=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:m.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new s({...this._def,unknownKeys:"strip"})}passthrough(){return new s({...this._def,unknownKeys:"passthrough"})}extend(e){return new s({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new s({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new s({...this._def,catchall:e})}pick(e){let t={};for(let r of k.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new s({...this._def,shape:()=>t})}omit(e){let t={};for(let r of k.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new s({...this._def,shape:()=>t})}deepPartial(){return ge(this)}partial(e){let t={};for(let r of k.objectKeys(this.shape)){let n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new s({...this._def,shape:()=>t})}required(e){let t={};for(let r of k.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof C;)i=i._def.innerType;t[r]=i}return new s({...this._def,shape:()=>t})}keyof(){return gt(k.objectKeys(this.shape))}};O.create=(s,e)=>new O({shape:()=>s,unknownKeys:"strip",catchall:M.create(),typeName:y.ZodObject,..._(e)});O.strictCreate=(s,e)=>new O({shape:()=>s,unknownKeys:"strict",catchall:M.create(),typeName:y.ZodObject,..._(e)});O.lazycreate=(s,e)=>new O({shape:s,unknownKeys:"strip",catchall:M.create(),typeName:y.ZodObject,..._(e)});var ne=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(i){for(let o of i)if(o.result.status==="valid")return o.result;for(let o of i)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(o=>new R(o.ctx.common.issues));return p(t,{code:d.invalid_union,unionErrors:a}),g}if(t.common.async)return Promise.all(r.map(async i=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(n);{let i,a=[];for(let c of r){let u={...t,common:{...t.common,issues:[]},parent:null},h=c._parseSync({data:t.data,path:t.path,parent:u});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let o=a.map(c=>new R(c));return p(t,{code:d.invalid_union,unionErrors:o}),g}}get options(){return this._def.options}};ne.create=(s,e)=>new ne({options:s,typeName:y.ZodUnion,..._(e)});var z=s=>s instanceof ae?z(s.schema):s instanceof N?z(s.innerType()):s instanceof oe?[s.value]:s instanceof ce?s.options:s instanceof ue?k.objectValues(s.enum):s instanceof le?z(s._def.innerType):s instanceof se?[void 0]:s instanceof re?[null]:s instanceof C?[void 0,...z(s.unwrap())]:s instanceof U?[null,...z(s.unwrap())]:s instanceof Ae||s instanceof pe?z(s.unwrap()):s instanceof de?z(s._def.innerType):[],Ce=class s extends b{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return p(t,{code:d.invalid_type,expected:f.object,received:t.parsedType}),g;let r=this.discriminator,n=t.data[r],i=this.optionsMap.get(n);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let n=new Map;for(let i of t){let a=z(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of a){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,i)}}return new s({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,..._(r)})}};function He(s,e){let t=D(s),r=D(e);if(s===e)return{valid:!0,data:s};if(t===f.object&&r===f.object){let n=k.objectKeys(e),i=k.objectKeys(s).filter(o=>n.indexOf(o)!==-1),a={...s,...e};for(let o of i){let c=He(s[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(t===f.array&&r===f.array){if(s.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<s.length;i++){let a=s[i],o=e[i],c=He(a,o);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else return t===f.date&&r===f.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}var ie=class extends b{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(i,a)=>{if(Re(i)||Re(a))return g;let o=He(i.value,a.value);return o.valid?((Oe(i)||Oe(a))&&t.dirty(),{status:t.value,value:o.data}):(p(r,{code:d.invalid_intersection_types}),g)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>n(i,a)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};ie.create=(s,e,t)=>new ie({left:s,right:e,typeName:y.ZodIntersection,..._(t)});var j=class s extends b{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.array)return p(r,{code:d.invalid_type,expected:f.array,received:r.parsedType}),g;if(r.data.length<this._def.items.length)return p(r,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&r.data.length>this._def.items.length&&(p(r,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((a,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new $(r,a,r.path,o)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>A.mergeArray(t,a)):A.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new s({...this._def,rest:e})}};j.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new j({items:s,typeName:y.ZodTuple,rest:null,..._(e)})};var $e=class s extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.object)return p(r,{code:d.invalid_type,expected:f.object,received:r.parsedType}),g;let n=[],i=this._def.keyType,a=this._def.valueType;for(let o in r.data)n.push({key:i._parse(new $(r,o,r.path,o)),value:a._parse(new $(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?A.mergeObjectAsync(t,n):A.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof b?new s({keyType:e,valueType:t,typeName:y.ZodRecord,..._(r)}):new s({keyType:q.create(),valueType:e,typeName:y.ZodRecord,..._(t)})}},_e=class extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.map)return p(r,{code:d.invalid_type,expected:f.map,received:r.parsedType}),g;let n=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([o,c],u)=>({key:n._parse(new $(r,o,r.path,[u,"key"])),value:i._parse(new $(r,c,r.path,[u,"value"]))}));if(r.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of a){let u=await c.key,h=await c.value;if(u.status==="aborted"||h.status==="aborted")return g;(u.status==="dirty"||h.status==="dirty")&&t.dirty(),o.set(u.value,h.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let c of a){let u=c.key,h=c.value;if(u.status==="aborted"||h.status==="aborted")return g;(u.status==="dirty"||h.status==="dirty")&&t.dirty(),o.set(u.value,h.value)}return{status:t.value,value:o}}}};_e.create=(s,e,t)=>new _e({valueType:e,keyType:s,typeName:y.ZodMap,..._(t)});var be=class s extends b{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.set)return p(r,{code:d.invalid_type,expected:f.set,received:r.parsedType}),g;let n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(p(r,{code:d.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&r.data.size>n.maxSize.value&&(p(r,{code:d.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());let i=this._def.valueType;function a(c){let u=new Set;for(let h of c){if(h.status==="aborted")return g;h.status==="dirty"&&t.dirty(),u.add(h.value)}return{status:t.value,value:u}}let o=[...r.data.values()].map((c,u)=>i._parse(new $(r,c,r.path,u)));return r.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,t){return new s({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new s({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};be.create=(s,e)=>new be({valueType:s,minSize:null,maxSize:null,typeName:y.ZodSet,..._(e)});var Ne=class s extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return p(t,{code:d.invalid_type,expected:f.function,received:t.parsedType}),g;function r(o,c){return we({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,me(),B].filter(u=>!!u),issueData:{code:d.invalid_arguments,argumentsError:c}})}function n(o,c){return we({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,me(),B].filter(u=>!!u),issueData:{code:d.invalid_return_type,returnTypeError:c}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof G){let o=this;return S(async function(...c){let u=new R([]),h=await o._def.args.parseAsync(c,i).catch(T=>{throw u.addIssue(r(c,T)),u}),x=await Reflect.apply(a,this,h);return await o._def.returns._def.type.parseAsync(x,i).catch(T=>{throw u.addIssue(n(x,T)),u})})}else{let o=this;return S(function(...c){let u=o._def.args.safeParse(c,i);if(!u.success)throw new R([r(c,u.error)]);let h=Reflect.apply(a,this,u.data),x=o._def.returns.safeParse(h,i);if(!x.success)throw new R([n(h,x.error)]);return x.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new s({...this._def,args:j.create(e).rest(F.create())})}returns(e){return new s({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new s({args:e||j.create([]).rest(F.create()),returns:t||F.create(),typeName:y.ZodFunction,..._(r)})}},ae=class extends b{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ae.create=(s,e)=>new ae({getter:s,typeName:y.ZodLazy,..._(e)});var oe=class extends b{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};oe.create=(s,e)=>new oe({value:s,typeName:y.ZodLiteral,..._(e)});function gt(s,e){return new ce({values:s,typeName:y.ZodEnum,..._(e)})}var ce=class s extends b{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return p(t,{expected:k.joinValues(r),received:t.parsedType,code:d.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return p(t,{received:t.data,code:d.invalid_enum_value,options:r}),g}return S(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return s.create(e,{...this._def,...t})}exclude(e,t=this._def){return s.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};ce.create=gt;var ue=class extends b{_parse(e){let t=k.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==f.string&&r.parsedType!==f.number){let n=k.objectValues(t);return p(r,{expected:k.joinValues(n),received:r.parsedType,code:d.invalid_type}),g}if(this._cache||(this._cache=new Set(k.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=k.objectValues(t);return p(r,{received:r.data,code:d.invalid_enum_value,options:n}),g}return S(e.data)}get enum(){return this._def.values}};ue.create=(s,e)=>new ue({values:s,typeName:y.ZodNativeEnum,..._(e)});var G=class extends b{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return p(t,{code:d.invalid_type,expected:f.promise,received:t.parsedType}),g;let r=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return S(r.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};G.create=(s,e)=>new G({type:s,typeName:y.ZodPromise,..._(e)});var N=class extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:a=>{p(r,a),a.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let a=n.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return g;let c=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return c.status==="aborted"?g:c.status==="dirty"?J(c.value):t.value==="dirty"?J(c.value):c});{if(t.value==="aborted")return g;let o=this._def.schema._parseSync({data:a,path:r.path,parent:r});return o.status==="aborted"?g:o.status==="dirty"?J(o.value):t.value==="dirty"?J(o.value):o}}if(n.type==="refinement"){let a=o=>{let c=n.refinement(o,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?g:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?g:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!K(a))return g;let o=n.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>K(a)?Promise.resolve(n.transform(a.value,i)).then(o=>({status:t.value,value:o})):g);k.assertNever(n)}};N.create=(s,e,t)=>new N({schema:s,typeName:y.ZodEffects,effect:e,..._(t)});N.createWithPreprocess=(s,e,t)=>new N({schema:e,effect:{type:"preprocess",transform:s},typeName:y.ZodEffects,..._(t)});var C=class extends b{_parse(e){return this._getType(e)===f.undefined?S(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};C.create=(s,e)=>new C({innerType:s,typeName:y.ZodOptional,..._(e)});var U=class extends b{_parse(e){return this._getType(e)===f.null?S(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};U.create=(s,e)=>new U({innerType:s,typeName:y.ZodNullable,..._(e)});var le=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===f.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};le.create=(s,e)=>new le({innerType:s,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});var de=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return he(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new R(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new R(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};de.create=(s,e)=>new de({innerType:s,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});var xe=class extends b{_parse(e){if(this._getType(e)!==f.nan){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.nan,received:r.parsedType}),g}return{status:"valid",value:e.data}}};xe.create=s=>new xe({typeName:y.ZodNaN,..._(s)});var fs=Symbol("zod_brand"),Ae=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},Se=class s extends b{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?g:i.status==="dirty"?(t.dirty(),J(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?g:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new s({in:e,out:t,typeName:y.ZodPipeline})}},pe=class extends b{_parse(e){let t=this._def.innerType._parse(e),r=n=>(K(n)&&(n.value=Object.freeze(n.value)),n);return he(t)?t.then(n=>r(n)):r(t)}unwrap(){return this._def.innerType}};pe.create=(s,e)=>new pe({innerType:s,typeName:y.ZodReadonly,..._(e)});function pt(s,e){let t=typeof s=="function"?s(e):typeof s=="string"?{message:s}:s;return typeof t=="string"?{message:t}:t}function yt(s,e={},t){return s?Y.create().superRefine((r,n)=>{let i=s(r);if(i instanceof Promise)return i.then(a=>{if(!a){let o=pt(e,r),c=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:c})}});if(!i){let a=pt(e,r),o=a.fatal??t??!0;n.addIssue({code:"custom",...a,fatal:o})}}):Y.create()}var ms={object:O.lazycreate},y;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(y||(y={}));var hs=(s,e={message:`Input not instance of ${s.name}`})=>yt(t=>t instanceof s,e),vt=q.create,_t=Q.create,gs=xe.create,ys=X.create,bt=ee.create,vs=te.create,_s=ye.create,bs=se.create,xs=re.create,ks=Y.create,ws=F.create,As=M.create,Ss=ve.create,Es=W.create,Ts=O.create,Is=O.strictCreate,Rs=ne.create,Os=Ce.create,Cs=ie.create,$s=j.create,Ns=$e.create,Ps=_e.create,Ms=be.create,Ds=Ne.create,js=ae.create,Us=oe.create,Vs=ce.create,Ls=ue.create,Zs=G.create,Bs=N.create,zs=C.create,Fs=U.create,Ws=N.createWithPreprocess,Hs=Se.create,Ks=()=>vt().optional(),qs=()=>_t().optional(),Ys=()=>bt().optional(),Gs={string:(s=>q.create({...s,coerce:!0})),number:(s=>Q.create({...s,coerce:!0})),boolean:(s=>ee.create({...s,coerce:!0})),bigint:(s=>X.create({...s,coerce:!0})),date:(s=>te.create({...s,coerce:!0}))};var Js=g;function Qs(s,e){let t=s.split(/[.+-]/),r=e.split(/[.+-]/);for(let n=0;n<Math.max(t.length,r.length);n++){let i=t[n]??"",a=r[n]??"",o=/^\d+$/.test(i)&&/^\d+$/.test(a)?Number(i)-Number(a):i.localeCompare(a);if(o)return o}return 0}function xt(s){let e=s.version||"unknown";return s.update?`${e}+${s.update.slice(0,12)}`:e}function Ke(s,e,t,r){return s&&e?Qs(e,s)>=0:!!t&&r>t}var Xs=/^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/,er=/^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/,tr=[/node_modules/,/\bnative\b/,/\[native code\]/,/InternalBytecode/],sr=/\.(?:js)?bundle\b/;function rr(s){return s.replace(/^address at /,"")}function kt(s){if(!s)return[];let e=[];for(let t of s.split(`
|
|
2
|
+
`)){let r=Xs.exec(t)??er.exec(t);if(!r)continue;let[,n,i,a,o]=r,c=rr(i??"");if(e.push({fn:n||void 0,file:c,line:Number(a),col:Number(o),inApp:sr.test(c)?!/^(?:anonymous|eval|global code)$/.test(n??""):!tr.some(u=>u.test(c))}),e.length>=100)break}return e}var nr=l.string().min(1).max(64).regex(/^[a-z0-9_]+(\.[a-z0-9_]+)*$/,"flow must be dotted lowercase, e.g. auth.login"),ir=l.record(l.string().max(200)).optional(),qe=l.string().datetime({offset:!0}),ar=l.object({model:l.string().optional(),manufacturer:l.string().optional(),brand:l.string().optional(),type:l.enum(["phone","tablet","desktop","tv","unknown"]).default("unknown"),isEmulator:l.boolean().optional(),memoryMb:l.number().optional(),screen:l.object({width:l.number(),height:l.number(),scale:l.number().optional()}).optional()}),or=l.object({name:l.string(),version:l.string().optional()}),cr=l.object({id:l.string().min(1),version:l.string().optional(),build:l.string().optional(),update:l.string().max(100).optional(),environment:l.string().default("production")}),ur=l.object({name:l.string(),version:l.string().optional(),engine:l.string().optional()}),lr=l.object({type:l.enum(["wifi","cellular","ethernet","none","unknown"]).default("unknown"),effectiveType:l.string().optional(),isConnected:l.boolean().optional()}),dr=l.object({app:cr,device:ar.default({}),os:or,runtime:ur,network:lr.optional(),locale:l.string().optional(),timezone:l.string().optional()}),pr=l.object({ts:qe,category:l.enum(["navigation","network","ui","log","event","custom"]),message:l.string().max(500),level:l.enum(["debug","info","warning","error"]).default("info"),data:l.record(l.union([l.string(),l.number(),l.boolean(),l.null()])).optional()}),fr=l.object({fn:l.string().optional(),file:l.string().optional(),line:l.number().optional(),col:l.number().optional(),inApp:l.boolean().optional()}),mr=l.enum(["low","medium","high","critical"]),Pe=l.object({id:l.string().min(8).max(64),ts:qe,flow:nr.optional(),step:l.string().max(64).optional(),tags:ir}),hr=Pe.extend({type:l.literal("error"),handled:l.boolean().default(!0),severity:mr.optional(),error:l.object({name:l.string().max(200).default("Error"),message:l.string().max(2e3),stack:l.string().max(2e4).optional(),frames:l.array(fr).max(100).optional()}),breadcrumbs:l.array(pr).max(50).optional(),request:l.object({method:l.string().max(10),url:l.string().max(500),status:l.number().int().optional(),durationMs:l.number().optional()}).optional()}),gr=Pe.extend({type:l.literal("event"),name:l.string().min(1).max(100),outcome:l.enum(["success","failure","abandoned"]).optional(),props:l.record(l.union([l.string(),l.number(),l.boolean(),l.null()])).optional()}),yr=Pe.extend({type:l.literal("session"),status:l.enum(["started","errored","crashed"])}),vr=Pe.extend({type:l.literal("metric"),name:l.literal("http"),key:l.string().min(1).max(300),count:l.number().int().min(1).max(1e6),errors:l.number().int().min(0).max(1e6),buckets:l.array(l.number().int().min(0)).length(13)}),_r=l.discriminatedUnion("type",[hr,gr,yr,vr]),At=l.object({schema:l.literal(1).default(1),sdk:l.object({name:l.string(),version:l.string()}),context:dr,user:l.object({id:l.string().optional(),anonymousId:l.string()}).optional(),session:l.object({id:l.string(),startedAt:qe}),events:l.array(_r).min(1).max(100)});function Me(s){let e=new Map;for(let t of s){let r=Ye(t),n=e.get(r)??{app:t.app,day:t.day,dimension:t.dimension,key:t.key,errors:0,events:0};t.kind==="error"?n.errors+=t.by:n.events+=t.by,e.set(r,n)}return[...e.values()]}var Ye=s=>`${s.day}__${s.dimension}__${encodeURIComponent(s.key)}`;var Ge=1,Je=3650,St=7,Et=["owner","admin","member"];var je=class{constructor(e,t){this.doc=e;this.opts=t}doc;opts;get table(){return this.opts.table}async getMember(e){let t=await this.doc.send(new Ee({TableName:this.table,Key:{pk:"TEAM",sk:`M#${e}`}}));return t.Item?L(t.Item):null}async putMember(e){await this.doc.send(new Qe({TableName:this.table,Item:{...Tt(e),pk:"TEAM",sk:`M#${e.email}`}}))}async listMembers(){return await this.teamItems("M#")}async getInvite(e){let t=await this.doc.send(new Ee({TableName:this.table,Key:{pk:"TEAM",sk:`I#${e}`}}));return t.Item?L(t.Item):null}async putInvite(e){await this.doc.send(new Qe({TableName:this.table,Item:{...Tt(e),pk:"TEAM",sk:`I#${e.id}`}}))}async claimInvite(e,t,r){try{return await this.doc.send(new V({TableName:this.table,Key:{pk:"TEAM",sk:`I#${e}`},UpdateExpression:"SET usedAt = :at, usedBy = :by",ConditionExpression:"attribute_exists(pk) AND attribute_not_exists(usedAt) AND attribute_not_exists(revokedAt)",ExpressionAttributeValues:{":at":r,":by":t}})),!0}catch(n){if(n.name==="ConditionalCheckFailedException")return!1;throw n}}async listInvites(){return(await this.teamItems("I#")).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}async teamItems(e){let t=[],r;do{let n=await this.doc.send(new De({TableName:this.table,KeyConditionExpression:"pk = :pk AND begins_with(sk, :p)",ExpressionAttributeValues:{":pk":"TEAM",":p":e},ExclusiveStartKey:r}));t.push(...(n.Items??[]).map(L)),r=n.LastEvaluatedKey}while(r);return t}async registerApp(e){await this.doc.send(new Qe({TableName:this.table,Item:{pk:"APPS",sk:e}}))}async writeEvents(e,t={}){let r=t.retentionDays??this.opts.retentionDays??30,n=a=>Math.floor(Date.parse(a.receivedAt)/1e3)+r*86400,i=e.flatMap(a=>{let o=`${a.event.ts}#${a.event.id}`,c={...a,ttl:n(a)},u=[{pk:`APP#${a.app}#EV#${a.day}`,sk:o,...c}];return a.fingerprint&&u.push({pk:`APP#${a.app}#ISSUEEV#${a.fingerprint}`,sk:o,...c}),u});for(let a=0;a<i.length;a+=25){let o={[this.table]:i.slice(a,a+25).map(c=>({PutRequest:{Item:c}}))};for(let c=0;o&&Object.keys(o).length&&c<5;c++)o=(await this.doc.send(new br({RequestItems:o}))).UnprocessedItems,o&&Object.keys(o).length&&await new Promise(h=>setTimeout(h,50*2**c))}}async upsertIssues(e){let t={created:[],regressed:[]};return await Promise.all(e.map(async r=>{(await this.doc.send(new V({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},UpdateExpression:"ADD #count :by SET app = :app, fingerprint = :fp, title = :title, flow = :flow, culprit = :culprit, firstSeen = if_not_exists(firstSeen, :first)",ExpressionAttributeNames:{"#count":"count"},ExpressionAttributeValues:{":by":r.by,":app":r.app,":fp":r.fingerprint,":title":r.title,":flow":r.flow??null,":culprit":r.culprit??null,":first":r.firstTs},ReturnValues:"UPDATED_OLD"}))).Attributes?.count===void 0&&t.created.push(r.fingerprint),await this.doc.send(new V({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},UpdateExpression:"SET lastSeen = :ts, lastEvent = :ev, lastVersion = :v, firstVersion = if_not_exists(firstVersion, :v)",ConditionExpression:"attribute_not_exists(lastSeen) OR lastSeen < :ts",ExpressionAttributeValues:{":ts":r.ts,":ev":r.lastEvent,":v":r.version??null}})).catch(a=>{if(a.name!=="ConditionalCheckFailedException")throw a});let i=(await this.doc.send(new Ee({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},ProjectionExpression:"#s, resolvedIn, resolvedAt",ExpressionAttributeNames:{"#s":"status"}}))).Item;i?.status==="resolved"&&Ke(i.resolvedIn,r.version,i.resolvedAt,r.ts)&&await this.doc.send(new V({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},UpdateExpression:"SET #s = :r, regressedAt = :ts",ConditionExpression:"#s = :resolved",ExpressionAttributeNames:{"#s":"status"},ExpressionAttributeValues:{":r":"regressed",":ts":r.ts,":resolved":"resolved"}})).then(()=>t.regressed.push(r.fingerprint)).catch(a=>{if(a.name!=="ConditionalCheckFailedException")throw a}),await this.doc.send(new V({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},UpdateExpression:"SET firstSeen = :first",ConditionExpression:"firstSeen > :first",ExpressionAttributeValues:{":first":r.firstTs}})).catch(a=>{if(a.name!=="ConditionalCheckFailedException")throw a})})),t}async incrementRollups(e){await Promise.all(Me(e).map(t=>this.doc.send(new V({TableName:this.table,Key:{pk:`APP#${t.app}#ROLLUP#${t.dimension}`,sk:`${t.day}#${t.key}`},UpdateExpression:`ADD errors :e, events :v SET app = :app, #day = :day, dimension = :dim, #key = :key${t.dimension==="issueHour"?", #ttl = :ttl":""}`,ExpressionAttributeNames:{"#day":"day","#key":"key",...t.dimension==="issueHour"?{"#ttl":"ttl"}:{}},ExpressionAttributeValues:{":e":t.errors,":v":t.events,":app":t.app,":day":t.day,":dim":t.dimension,":key":t.key,...t.dimension==="issueHour"?{":ttl":Math.floor(Date.parse(`${t.day}:00:00Z`)/1e3)+St*86400}:{}}}))))}async markUsers(e,t){await Promise.all(t.map(r=>this.doc.send(new V({TableName:this.table,Key:{pk:`APP#${e}#USERS#${r.scope}`,sk:r.member},UpdateExpression:"SET lastDay = :d",ConditionExpression:"attribute_not_exists(lastDay) OR lastDay < :d",ExpressionAttributeValues:{":d":r.day}})).catch(n=>{if(n.name!=="ConditionalCheckFailedException")throw n})))}async countUsers(e,t,r){let n=0,i;do{let a=await this.doc.send(new De({TableName:this.table,KeyConditionExpression:"pk = :pk",FilterExpression:"lastDay >= :d",ExpressionAttributeValues:{":pk":`APP#${e}#USERS#${t}`,":d":r},Select:"COUNT",ExclusiveStartKey:i}));n+=a.Count??0,i=a.LastEvaluatedKey}while(i);return n}async setIssueStatus(e,t,r){let n=r.status==="resolved",i=await this.doc.send(new V({TableName:this.table,Key:{pk:`APP#${e}#ISSUE`,sk:t},UpdateExpression:n?"SET #s = :s, resolvedAt = :at, resolvedIn = :in REMOVE regressedAt":"SET #s = :s REMOVE resolvedIn, resolvedAt, regressedAt",ConditionExpression:"attribute_exists(pk)",ExpressionAttributeNames:{"#s":"status"},ExpressionAttributeValues:n?{":s":r.status,":at":new Date().toISOString(),":in":r.resolvedIn??null}:{":s":r.status},ReturnValues:"ALL_NEW"})).catch(a=>{if(a.name==="ConditionalCheckFailedException")return null;throw a});return i?.Attributes?L(i.Attributes):null}async getSettings(e){let t=await this.doc.send(new Ee({TableName:this.table,Key:{pk:`APP#${e}#SETTINGS`,sk:"app"}}));return t.Item?L(t.Item):null}async putSettings(e,t){let r=Object.fromEntries(Object.entries({...t,updatedAt:new Date().toISOString()}).filter(([,a])=>a!==void 0)),n=Object.keys(r),i=await this.doc.send(new V({TableName:this.table,Key:{pk:`APP#${e}#SETTINGS`,sk:"app"},UpdateExpression:`SET ${n.map((a,o)=>`#n${o} = :v${o}`).join(", ")}`,ExpressionAttributeNames:Object.fromEntries(n.map((a,o)=>[`#n${o}`,a])),ExpressionAttributeValues:Object.fromEntries(n.map((a,o)=>[`:v${o}`,r[a]])),ReturnValues:"ALL_NEW"}));return L(i.Attributes??r)}async restampExpiry(e,t,{cursor:r}={}){let n=r?Number(r):0,i=0;for(let a=0;a<30&&n<=3650;a++,n++){let o=new Date(Date.now()-n*864e5).toISOString().slice(0,10),c=await this.queryAll({pk:`APP#${e}#EV#${o}`});for(let u of c){let h=Math.floor(Date.parse(u.receivedAt)/1e3)+t*86400,x=[{pk:u.pk,sk:u.sk},...u.fingerprint?[{pk:`APP#${e}#ISSUEEV#${u.fingerprint}`,sk:u.sk}]:[]];await Promise.all(x.map(E=>this.doc.send(new V({TableName:this.table,Key:E,UpdateExpression:"SET #t = :t",ConditionExpression:"attribute_exists(pk)",ExpressionAttributeNames:{"#t":"ttl"},ExpressionAttributeValues:{":t":h}})).catch(T=>{if(T.name!=="ConditionalCheckFailedException")throw T}))),i++}if(c.length){n++;break}}return{updated:i,cursor:n<=3650?String(n):void 0}}async listApps(){return(await this.queryAll({pk:"APPS"})).map(e=>e.sk).sort()}async listIssues(e,{limit:t=200}={}){return(await this.queryAll({pk:`APP#${e}#ISSUE`})).sort((n,i)=>i.lastSeen.localeCompare(n.lastSeen)).slice(0,t).map(L)}async getIssue(e,t){let r=await this.doc.send(new Ee({TableName:this.table,Key:{pk:`APP#${e}#ISSUE`,sk:t}}));return r.Item?L(r.Item):null}async getRollups(e,t,r,n){return(await this.queryAll({pk:`APP#${e}#ROLLUP#${t}`,between:[`${r}#`,`${n}#\uFFFF`]})).map(a=>L(a))}async listIssueEvents(e,t,{limit:r=50}={}){return((await this.doc.send(new De({TableName:this.table,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":`APP#${e}#ISSUEEV#${t}`},ScanIndexForward:!1,Limit:r}))).Items??[]).map(i=>L(i))}async queryAll({pk:e,between:t}){let r=[],n;do{let i=await this.doc.send(new De({TableName:this.table,KeyConditionExpression:t?"pk = :pk AND sk BETWEEN :a AND :b":"pk = :pk",ExpressionAttributeValues:t?{":pk":e,":a":t[0],":b":t[1]}:{":pk":e},ExclusiveStartKey:n}));r.push(...i.Items??[]),n=i.LastEvaluatedKey}while(n);return r}};function L(s){let{pk:e,sk:t,ttl:r,...n}=s;return n}function Tt(s){return Object.fromEntries(Object.entries(s).filter(([,e])=>e!==void 0))}import{createHash as Dr}from"crypto";import{timingSafeEqual as Tr}from"crypto";import{createHash as xr,randomBytes as kr}from"crypto";var Rt=7,wr=/^[^\s@/]{1,64}@[^\s@/]{1,190}\.[^\s@/]{2,63}$/,Ar=/^scrypt\.[0-9a-f]{32}\.[0-9a-f]{128}$/,w=(s,e=400)=>({status:e,body:{ok:!1,error:s}}),Xe=s=>xr("sha256").update(s).digest("hex");function Ue(s){let{passwordHash:e,...t}=s;return t}var It=s=>Et.includes(s)?s:void 0,Te=s=>typeof s=="string"&&wr.test(s.trim())?s.trim().toLowerCase():void 0;async function et(s,e,t,r=new Date){let n=r.toISOString();switch(e){case"invite":{let i=It(t.role);if(!i)return w("role must be owner, admin or member");let a=Te(t.invitedBy);if(!a)return w("invitedBy must be an email");let o=t.email?Te(t.email):void 0;if(t.email&&!o)return w("email isn't a valid address");if(o){let h=await s.getMember(o);if(h&&!h.removedAt)return w(`${o} is already on the team`,409)}let c=kr(32).toString("base64url"),u={id:Xe(c),role:i,email:o,invitedBy:a,createdAt:n,expiresAt:new Date(r.getTime()+Rt*864e5).toISOString()};return await s.putInvite(u),{status:200,body:{ok:!0,token:c,invite:u}}}case"accept":{let i=typeof t.token=="string"?t.token:"";if(!/^[A-Za-z0-9_-]{40,64}$/.test(i))return w("This invite link isn't valid.",404);let a=Te(t.email);if(!a)return w("Enter a valid email address.");if(typeof t.passwordHash!="string"||!Ar.test(t.passwordHash))return w("passwordHash must be a scrypt hash");let o=typeof t.name=="string"&&t.name.trim().slice(0,80)||void 0,c=await s.getInvite(Xe(i));if(!c||c.usedAt||c.revokedAt)return w("This invite link has already been used or was cancelled. Ask for a new one.",410);if(Date.parse(c.expiresAt)<r.getTime())return w("This invite link has expired. Ask for a new one.",410);if(c.email&&c.email!==a)return w(`This invite is for ${c.email}.`,403);let u=await s.getMember(a);if(u&&!u.removedAt)return w(`${a} already has access. Sign in instead.`,409);if(!await s.claimInvite(c.id,a,n))return w("This invite link has already been used. Ask for a new one.",410);let h={email:a,name:o,role:c.role,passwordHash:t.passwordHash,sessionVersion:(u?.sessionVersion??0)+1,createdAt:u?.createdAt??n,updatedAt:n,invitedBy:c.invitedBy};return await s.putMember(h),{status:200,body:{ok:!0,member:Ue(h)}}}case"role":{let i=Te(t.email),a=It(t.role);if(!i||!a)return w("email and role are required");let o=await s.getMember(i);if(!o||o.removedAt)return w("No such member.",404);let c={...o,role:a,updatedAt:n};return await s.putMember(c),{status:200,body:{ok:!0,member:Ue(c)}}}case"remove":{let i=Te(t.email);if(!i)return w("email is required");let a=await s.getMember(i);if(!a||a.removedAt)return w("No such member.",404);let o={...a,removedAt:n,updatedAt:n,sessionVersion:a.sessionVersion+1};return await s.putMember(o),{status:200,body:{ok:!0,member:Ue(o)}}}case"revoke":{let i=typeof t.id=="string"&&/^[0-9a-f]{64}$/.test(t.id)?t.id:void 0;if(!i)return w("id is required");let a=await s.getInvite(i);return a?(!a.usedAt&&!a.revokedAt&&await s.putInvite({...a,revokedAt:n}),{status:200,body:{ok:!0}}):w("No such invite.",404)}default:return w("not found",404)}}var Ie=/^https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9/_-]{10,200}$/,Ve=new Map,Sr=36e5,Er=(s,e)=>fetch(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(3e3)});async function tt(s,e,t,r,n=Er){let i=r?.alerts;if(!e||!i?.slackWebhookUrl||!Ie.test(i.slackWebhookUrl))return 0;let a=new Set(r?.criticalFlows??[]),o=[...i.newIssues!==!1?e.created.map(u=>({fp:u,kind:"new"})):[],...i.regressions!==!1?e.regressed.map(u=>({fp:u,kind:"regressed"})):[]].filter(({fp:u})=>!i.onlyCriticalFlows||a.has(t.get(u)?.flow??"")).filter(({fp:u,kind:h})=>{let x=`${s}|${u}|${h}`,E=Ve.get(x);return E&&Date.now()-E<Sr?!1:(Ve.set(x,Date.now()),!0)}).slice(0,10);Ve.size>5e3&&Ve.clear();let c=0;for(let{fp:u,kind:h}of o){let x=t.get(u);if(!x)continue;let E=i.dashboardUrl?`${i.dashboardUrl.replace(/\/+$/,"")}/issues/${u}?app=${encodeURIComponent(s)}`:void 0,T=[x.culprit&&`\`${x.culprit}\``,x.flow&&`flow \`${x.flow}\`${a.has(x.flow)?" (critical)":""}`,x.version&&`version ${x.version}`].filter(Boolean).join(" \xB7 "),ze=`${h==="new"?":new: New issue":":rotating_light: Regressed"} in *${s}*: ${E?`<${E}|${x.title}>`:x.title}${T?`
|
|
3
|
+
${T}`:""}`;try{await n(i.slackWebhookUrl,{text:ze}),c++}catch(fe){console.error("[deBug] Slack alert failed",fe)}}return c}var st=30,Ir=6e4,rt=new Map;async function Le(s,e){let t=rt.get(e);if(t&&Date.now()-t.at<Ir)return t.settings;let r;try{r=await s.getSettings(e)}catch{r=null}return rt.set(e,{at:Date.now(),settings:r}),r}async function Ze(s,e,t){return(await Le(s,e))?.retentionDays??t??st}function Ot(s){return s?.alerts?.slackWebhookUrl?{...s,alerts:{...s.alerts,slackWebhookUrl:`https://hooks.slack.com/\u2026${s.alerts.slackWebhookUrl.slice(-4)}`}}:s}var Rr=/^[a-z0-9_]+(\.[a-z0-9_]+)*$/;function Or(s,e){let t={};if(s.retentionDays!==void 0){let r=Number(s.retentionDays);if(!Number.isInteger(r)||r<Ge||r>Je)return`retentionDays must be a whole number from ${Ge} to ${Je}`;t.retentionDays=r}if(s.criticalFlows!==void 0){if(!Array.isArray(s.criticalFlows)||s.criticalFlows.length>30||!s.criticalFlows.every(r=>typeof r=="string"&&r.length<=64&&Rr.test(r)))return"criticalFlows must be up to 30 dotted lowercase flow names, like checkout.payment";t.criticalFlows=[...new Set(s.criticalFlows)]}if(s.alerts!==void 0){let r=s.alerts;if(!r||typeof r!="object")return"alerts must be an object";let n={},i=r.slackWebhookUrl;if(typeof i=="string"&&i.includes("\u2026"))n.slackWebhookUrl=e?.alerts?.slackWebhookUrl;else if(i===""||i===null||i===void 0)n.slackWebhookUrl=void 0;else if(typeof i=="string"&&Ie.test(i))n.slackWebhookUrl=i;else return"slackWebhookUrl must be a Slack incoming-webhook URL (https://hooks.slack.com/services/\u2026)";for(let a of["newIssues","regressions","onlyCriticalFlows"])typeof r[a]=="boolean"&&(n[a]=r[a]);if(typeof r.dashboardUrl=="string"&&r.dashboardUrl){if(!/^https?:\/\/[^\s]{3,300}$/.test(r.dashboardUrl))return"dashboardUrl must be an http(s) URL";n.dashboardUrl=r.dashboardUrl}t.alerts=n}return Object.keys(t).length?t:"nothing to change"}function Cr(s,e){let t=Buffer.from((s??"").replace(/^Bearer\s+/i,"")),r=Buffer.from(e);return t.length===r.length&&Tr(t,r)}var $r=/^[a-z0-9][a-z0-9._-]{0,63}$/i;async function nt(s,e){if(!e.adminToken||e.adminToken.length<16)return{status:404,body:{ok:!1,error:"admin routes are off (set DEBUG_ADMIN_TOKEN)"}};if(!Cr(s.authorization,e.adminToken))return{status:401,body:{ok:!1,error:"unauthorized"}};let t={};if(s.method!=="GET"&&s.body)try{t=JSON.parse(s.body)}catch{return{status:400,body:{ok:!1,error:"invalid json"}}}let r=s.path.replace(/\/+$/,"").replace(/^.*\/admin/,"");if(r.startsWith("/team/"))return s.method!=="POST"?{status:405,body:{ok:!1,error:"use POST"}}:et(e.store,r.slice(6),t);let n=String((s.method==="GET"?s.query?.app:t.app)??"");if(!$r.test(n))return{status:400,body:{ok:!1,error:"app is required"}};if(r==="/settings"&&s.method==="GET"){let i=await e.store.getSettings(n);return{status:200,body:{ok:!0,settings:Ot(i),retentionDays:i?.retentionDays??e.retentionDays??st}}}if(r==="/settings"&&(s.method==="PUT"||s.method==="POST")){let i=await e.store.getSettings(n),a=Or(t,i);if(typeof a=="string")return{status:400,body:{ok:!1,error:a}};let o=await e.store.putSettings(n,a);return rt.delete(n),{status:200,body:{ok:!0,settings:Ot(o),retentionDays:o.retentionDays??e.retentionDays??st}}}if(r==="/alert-test"&&s.method==="POST"){let i=(await e.store.getSettings(n))?.alerts?.slackWebhookUrl;if(!i||!Ie.test(i))return{status:400,body:{ok:!1,error:"No Slack webhook is set for this app"}};let a=await fetch(i,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:`:white_check_mark: deBug alerts for *${n}* are working.`}),signal:AbortSignal.timeout(5e3)}).catch(o=>o);return a instanceof Error||!a.ok?{status:502,body:{ok:!1,error:`Slack didn't accept it: ${a instanceof Error?a.message:a.status}`}}:{status:200,body:{ok:!0}}}if(r==="/restamp"&&s.method==="POST"){let i=await Ze(e.store,n,e.retentionDays),a=await e.store.restampExpiry(n,i,{cursor:typeof t.cursor=="string"?t.cursor:void 0});return{status:200,body:{ok:!0,retentionDays:i,...a}}}if(r==="/issue"&&(s.method==="PUT"||s.method==="POST")){let i=String(t.fingerprint??""),a=String(t.status??"");if(!/^[a-f0-9]{8,64}$/.test(i))return{status:400,body:{ok:!1,error:"fingerprint is required"}};if(a!=="open"&&a!=="resolved"&&a!=="ignored")return{status:400,body:{ok:!1,error:"status must be open, resolved or ignored"}};let o=typeof t.resolvedIn=="string"&&t.resolvedIn.trim()?t.resolvedIn.trim().slice(0,100):void 0,c=await e.store.setIssueStatus(n,i,{status:a,resolvedIn:a==="resolved"?o:void 0});return c?{status:200,body:{ok:!0,status:c.status,resolvedIn:c.resolvedIn??null}}:{status:404,body:{ok:!1,error:"no such issue"}}}return{status:404,body:{ok:!1,error:"not found"}}}var Nr={"Africa/Johannesburg":"ZA","Africa/Lagos":"NG","Africa/Nairobi":"KE","Africa/Cairo":"EG","Africa/Casablanca":"MA","Africa/Accra":"GH","Africa/Harare":"ZW","Africa/Lusaka":"ZM","Africa/Maputo":"MZ","Africa/Windhoek":"NA","Africa/Gaborone":"BW","Africa/Kampala":"UG","Africa/Dar_es_Salaam":"TZ","Africa/Addis_Ababa":"ET","Africa/Kigali":"RW","Africa/Algiers":"DZ","Africa/Tunis":"TN","Africa/Abidjan":"CI","Africa/Dakar":"SN","Africa/Luanda":"AO","Europe/London":"GB","Europe/Dublin":"IE","Europe/Paris":"FR","Europe/Berlin":"DE","Europe/Madrid":"ES","Europe/Rome":"IT","Europe/Amsterdam":"NL","Europe/Brussels":"BE","Europe/Lisbon":"PT","Europe/Stockholm":"SE","Europe/Oslo":"NO","Europe/Copenhagen":"DK","Europe/Helsinki":"FI","Europe/Warsaw":"PL","Europe/Zurich":"CH","Europe/Vienna":"AT","Europe/Athens":"GR","Europe/Istanbul":"TR","Europe/Moscow":"RU","Europe/Kyiv":"UA","Europe/Kiev":"UA","Europe/Prague":"CZ","Europe/Budapest":"HU","Europe/Bucharest":"RO","America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","America/Phoenix":"US","America/Anchorage":"US","Pacific/Honolulu":"US","America/Detroit":"US","America/Toronto":"CA","America/Vancouver":"CA","America/Edmonton":"CA","America/Halifax":"CA","America/Mexico_City":"MX","America/Sao_Paulo":"BR","America/Argentina/Buenos_Aires":"AR","America/Bogota":"CO","America/Lima":"PE","America/Santiago":"CL","Asia/Dubai":"AE","Asia/Riyadh":"SA","Asia/Qatar":"QA","Asia/Jerusalem":"IL","Asia/Kolkata":"IN","Asia/Calcutta":"IN","Asia/Karachi":"PK","Asia/Dhaka":"BD","Asia/Bangkok":"TH","Asia/Jakarta":"ID","Asia/Singapore":"SG","Asia/Kuala_Lumpur":"MY","Asia/Manila":"PH","Asia/Ho_Chi_Minh":"VN","Asia/Hong_Kong":"HK","Asia/Shanghai":"CN","Asia/Tokyo":"JP","Asia/Seoul":"KR","Asia/Taipei":"TW","Australia/Sydney":"AU","Australia/Melbourne":"AU","Australia/Brisbane":"AU","Australia/Perth":"AU","Australia/Adelaide":"AU","Pacific/Auckland":"NZ","Indian/Mauritius":"MU"};function it(s){let e=s.timezone?Nr[s.timezone]:void 0;return e||(/[-_]([A-Z]{2})(?:\b|$)/.exec(s.locale??"")?.[1]??"unknown")}import{createHash as Pr}from"crypto";function Mr(s){return s.replace(/https?:\/\/\S+/g,"<url>").replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,"<uuid>").replace(/\b[0-9a-f]{16,}\b/gi,"<hex>").replace(/[\w.+-]+@[\w-]+\.[\w.]+/g,"<email>").replace(/\d+(\.\d+)?/g,"<n>").replace(/(["'`]).*?\1/g,"<str>").trim().slice(0,300)}function Ct(s){if(!s)return"";let e=s.replace(/\/\/&.*$/,"").replace(/[?#].*$/,"").replace(/^[a-z]+:\/\/[^/]+/i,"");if(/\.(?:js)?bundle$/.test(e))return e.replace(/^.*\//,"");for(let t of["/src/","/lib/","/app/"]){let r=e.lastIndexOf(t);if(r>=0){e=e.slice(r+1);break}}return e.replace(/\.[0-9a-f]{6,}\./g,".")}function $t(s){return s?.find(e=>e.inApp!==!1&&e.file)??s?.[0]}function Nt(s){let e=$t(s.error.frames);if(!e)return;let t=Ct(e.file)+(e.line?`:${e.line}`:"");return e.fn?`${e.fn} (${t})`:t}function Pt(s){let e=$t(s.error.frames),t=s.request,r=t?`${t.method.toUpperCase()} ${t.url} ${t.status?`${Math.floor(t.status/100)}xx`:"failed"}`:e?`${e.fn??"?"}@${Ct(e.file)}`:Mr(s.error.message);return Pr("sha256").update([s.error.name,r,s.flow??""].join("|")).digest("hex").slice(0,24)}function Mt(s){return`${s.error.name}: ${s.error.message}`.slice(0,200)}function jt(s){let e={};for(let t of(s??"").split(",").map(r=>r.trim()).filter(Boolean)){let[r,n]=t.split(":");r&&n&&(e[r]=n)}return e}var Dt=s=>s.slice(0,10);function jr(s,e){let t=Date.parse(s),r=e.getTime();return Number.isNaN(t)||t>r+5*6e4||t<r-7*864e5?e.toISOString():new Date(t).toISOString()}function Ur(s){return{...s,os:{...s.os,name:s.os.name.toLowerCase()},runtime:{...s.runtime,name:s.runtime.name.toLowerCase()}}}async function Ut(s,e,t){let r=t.now?.()??new Date;if(!e||!t.keys[e])return{status:401,body:{ok:!1,error:"invalid ingest key"}};if(Buffer.byteLength(s)>(t.maxBytes??512*1024))return{status:413,body:{ok:!1,error:"payload too large"}};let n;try{n=JSON.parse(s)}catch{return{status:400,body:{ok:!1,error:"invalid json"}}}let i=At.safeParse(n);if(!i.success)return{status:400,body:{ok:!1,error:"invalid envelope",issues:i.error.flatten()}};let a=i.data,o=a.context.app.id;if(t.keys[e]!==o&&t.keys[e]!=="*")return{status:403,body:{ok:!1,error:`key not allowed for app ${o}`}};let c=Ur(a.context),u=r.toISOString(),h=[],x=[],E=new Map,T=new Set;for(let ct of a.events){let v={...ct,ts:jr(ct.ts,r)};v.type==="error"&&!v.error.frames?.length&&v.error.stack&&(v.error.frames=kt(v.error.stack));let H=Dt(v.ts);if(v.type==="session"){x.push({app:o,day:H,dimension:"session",key:`${c.app.version||"unknown"}|${v.status}`,kind:"event",by:1}),T.add("app"),v.status==="started"&&x.push({app:o,day:H,dimension:"release",key:xt(c.app),kind:"event",by:1}),v.status==="crashed"&&T.add("crash");continue}if(T.add("app"),v.type==="metric"){x.push({app:o,day:H,dimension:"requests",key:v.key,kind:"event",by:v.count}),v.errors&&x.push({app:o,day:H,dimension:"requests",key:v.key,kind:"error",by:v.errors}),v.buckets.forEach((I,ke)=>I&&x.push({app:o,day:H,dimension:"latency",key:`${v.key}|${ke}`,kind:"event",by:I}));continue}let ut=v.type==="error"?"error":"event",P=(I,ke)=>x.push({app:o,day:H,dimension:I,key:ke||"unknown",kind:ut,by:1}),Z;if(v.type==="error"){Z=Pt(v);let I=E.get(Z),ke={app:o,day:H,fingerprint:Z,event:v,context:c,user:a.user,sessionId:a.session.id,receivedAt:u};E.set(Z,{app:o,fingerprint:Z,title:Mt(v),culprit:Nt(v),flow:v.flow,by:(I?.by??0)+1,ts:I&&I.ts>v.ts?I.ts:v.ts,firstTs:I&&I.firstTs<v.ts?I.firstTs:v.ts,lastEvent:I&&I.ts>v.ts?I.lastEvent:ke,version:c.app.version}),T.add(`issue:${Z}`),P("issue",Z),v.request&&P("endpoint",`${v.request.method.toUpperCase()} ${v.request.url}`),x.push({app:o,day:v.ts.slice(0,13),dimension:"issueHour",key:Z,kind:ut,by:1})}P("total","all"),P("flow",v.flow??"untagged"),P("os",`${c.os.name} ${c.os.version??""}`.trim()),P("appVersion",c.app.version),P("deviceModel",c.device.model),v.type==="event"&&v.outcome&&v.flow&&(P("flowOutcome",`${v.flow}|${v.outcome}`),v.step&&P("flowStep",`${v.flow}|${v.step}|${v.outcome}`)),v.type==="error"&&(P("network",c.network?.type),P("country",it(c))),h.push({app:o,day:H,fingerprint:Z,event:v,context:c,user:a.user,sessionId:a.session.id,receivedAt:u})}await t.store.registerApp(o);let ze=h.length?await Ze(t.store,o,t.retentionDays):void 0,[,fe]=await Promise.all([h.length?t.store.writeEvents(h,{retentionDays:ze}):void 0,t.store.upsertIssues([...E.values()]),t.store.incrementRollups(x),Vr(t.store,o,a.user?.id??a.user?.anonymousId??a.session.id,T,Dt(u))]);return fe&&(fe.created.length||fe.regressed.length)&&await tt(o,fe,E,await Le(t.store,o)),{status:202,body:{ok:!0,accepted:a.events.length}}}var Be=new Set;async function Vr(s,e,t,r,n){if(!r.size)return;let i=Dr("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24),a=[];for(let o of r){let c=`${e}|${o}|${i}|${n}`;Be.has(c)||(Be.add(c),a.push({scope:o,member:i,day:n}))}Be.size>5e4&&Be.clear(),a.length&&await s.markUsers(e,a)}var at={"access-control-allow-origin":"*","access-control-allow-methods":"POST, OPTIONS","access-control-allow-headers":"content-type, x-debug-key","access-control-max-age":"86400"};function Vt(s){return async e=>{let t=e.requestContext?.http?.method??e.httpMethod??"POST",r=e.rawPath??e.requestContext?.http?.path??e.path??"/";if(r.startsWith("/admin")){let a=Object.fromEntries(Object.entries(e.headers??{}).map(([c,u])=>[c.toLowerCase(),u])),o=e.isBase64Encoded?Buffer.from(e.body??"","base64").toString("utf8"):e.body??"";try{let c=await nt({method:t,path:r,query:e.queryStringParameters??{},body:o,authorization:a.authorization},{store:s.store,adminToken:s.adminToken,retentionDays:s.retentionDays});return{statusCode:c.status,headers:{"content-type":"application/json"},body:JSON.stringify(c.body)}}catch(c){return console.error("[deBug] admin request failed",c),{statusCode:500,headers:{"content-type":"application/json"},body:JSON.stringify({ok:!1,error:"internal"})}}}if(t==="OPTIONS")return{statusCode:204,headers:at,body:""};if(t!=="POST")return ot(405,{ok:!1,error:"method not allowed"});let n=Object.fromEntries(Object.entries(e.headers??{}).map(([a,o])=>[a.toLowerCase(),o])),i=e.isBase64Encoded?Buffer.from(e.body??"","base64").toString("utf8"):e.body??"";try{let a=await Ut(i,n["x-debug-key"],s);return ot(a.status,a.body)}catch(a){return console.error("[deBug] ingest failed",a),ot(500,{ok:!1,error:"internal"})}}}var ot=(s,e)=>({statusCode:s,headers:{...at,"content-type":"application/json"},body:JSON.stringify(e)});var Br=Zr.from(new Lr({}),{marshallOptions:{removeUndefinedValues:!0}}),fi=Vt({store:new je(Br,{table:process.env.DEBUG_TABLE??"debugkit"}),keys:jt(process.env.DEBUG_INGEST_KEYS),retentionDays:Number(process.env.DEBUG_RETENTION_DAYS)||void 0,adminToken:process.env.DEBUG_ADMIN_TOKEN});export{fi as handler};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@debugkit/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "Set up deBug in your app: npx @debugkit/cli init (or npx debugkit init once @debugkit/sdk is installed). Deploys ingest to your own cloud, wires the SDK and walks you through the dashboard.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -20,9 +20,9 @@
|
|
|
20
20
|
},
|
|
21
21
|
"devDependencies": {
|
|
22
22
|
"@aws-sdk/lib-dynamodb": "^3.700.0",
|
|
23
|
-
"@debugkit/adapters": "^0.
|
|
24
|
-
"@debugkit/ingest": "^0.
|
|
25
|
-
"@debugkit/sdk": "^0.
|
|
23
|
+
"@debugkit/adapters": "^0.6.1",
|
|
24
|
+
"@debugkit/ingest": "^0.6.1",
|
|
25
|
+
"@debugkit/sdk": "^0.6.1"
|
|
26
26
|
},
|
|
27
27
|
"engines": {
|
|
28
28
|
"node": ">=20.12"
|