@openfin/cloud-notification-core-api 0.0.1-alpha.6fbe52a → 0.0.1-alpha.708d95f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/README.md +3 -2
  2. package/bundle.d.ts +624 -531
  3. package/index.cjs +457 -158
  4. package/index.mjs +456 -159
  5. package/package.json +7 -9
package/index.mjs CHANGED
@@ -1,9 +1,13 @@
1
1
  import { Buffer } from 'buffer';
2
2
  import mqtt from 'mqtt';
3
3
 
4
- var g;(function(r){r.assertEqual=n=>n;function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{let a={};for(let i of n)a[i]=i;return a},r.getValidEnumValues=n=>{let a=r.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(let o of a)i[o]=n[o];return r.objectValues(i)},r.objectValues=n=>r.objectKeys(n).map(function(a){return n[a]}),r.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},r.find=(n,a)=>{for(let i of n)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&isFinite(n)&&Math.floor(n)===n;function s(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=s,r.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a;})(g||(g={}));var be;(function(r){r.mergeShapes=(e,t)=>({...e,...t});})(be||(be={}));var f$1=g.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),j=r=>{switch(typeof r){case "undefined":return f$1.undefined;case "string":return f$1.string;case "number":return isNaN(r)?f$1.nan:f$1.number;case "boolean":return f$1.boolean;case "function":return f$1.function;case "bigint":return f$1.bigint;case "symbol":return f$1.symbol;case "object":return Array.isArray(r)?f$1.array:r===null?f$1.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f$1.promise:typeof Map<"u"&&r instanceof Map?f$1.map:typeof Set<"u"&&r instanceof Set?f$1.set:typeof Date<"u"&&r instanceof Date?f$1.date:f$1.object;default:return f$1.unknown}},d=g.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"]),ze=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),T=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s];},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s];};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},s={_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)s._errors.push(t(i));else {let o=s,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(i))):o[c]=o[c]||{_errors:[]},o=o[c],l++;}}};return n(this),s}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,g.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},s=[];for(let n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):s.push(e(n));return {formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};T.create=r=>new T(r);var re=(r,e)=>{let t;switch(r.code){case d.invalid_type:r.received===f$1.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case d.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,g.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:t=`Unrecognized key(s) in object: ${g.joinValues(r.keys,", ")}`;break;case d.invalid_union:t="Invalid input";break;case d.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${g.joinValues(r.options)}`;break;case d.invalid_enum_value:t=`Invalid enum value. Expected ${g.joinValues(r.options)}, received '${r.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 r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:g.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case d.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case d.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.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 ${r.multipleOf}`;break;case d.not_finite:t="Number must be finite";break;default:t=e.defaultError,g.assertNever(r);}return {message:t}},Ee=re;function De(r){Ee=r;}function pe(){return Ee}var me=r=>{let{data:e,path:t,errorMaps:s,issueData:n}=r,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return {...n,path:a,message:n.message};let o="",l=s.filter(c=>!!c).slice().reverse();for(let c of l)o=c(i,{data:e,defaultError:o}).message;return {...n,path:a,message:o}},Le=[];function u(r,e){let t=pe(),s=me({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===re?void 0:re].filter(n=>!!n)});r.common.issues.push(s);}var x=class r{constructor(){this.value="valid";}dirty(){this.value==="valid"&&(this.value="dirty");}abort(){this.value!=="aborted"&&(this.value="aborted");}static mergeArray(e,t){let s=[];for(let n of t){if(n.status==="aborted")return v;n.status==="dirty"&&e.dirty(),s.push(n.value);}return {status:e.value,value:s}}static async mergeObjectAsync(e,t){let s=[];for(let n of t){let a=await n.key,i=await n.value;s.push({key:a,value:i});}return r.mergeObjectSync(e,s)}static mergeObjectSync(e,t){let s={};for(let n of t){let{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return v;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(s[a.value]=i.value);}return {status:e.value,value:s}}},v=Object.freeze({status:"aborted"}),te=r=>({status:"dirty",value:r}),b=r=>({status:"valid",value:r}),we=r=>r.status==="aborted",Te=r=>r.status==="dirty",P=r=>r.status==="valid",ue=r=>typeof Promise<"u"&&r instanceof Promise;function ve(r,e,t,s){if(typeof e=="function"?r!==e||true:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function Re(r,e,t,s,n){if(typeof e=="function"?r!==e||true:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message;})(h||(h={}));var de,ce,S=class{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=n;}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Oe=(r,e)=>{if(P(e))return {success:true,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return {success:false,get error(){if(this._error)return this._error;let t=new T(r.common.issues);return this._error=t,this._error}}};function _(r){if(!r)return {};let{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||s))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)=>{var l,c;let{message:p}=r;return i.code==="invalid_enum_value"?{message:p??o.defaultError}:typeof o.data>"u"?{message:(l=p??s)!==null&&l!==void 0?l:o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:(c=p??t)!==null&&c!==void 0?c:o.defaultError}},description:n}}var y=class{get description(){return this._def.description}_getType(e){return j(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:j(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return {status:new x,ctx:{common:e.parent.common,data:e.data,parsedType:j(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ue(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 s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){var s;let n={common:{issues:[],async:(s=t?.async)!==null&&s!==void 0?s:false,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:j(e)},a=this._parseSync({data:e,path:n.path,parent:n});return Oe(n,a)}"~validate"(e){var t,s;let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:j(e)};if(!this["~standard"].async)try{let a=this._parseSync({data:e,path:[],parent:n});return P(a)?{value:a.value}:{issues:n.common.issues}}catch(a){!((s=(t=a?.message)===null||t===void 0?void 0:t.toLowerCase())===null||s===void 0)&&s.includes("encountered")&&(this["~standard"].async=true),n.common={issues:[],async:true};}return this._parseAsync({data:e,path:[],parent:n}).then(a=>P(a)?{value:a.value}:{issues:n.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:true},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:j(e)},n=this._parse({data:e,path:s.path,parent:s}),a=await(ue(n)?n:Promise.resolve(n));return Oe(s,a)}refine(e,t){let s=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,...s(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?true:(o(),false)):i?true:(o(),false)})}refinement(e,t){return this._refinement((s,n)=>e(s)?true:(n.addIssue(typeof t=="function"?t(s,n):t),false))}_refinement(e){return new C({schema:this,typeName:m.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 R.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return I.create(this)}promise(){return V.create(this,this._def)}or(e){return W.create([this,e],this._def)}and(e){return q.create(this,e,this._def)}transform(e){return new C({..._(this._def),schema:this,typeName:m.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Q({..._(this._def),innerType:this,defaultValue:t,typeName:m.ZodDefault})}brand(){return new le({typeName:m.ZodBranded,type:this,..._(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new X({..._(this._def),innerType:this,catchValue:t,typeName:m.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return fe.create(this,e)}readonly(){return K.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ue=/^c[^\s-]{8,}$/i,Fe=/^[0-9a-z]+$/,Be=/^[0-9A-HJKMNP-TV-Z]{26}$/i,We=/^[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,qe=/^[a-z0-9_-]{21}$/i,Je=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ye=/^[-+]?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)?)??$/,He=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ge="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ke,Qe=/^(?:(?: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])$/,Xe=/^(?:(?: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])$/,Ke=/^(([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]))$/,et=/^(([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])$/,tt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ze="((\\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])))",st=new RegExp(`^${Ze}$`);function je(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return `([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function nt(r){return new RegExp(`^${je(r)}$`)}function Ne(r){let e=`${Ze}T${je(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function at(r,e){return !!((e==="v4"||!e)&&Qe.test(r)||(e==="v6"||!e)&&Ke.test(r))}function it(r,e){if(!Je.test(r))return false;try{let[t]=r.split("."),s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(s));return !(typeof n!="object"||n===null||!n.typ||!n.alg||e&&n.alg!==e)}catch{return false}}function ot(r,e){return !!((e==="v4"||!e)&&Xe.test(r)||(e==="v6"||!e)&&et.test(r))}var $=class r extends y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f$1.string){let a=this._getOrReturnCtx(e);return u(a,{code:d.invalid_type,expected:f$1.string,received:a.parsedType}),v}let s=new x,n;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:d.too_small,minimum:a.value,type:"string",inclusive:true,exact:false,message:a.message}),s.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:d.too_big,maximum:a.value,type:"string",inclusive:true,exact:false,message:a.message}),s.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?u(n,{code:d.too_big,maximum:a.value,type:"string",inclusive:true,exact:true,message:a.message}):o&&u(n,{code:d.too_small,minimum:a.value,type:"string",inclusive:true,exact:true,message:a.message}),s.dirty());}else if(a.kind==="email")He.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"email",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="emoji")ke||(ke=new RegExp(Ge,"u")),ke.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"emoji",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="uuid")We.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"uuid",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="nanoid")qe.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"nanoid",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid")Ue.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"cuid",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid2")Fe.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"cuid2",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="ulid")Be.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"ulid",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="url")try{new URL(e.data);}catch{n=this._getOrReturnCtx(e,n),u(n,{validation:"url",code:d.invalid_string,message:a.message}),s.dirty();}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"regex",code:d.invalid_string,message:a.message}),s.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),u(n,{code:d.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),s.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),u(n,{code:d.invalid_string,validation:{startsWith:a.value},message:a.message}),s.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),u(n,{code:d.invalid_string,validation:{endsWith:a.value},message:a.message}),s.dirty()):a.kind==="datetime"?Ne(a).test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{code:d.invalid_string,validation:"datetime",message:a.message}),s.dirty()):a.kind==="date"?st.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{code:d.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?nt(a).test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{code:d.invalid_string,validation:"time",message:a.message}),s.dirty()):a.kind==="duration"?Ye.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"duration",code:d.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?at(e.data,a.version)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"ip",code:d.invalid_string,message:a.message}),s.dirty()):a.kind==="jwt"?it(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"jwt",code:d.invalid_string,message:a.message}),s.dirty()):a.kind==="cidr"?ot(e.data,a.version)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"cidr",code:d.invalid_string,message:a.message}),s.dirty()):a.kind==="base64"?tt.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"base64",code:d.invalid_string,message:a.message}),s.dirty()):a.kind==="base64url"?rt.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"base64url",code:d.invalid_string,message:a.message}),s.dirty()):g.assertNever(a);return {status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(n=>e.test(n),{validation:t,code:d.invalid_string,...h.errToObj(s)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){var t,s;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:false,local:false,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(t=e?.offset)!==null&&t!==void 0?t:false,local:(s=e?.local)!==null&&s!==void 0?s:false,...h.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,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...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}};$.create=r=>{var e;return new $({checks:[],typeName:m.ZodString,coerce:(e=r?.coerce)!==null&&e!==void 0?e:false,..._(r)})};function dt(r,e){let t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=t>s?t:s,a=parseInt(r.toFixed(n).replace(".","")),i=parseInt(e.toFixed(n).replace(".",""));return a%i/Math.pow(10,n)}var z=class r extends y{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$1.number){let a=this._getOrReturnCtx(e);return u(a,{code:d.invalid_type,expected:f$1.number,received:a.parsedType}),v}let s,n=new x;for(let a of this._def.checks)a.kind==="int"?g.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{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)&&(s=this._getOrReturnCtx(e,s),u(s,{code:d.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:false,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),u(s,{code:d.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:false,message:a.message}),n.dirty()):a.kind==="multipleOf"?dt(e.data,a.value)!==0&&(s=this._getOrReturnCtx(e,s),u(s,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:d.not_finite,message:a.message}),n.dirty()):g.assertNever(a);return {status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,true,h.toString(t))}gt(e,t){return this.setLimit("min",e,false,h.toString(t))}lte(e,t){return this.setLimit("max",e,true,h.toString(t))}lt(e,t){return this.setLimit("max",e,false,h.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:false,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:false,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:true,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:true,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:true,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:true,value:Number.MAX_SAFE_INTEGER,message:h.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"&&g.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return true;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);}return Number.isFinite(t)&&Number.isFinite(e)}};z.create=r=>new z({checks:[],typeName:m.ZodNumber,coerce:r?.coerce||false,..._(r)});var D=class r extends y{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$1.bigint)return this._getInvalidInput(e);let s,n=new x;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),u(s,{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)&&(s=this._getOrReturnCtx(e,s),u(s,{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)&&(s=this._getOrReturnCtx(e,s),u(s,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):g.assertNever(a);return {status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return u(t,{code:d.invalid_type,expected:f$1.bigint,received:t.parsedType}),v}gte(e,t){return this.setLimit("min",e,true,h.toString(t))}gt(e,t){return this.setLimit("min",e,false,h.toString(t))}lte(e,t){return this.setLimit("max",e,true,h.toString(t))}lt(e,t){return this.setLimit("max",e,false,h.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:false,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:false,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:true,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:true,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.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}};D.create=r=>{var e;return new D({checks:[],typeName:m.ZodBigInt,coerce:(e=r?.coerce)!==null&&e!==void 0?e:false,..._(r)})};var L=class extends y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f$1.boolean){let s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f$1.boolean,received:s.parsedType}),v}return b(e.data)}};L.create=r=>new L({typeName:m.ZodBoolean,coerce:r?.coerce||false,..._(r)});var U=class r extends y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f$1.date){let a=this._getOrReturnCtx(e);return u(a,{code:d.invalid_type,expected:f$1.date,received:a.parsedType}),v}if(isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return u(a,{code:d.invalid_date}),v}let s=new x,n;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:d.too_small,message:a.message,inclusive:true,exact:false,minimum:a.value,type:"date"}),s.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:d.too_big,message:a.message,inclusive:true,exact:false,maximum:a.value,type:"date"}),s.dirty()):g.assertNever(a);return {status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.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}};U.create=r=>new U({checks:[],coerce:r?.coerce||false,typeName:m.ZodDate,..._(r)});var se=class extends y{_parse(e){if(this._getType(e)!==f$1.symbol){let s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f$1.symbol,received:s.parsedType}),v}return b(e.data)}};se.create=r=>new se({typeName:m.ZodSymbol,..._(r)});var F=class extends y{_parse(e){if(this._getType(e)!==f$1.undefined){let s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f$1.undefined,received:s.parsedType}),v}return b(e.data)}};F.create=r=>new F({typeName:m.ZodUndefined,..._(r)});var B=class extends y{_parse(e){if(this._getType(e)!==f$1.null){let s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f$1.null,received:s.parsedType}),v}return b(e.data)}};B.create=r=>new B({typeName:m.ZodNull,..._(r)});var M=class extends y{constructor(){super(...arguments),this._any=true;}_parse(e){return b(e.data)}};M.create=r=>new M({typeName:m.ZodAny,..._(r)});var N=class extends y{constructor(){super(...arguments),this._unknown=true;}_parse(e){return b(e.data)}};N.create=r=>new N({typeName:m.ZodUnknown,..._(r)});var A=class extends y{_parse(e){let t=this._getOrReturnCtx(e);return u(t,{code:d.invalid_type,expected:f$1.never,received:t.parsedType}),v}};A.create=r=>new A({typeName:m.ZodNever,..._(r)});var ne=class extends y{_parse(e){if(this._getType(e)!==f$1.undefined){let s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f$1.void,received:s.parsedType}),v}return b(e.data)}};ne.create=r=>new ne({typeName:m.ZodVoid,..._(r)});var I=class r extends y{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==f$1.array)return u(t,{code:d.invalid_type,expected:f$1.array,received:t.parsedType}),v;if(n.exactLength!==null){let i=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(i||o)&&(u(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:true,exact:true,message:n.exactLength.message}),s.dirty());}if(n.minLength!==null&&t.data.length<n.minLength.value&&(u(t,{code:d.too_small,minimum:n.minLength.value,type:"array",inclusive:true,exact:false,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(u(t,{code:d.too_big,maximum:n.maxLength.value,type:"array",inclusive:true,exact:false,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>n.type._parseAsync(new S(t,i,t.path,o)))).then(i=>x.mergeArray(s,i));let a=[...t.data].map((i,o)=>n.type._parseSync(new S(t,i,t.path,o)));return x.mergeArray(s,a)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};I.create=(r,e)=>new I({type:r,minLength:null,maxLength:null,exactLength:null,typeName:m.ZodArray,..._(e)});function ee(r){if(r instanceof w){let e={};for(let t in r.shape){let s=r.shape[t];e[t]=O.create(ee(s));}return new w({...r._def,shape:()=>e})}else return r instanceof I?new I({...r._def,type:ee(r.element)}):r instanceof O?O.create(ee(r.unwrap())):r instanceof R?R.create(ee(r.unwrap())):r instanceof E?E.create(r.items.map(e=>ee(e))):r}var w=class r extends y{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=g.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==f$1.object){let c=this._getOrReturnCtx(e);return u(c,{code:d.invalid_type,expected:f$1.object,received:c.parsedType}),v}let{status:s,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof A&&this._def.unknownKeys==="strip"))for(let c in n.data)i.includes(c)||o.push(c);let l=[];for(let c of i){let p=a[c],k=n.data[c];l.push({key:{status:"valid",value:c},value:p._parse(new S(n,k,n.path,c)),alwaysSet:c in n.data});}if(this._def.catchall instanceof A){let c=this._def.unknownKeys;if(c==="passthrough")for(let p of o)l.push({key:{status:"valid",value:p},value:{status:"valid",value:n.data[p]}});else if(c==="strict")o.length>0&&(u(n,{code:d.unrecognized_keys,keys:o}),s.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else {let c=this._def.catchall;for(let p of o){let k=n.data[p];l.push({key:{status:"valid",value:p},value:c._parse(new S(n,k,n.path,p)),alwaysSet:p in n.data});}}return n.common.async?Promise.resolve().then(async()=>{let c=[];for(let p of l){let k=await p.key,he=await p.value;c.push({key:k,value:he,alwaysSet:p.alwaysSet});}return c}).then(c=>x.mergeObjectSync(s,c)):x.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{var n,a,i,o;let l=(i=(a=(n=this._def).errorMap)===null||a===void 0?void 0:a.call(n,t,s).message)!==null&&i!==void 0?i:s.defaultError;return t.code==="unrecognized_keys"?{message:(o=h.errToObj(e).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:m.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};return g.objectKeys(e).forEach(s=>{e[s]&&this.shape[s]&&(t[s]=this.shape[s]);}),new r({...this._def,shape:()=>t})}omit(e){let t={};return g.objectKeys(this.shape).forEach(s=>{e[s]||(t[s]=this.shape[s]);}),new r({...this._def,shape:()=>t})}deepPartial(){return ee(this)}partial(e){let t={};return g.objectKeys(this.shape).forEach(s=>{let n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional();}),new r({...this._def,shape:()=>t})}required(e){let t={};return g.objectKeys(this.shape).forEach(s=>{if(e&&!e[s])t[s]=this.shape[s];else {let a=this.shape[s];for(;a instanceof O;)a=a._def.innerType;t[s]=a;}}),new r({...this._def,shape:()=>t})}keyof(){return Ie(g.objectKeys(this.shape))}};w.create=(r,e)=>new w({shape:()=>r,unknownKeys:"strip",catchall:A.create(),typeName:m.ZodObject,..._(e)});w.strictCreate=(r,e)=>new w({shape:()=>r,unknownKeys:"strict",catchall:A.create(),typeName:m.ZodObject,..._(e)});w.lazycreate=(r,e)=>new w({shape:r,unknownKeys:"strip",catchall:A.create(),typeName:m.ZodObject,..._(e)});var W=class extends y{_parse(e){let{ctx:t}=this._processInputParams(e),s=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 T(o.ctx.common.issues));return u(t,{code:d.invalid_union,unionErrors:i}),v}if(t.common.async)return Promise.all(s.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 l of s){let c={...t,common:{...t.common,issues:[]},parent:null},p=l._parseSync({data:t.data,path:t.path,parent:c});if(p.status==="valid")return p;p.status==="dirty"&&!a&&(a={result:p,ctx:c}),c.common.issues.length&&i.push(c.common.issues);}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(l=>new T(l));return u(t,{code:d.invalid_union,unionErrors:o}),v}}get options(){return this._def.options}};W.create=(r,e)=>new W({options:r,typeName:m.ZodUnion,..._(e)});var Z=r=>r instanceof J?Z(r.schema):r instanceof C?Z(r.innerType()):r instanceof Y?[r.value]:r instanceof H?r.options:r instanceof G?g.objectValues(r.enum):r instanceof Q?Z(r._def.innerType):r instanceof F?[void 0]:r instanceof B?[null]:r instanceof O?[void 0,...Z(r.unwrap())]:r instanceof R?[null,...Z(r.unwrap())]:r instanceof le||r instanceof K?Z(r.unwrap()):r instanceof X?Z(r._def.innerType):[],_e=class r extends y{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f$1.object)return u(t,{code:d.invalid_type,expected:f$1.object,received:t.parsedType}),v;let s=this.discriminator,n=t.data[s],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}):(u(t,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),v)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){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 r({typeName:m.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,..._(s)})}};function Ce(r,e){let t=j(r),s=j(e);if(r===e)return {valid:true,data:r};if(t===f$1.object&&s===f$1.object){let n=g.objectKeys(e),a=g.objectKeys(r).filter(o=>n.indexOf(o)!==-1),i={...r,...e};for(let o of a){let l=Ce(r[o],e[o]);if(!l.valid)return {valid:false};i[o]=l.data;}return {valid:true,data:i}}else if(t===f$1.array&&s===f$1.array){if(r.length!==e.length)return {valid:false};let n=[];for(let a=0;a<r.length;a++){let i=r[a],o=e[a],l=Ce(i,o);if(!l.valid)return {valid:false};n.push(l.data);}return {valid:true,data:n}}else return t===f$1.date&&s===f$1.date&&+r==+e?{valid:true,data:r}:{valid:false}}var q=class extends y{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=(a,i)=>{if(we(a)||we(i))return v;let o=Ce(a.value,i.value);return o.valid?((Te(a)||Te(i))&&t.dirty(),{status:t.value,value:o.data}):(u(s,{code:d.invalid_intersection_types}),v)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};q.create=(r,e,t)=>new q({left:r,right:e,typeName:m.ZodIntersection,..._(t)});var E=class r extends y{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f$1.array)return u(s,{code:d.invalid_type,expected:f$1.array,received:s.parsedType}),v;if(s.data.length<this._def.items.length)return u(s,{code:d.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"}),v;!this._def.rest&&s.data.length>this._def.items.length&&(u(s,{code:d.too_big,maximum:this._def.items.length,inclusive:true,exact:false,type:"array"}),t.dirty());let a=[...s.data].map((i,o)=>{let l=this._def.items[o]||this._def.rest;return l?l._parse(new S(s,i,s.path,o)):null}).filter(i=>!!i);return s.common.async?Promise.all(a).then(i=>x.mergeArray(t,i)):x.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};E.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new E({items:r,typeName:m.ZodTuple,rest:null,..._(e)})};var ye=class r extends y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f$1.object)return u(s,{code:d.invalid_type,expected:f$1.object,received:s.parsedType}),v;let n=[],a=this._def.keyType,i=this._def.valueType;for(let o in s.data)n.push({key:a._parse(new S(s,o,s.path,o)),value:i._parse(new S(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?x.mergeObjectAsync(t,n):x.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof y?new r({keyType:e,valueType:t,typeName:m.ZodRecord,..._(s)}):new r({keyType:$.create(),valueType:e,typeName:m.ZodRecord,..._(t)})}},ae=class extends y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f$1.map)return u(s,{code:d.invalid_type,expected:f$1.map,received:s.parsedType}),v;let n=this._def.keyType,a=this._def.valueType,i=[...s.data.entries()].map(([o,l],c)=>({key:n._parse(new S(s,o,s.path,[c,"key"])),value:a._parse(new S(s,l,s.path,[c,"value"]))}));if(s.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,p=await l.value;if(c.status==="aborted"||p.status==="aborted")return v;(c.status==="dirty"||p.status==="dirty")&&t.dirty(),o.set(c.value,p.value);}return {status:t.value,value:o}})}else {let o=new Map;for(let l of i){let c=l.key,p=l.value;if(c.status==="aborted"||p.status==="aborted")return v;(c.status==="dirty"||p.status==="dirty")&&t.dirty(),o.set(c.value,p.value);}return {status:t.value,value:o}}}};ae.create=(r,e,t)=>new ae({valueType:e,keyType:r,typeName:m.ZodMap,..._(t)});var ie=class r extends y{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f$1.set)return u(s,{code:d.invalid_type,expected:f$1.set,received:s.parsedType}),v;let n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(u(s,{code:d.too_small,minimum:n.minSize.value,type:"set",inclusive:true,exact:false,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(u(s,{code:d.too_big,maximum:n.maxSize.value,type:"set",inclusive:true,exact:false,message:n.maxSize.message}),t.dirty());let a=this._def.valueType;function i(l){let c=new Set;for(let p of l){if(p.status==="aborted")return v;p.status==="dirty"&&t.dirty(),c.add(p.value);}return {status:t.value,value:c}}let o=[...s.data.values()].map((l,c)=>a._parse(new S(s,l,s.path,c)));return s.common.async?Promise.all(o).then(l=>i(l)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ie.create=(r,e)=>new ie({valueType:r,minSize:null,maxSize:null,typeName:m.ZodSet,..._(e)});var ge=class r extends y{constructor(){super(...arguments),this.validate=this.implement;}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f$1.function)return u(t,{code:d.invalid_type,expected:f$1.function,received:t.parsedType}),v;function s(o,l){return me({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pe(),re].filter(c=>!!c),issueData:{code:d.invalid_arguments,argumentsError:l}})}function n(o,l){return me({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pe(),re].filter(c=>!!c),issueData:{code:d.invalid_return_type,returnTypeError:l}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof V){let o=this;return b(async function(...l){let c=new T([]),p=await o._def.args.parseAsync(l,a).catch(xe=>{throw c.addIssue(s(l,xe)),c}),k=await Reflect.apply(i,this,p);return await o._def.returns._def.type.parseAsync(k,a).catch(xe=>{throw c.addIssue(n(k,xe)),c})})}else {let o=this;return b(function(...l){let c=o._def.args.safeParse(l,a);if(!c.success)throw new T([s(l,c.error)]);let p=Reflect.apply(i,this,c.data),k=o._def.returns.safeParse(p,a);if(!k.success)throw new T([n(p,k.error)]);return k.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:E.create(e).rest(N.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new r({args:e||E.create([]).rest(N.create()),returns:t||N.create(),typeName:m.ZodFunction,..._(s)})}},J=class extends y{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})}};J.create=(r,e)=>new J({getter:r,typeName:m.ZodLazy,..._(e)});var Y=class extends y{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return u(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),v}return {status:"valid",value:e.data}}get value(){return this._def.value}};Y.create=(r,e)=>new Y({value:r,typeName:m.ZodLiteral,..._(e)});function Ie(r,e){return new H({values:r,typeName:m.ZodEnum,..._(e)})}var H=class r extends y{constructor(){super(...arguments),de.set(this,void 0);}_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),s=this._def.values;return u(t,{expected:g.joinValues(s),received:t.parsedType,code:d.invalid_type}),v}if(ve(this,de)||Re(this,de,new Set(this._def.values)),!ve(this,de).has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return u(t,{received:t.data,code:d.invalid_enum_value,options:s}),v}return b(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 r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}};de=new WeakMap;H.create=Ie;var G=class extends y{constructor(){super(...arguments),ce.set(this,void 0);}_parse(e){let t=g.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f$1.string&&s.parsedType!==f$1.number){let n=g.objectValues(t);return u(s,{expected:g.joinValues(n),received:s.parsedType,code:d.invalid_type}),v}if(ve(this,ce)||Re(this,ce,new Set(g.getValidEnumValues(this._def.values))),!ve(this,ce).has(e.data)){let n=g.objectValues(t);return u(s,{received:s.data,code:d.invalid_enum_value,options:n}),v}return b(e.data)}get enum(){return this._def.values}};ce=new WeakMap;G.create=(r,e)=>new G({values:r,typeName:m.ZodNativeEnum,..._(e)});var V=class extends y{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f$1.promise&&t.common.async===false)return u(t,{code:d.invalid_type,expected:f$1.promise,received:t.parsedType}),v;let s=t.parsedType===f$1.promise?t.data:Promise.resolve(t.data);return b(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};V.create=(r,e)=>new V({type:r,typeName:m.ZodPromise,..._(e)});var C=class extends y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===m.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{u(s,i),i.fatal?t.abort():t.dirty();},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){let i=n.transform(s.data,a);if(s.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return v;let l=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return l.status==="aborted"?v:l.status==="dirty"||t.value==="dirty"?te(l.value):l});{if(t.value==="aborted")return v;let o=this._def.schema._parseSync({data:i,path:s.path,parent:s});return o.status==="aborted"?v:o.status==="dirty"||t.value==="dirty"?te(o.value):o}}if(n.type==="refinement"){let i=o=>{let l=n.refinement(o,a);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===false){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?v:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?v:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(s.common.async===false){let i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!P(i))return i;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:s.data,path:s.path,parent:s}).then(i=>P(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):i);g.assertNever(n);}};C.create=(r,e,t)=>new C({schema:r,typeName:m.ZodEffects,effect:e,..._(t)});C.createWithPreprocess=(r,e,t)=>new C({schema:e,effect:{type:"preprocess",transform:r},typeName:m.ZodEffects,..._(t)});var O=class extends y{_parse(e){return this._getType(e)===f$1.undefined?b(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};O.create=(r,e)=>new O({innerType:r,typeName:m.ZodOptional,..._(e)});var R=class extends y{_parse(e){return this._getType(e)===f$1.null?b(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};R.create=(r,e)=>new R({innerType:r,typeName:m.ZodNullable,..._(e)});var Q=class extends y{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===f$1.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Q.create=(r,e)=>new Q({innerType:r,typeName:m.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});var X=class extends y{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return ue(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new T(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new T(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};X.create=(r,e)=>new X({innerType:r,typeName:m.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});var oe=class extends y{_parse(e){if(this._getType(e)!==f$1.nan){let s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f$1.nan,received:s.parsedType}),v}return {status:"valid",value:e.data}}};oe.create=r=>new oe({typeName:m.ZodNaN,..._(r)});var ct=Symbol("zod_brand"),le=class extends y{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},fe=class r extends y{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return (async()=>{let a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?v:a.status==="dirty"?(t.dirty(),te(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{let n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?v:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,t){return new r({in:e,out:t,typeName:m.ZodPipeline})}},K=class extends y{_parse(e){let t=this._def.innerType._parse(e),s=n=>(P(n)&&(n.value=Object.freeze(n.value)),n);return ue(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}};K.create=(r,e)=>new K({innerType:r,typeName:m.ZodReadonly,..._(e)});function Se(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function $e(r,e={},t){return r?M.create().superRefine((s,n)=>{var a,i;let o=r(s);if(o instanceof Promise)return o.then(l=>{var c,p;if(!l){let k=Se(e,s),he=(p=(c=k.fatal)!==null&&c!==void 0?c:t)!==null&&p!==void 0?p:true;n.addIssue({code:"custom",...k,fatal:he});}});if(!o){let l=Se(e,s),c=(i=(a=l.fatal)!==null&&a!==void 0?a:t)!==null&&i!==void 0?i:true;n.addIssue({code:"custom",...l,fatal:c});}}):M.create()}var ut={object:w.lazycreate},m;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly";})(m||(m={}));var lt=(r,e={message:`Input not instance of ${r.name}`})=>$e(t=>t instanceof r,e),Me=$.create,Ve=z.create,ft=oe.create,ht=D.create,Pe=L.create,pt=U.create,mt=se.create,vt=F.create,_t=B.create,yt=M.create,gt=N.create,xt=A.create,kt=ne.create,bt=I.create,wt=w.create,Tt=w.strictCreate,Ct=W.create,Ot=_e.create,St=q.create,At=E.create,Et=ye.create,Rt=ae.create,Zt=ie.create,jt=ge.create,Nt=J.create,It=Y.create,$t=H.create,Mt=G.create,Vt=V.create,Ae=C.create,Pt=O.create,zt=R.create,Dt=C.createWithPreprocess,Lt=fe.create,Ut=()=>Me().optional(),Ft=()=>Ve().optional(),Bt=()=>Pe().optional(),Wt={string:r=>$.create({...r,coerce:true}),number:r=>z.create({...r,coerce:true}),boolean:r=>L.create({...r,coerce:true}),bigint:r=>D.create({...r,coerce:true}),date:r=>U.create({...r,coerce:true})},qt=v,Jt=Object.freeze({__proto__:null,defaultErrorMap:re,setErrorMap:De,getErrorMap:pe,makeIssue:me,EMPTY_PATH:Le,addIssueToContext:u,ParseStatus:x,INVALID:v,DIRTY:te,OK:b,isAborted:we,isDirty:Te,isValid:P,isAsync:ue,get util(){return g},get objectUtil(){return be},ZodParsedType:f$1,getParsedType:j,ZodType:y,datetimeRegex:Ne,ZodString:$,ZodNumber:z,ZodBigInt:D,ZodBoolean:L,ZodDate:U,ZodSymbol:se,ZodUndefined:F,ZodNull:B,ZodAny:M,ZodUnknown:N,ZodNever:A,ZodVoid:ne,ZodArray:I,ZodObject:w,ZodUnion:W,ZodDiscriminatedUnion:_e,ZodIntersection:q,ZodTuple:E,ZodRecord:ye,ZodMap:ae,ZodSet:ie,ZodFunction:ge,ZodLazy:J,ZodLiteral:Y,ZodEnum:H,ZodNativeEnum:G,ZodPromise:V,ZodEffects:C,ZodTransformer:C,ZodOptional:O,ZodNullable:R,ZodDefault:Q,ZodCatch:X,ZodNaN:oe,BRAND:ct,ZodBranded:le,ZodPipeline:fe,ZodReadonly:K,custom:$e,Schema:y,ZodSchema:y,late:ut,get ZodFirstPartyTypeKind(){return m},coerce:Wt,any:yt,array:bt,bigint:ht,boolean:Pe,date:pt,discriminatedUnion:Ot,effect:Ae,enum:$t,function:jt,instanceof:lt,intersection:St,lazy:Nt,literal:It,map:Rt,nan:ft,nativeEnum:Mt,never:xt,null:_t,nullable:zt,number:Ve,object:wt,oboolean:Bt,onumber:Ft,optional:Pt,ostring:Ut,pipeline:Lt,preprocess:Dt,promise:Vt,record:Et,set:Zt,strictObject:Tt,string:Me,symbol:mt,transformer:Ae,tuple:At,undefined:vt,union:Ct,unknown:gt,void:kt,NEVER:qt,ZodIssueCode:d,quotelessJson:ze,ZodError:T});
4
+ var Y$1;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Y$1="oauth4webapi/v3.8.8");function q$1(e,t){if(e==null)return false;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return false}}var y$1="ERR_INVALID_ARG_VALUE",_$1="ERR_INVALID_ARG_TYPE";function l(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var L$1=Symbol(),W$1=Symbol(),M$1=Symbol(),O$1=Symbol();var qe$1=new TextEncoder,We$1=new TextDecoder;function le$1(e){return typeof e=="string"?qe$1.encode(e):We$1.decode(e)}var Q$1;Uint8Array.prototype.toBase64?Q$1=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:true})):Q$1=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=32768)n.push(String.fromCharCode.apply(null,t.subarray(r,r+32768)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var X$1;Uint8Array.fromBase64?X$1=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw l("The input to be decoded is not correctly encoded.",y$1,t)}}:X$1=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}catch(t){throw l("The input to be decoded is not correctly encoded.",y$1,t)}};function fe$1(e){return typeof e=="string"?X$1(e):Q$1(e)}var T=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=K$1,Error.captureStackTrace?.(this,this.constructor);}},D$1=class D extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,n?.code&&(this.code=n?.code),Error.captureStackTrace?.(this,this.constructor);}};function i$1(e,t,n){return new D$1(e,{code:t,cause:n})}function H$1(e){return !(e===null||typeof e!="object"||Array.isArray(e))}function me$1(e){q$1(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(Y$1&&!t.has("user-agent")&&t.set("user-agent",Y$1),t.has("authorization"))throw l('"options.headers" must not include the "authorization" header name',y$1);return t}function ye$1(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw l('"options.signal" must return or be an instance of AbortSignal',_$1);return t}}function _e$1(e){return e.includes("//")?e.replace("//","/"):e}function Me$1(e,t,n=false){return e.pathname==="/"?e.pathname=t:e.pathname=_e$1(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,"")}`),e}function ze$1(e,t){return e.pathname=_e$1(`${e.pathname}/${t}`),e}async function Ke$1(e,t,n,r){if(!(e instanceof URL))throw l(`"${t}" must be an instance of URL`,_$1);z$1(e,r?.[L$1]!==true);let o=n(new URL(e.href)),s=me$1(r?.headers);return s.set("accept","application/json"),(r?.[O$1]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:ye$1(o,r?.signal)})}async function ge(e,t){return Ke$1(e,"issuerIdentifier",n=>{switch(t?.algorithm){case void 0:case "oidc":ze$1(n,".well-known/openid-configuration");break;case "oauth2":Me$1(n,".well-known/oauth-authorization-server");break;default:throw l('"options.algorithm" must be "oidc" (default), or "oauth2"',y$1)}return n},t)}function Z$1(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw l(`${n} must be a number`,_$1,o);if(e>0)return;if(t){if(e!==0)throw l(`${n} must be a non-negative number`,y$1,o);return}throw l(`${n} must be a positive number`,y$1,o)}catch(s){throw r?i$1(s.message,r,o):s}}function b$1(e,t,n,r){try{if(typeof e!="string")throw l(`${t} must be a string`,_$1,r);if(e.length===0)throw l(`${t} must not be empty`,y$1,r)}catch(o){throw n?i$1(o.message,n,r):o}}async function Re$1(e,t){let n=e;if(!(n instanceof URL)&&n!==J$1)throw l('"expectedIssuerIdentifier" must be an instance of URL',_$1);if(!q$1(t,Response))throw l('"response" must be an instance of Response',_$1);if(t.status!==200)throw i$1('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',$$1,t);oe$1(t);let r=await Ie$1(t);if(b$1(r.issuer,'"response" body "issuer" property',d$2,{body:r}),n!==J$1&&new URL(r.issuer).href!==n.href)throw i$1('"response" body "issuer" property does not match the expected value',F$1,{expected:n.href,body:r,attribute:"issuer"});return r}function be(e){Fe$1(e,"application/json");}function $e(e,...t){let n='"response" content-type must be ';if(t.length>2){let r=t.pop();n+=`${t.join(", ")}, or ${r}`;}else t.length===2?n+=`${t[0]} or ${t[1]}`:n+=t[0];return i$1(n,te$1,e)}function Fe$1(e,t){if(Ee$1(e)!==t)throw $e(e,t)}function Be$1(e){let t=e?.[W$1];return typeof t=="number"&&Number.isFinite(t)?t:0}function Ge$1(e){let t=e?.[M$1];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Ve$1(){return Math.floor(Date.now()/1e3)}function Se$1(e){if(typeof e!="object"||e===null)throw l('"as" must be an object',_$1);b$1(e.issuer,'"as.issuer"');}function Pe$1(e){if(typeof e!="object"||e===null)throw l('"client" must be an object',_$1);b$1(e.client_id,'"client.client_id"');}function ee$1(e){return b$1(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e);}}function Ae$1(){return (e,t,n,r)=>{n.set("client_id",t.client_id);}}var Ye$1=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function z$1(e,t){if(t&&e.protocol!=="https:")throw i$1("only requests to HTTPS are allowed",ne$1,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw i$1("only HTTP and HTTPS requests are allowed",re$1,e)}function pe$1(e,t,n,r){let o;if(typeof e!="string"||!(o=Ye$1(e)))throw i$1(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Tt$1:kt$1,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return z$1(o,r),o}function Te$1(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?pe$1(e.mtls_endpoint_aliases[t],t,n,r):pe$1(e[t],t,n,r)}var g$1=class g extends Error{cause;code;error;status;error_description;response;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Pt$1,this.cause=n.cause,this.error=n.cause.error,this.status=n.response.status,this.error_description=n.cause.error_description,Object.defineProperty(this,"response",{enumerable:false,value:n.response}),Error.captureStackTrace?.(this,this.constructor);}},I$2=class I extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=At$1,this.cause=n.cause,this.error=n.cause.get("error"),this.error_description=n.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor);}},k$1=class k extends Error{cause;code;response;status;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=St$1,this.cause=n.cause,this.status=n.response.status,this.response=n.response,Object.defineProperty(this,"response",{enumerable:false}),Error.captureStackTrace?.(this,this.constructor);}},N$2="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",Qe$1="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",Xe$1='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',Ze$1="("+N$2+")\\s*=\\s*"+Xe$1,et$1="("+N$2+")\\s*=\\s*("+N$2+")",tt$1=new RegExp("^[,\\s]*("+N$2+")"),nt$1=new RegExp("^[,\\s]*"+Ze$1+"[,\\s]*(.*)"),rt$1=new RegExp("^[,\\s]*"+et$1+"[,\\s]*(.*)"),ot$1=new RegExp("^("+Qe$1+")(?:$|[,\\s])(.*)");function at$1(e){if(!q$1(e,Response))throw l('"response" must be an instance of Response',_$1);let t=e.headers.get("www-authenticate");if(t===null)return;let n=[],r=t;for(;r;){let o=r.match(tt$1),s=o?.[1].toLowerCase();if(!s)return;let a=r.substring(o[0].length);if(a&&!a.match(/^[\s,]/))return;let u=a.match(/^\s+(.*)$/),h=!!u;r=u?u[1]:void 0;let c={},p;if(h)for(;r;){let P,A;if(o=r.match(nt$1)){[,P,A,r]=o,A.includes("\\")&&(A=A.replace(/\\([\s\S])/g,"$1")),c[P.toLowerCase()]=A;continue}if(o=r.match(rt$1)){[,P,A,r]=o,c[P.toLowerCase()]=A;continue}if(o=r.match(ot$1)){if(Object.keys(c).length)break;[,p,r]=o;break}return}else r=a||void 0;let m={scheme:s,parameters:c};p&&(m.token68=p),n.push(m);}if(n.length)return n}async function st$1(e){if(e.status>399&&e.status<500){oe$1(e),be(e);try{let t=await e.clone().json();if(H$1(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function it$1(e,t,n){if(e.status!==t){ft$1(e);let r;throw (r=await st$1(e))?(await e.body?.cancel(),new g$1("server responded with an error in the response body",{cause:r,response:e})):i$1(`"response" is not a conform ${n} response (unexpected HTTP status code)`,$$1,e)}}function Ee$1(e){return e.headers.get("content-type")?.split(";")[0]}async function ut$1(e,t,n,r,o,s,a){return await n(e,t,o,s),s.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(a?.[O$1]||fetch)(r.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:ye$1(r,a?.signal)})}async function dt$1(e,t,n,r,o,s){let a=Te$1(e,"token_endpoint",t.use_mtls_endpoint_aliases,s?.[L$1]!==true);o.set("grant_type",r);let u=me$1(s?.headers);u.set("accept","application/json");let h=await ut$1(e,t,n,a,o,u,s);return h}var xe$1=new WeakMap,ht$1=new WeakMap;function Oe$1(e){if(!e.id_token)return;let t=xe$1.get(e);if(!t)throw l('"ref" was already garbage collected or did not resolve from the proper sources',y$1);return t}async function lt$1(e,t,n,r,o,s){if(Se$1(e),Pe$1(t),!q$1(n,Response))throw l('"response" must be an instance of Response',_$1);await it$1(n,200,"Token Endpoint"),oe$1(n);let a=await Ie$1(n);if(b$1(a.access_token,'"response" body "access_token" property',d$2,{body:a}),b$1(a.token_type,'"response" body "token_type" property',d$2,{body:a}),a.token_type=a.token_type.toLowerCase(),a.expires_in!==void 0){let u=typeof a.expires_in!="number"?parseFloat(a.expires_in):a.expires_in;Z$1(u,true,'"response" body "expires_in" property',d$2,{body:a}),a.expires_in=u;}if(a.refresh_token!==void 0&&b$1(a.refresh_token,'"response" body "refresh_token" property',d$2,{body:a}),a.scope!==void 0&&typeof a.scope!="string")throw i$1('"response" body "scope" property must be a string',d$2,{body:a});if(a.id_token!==void 0){b$1(a.id_token,'"response" body "id_token" property',d$2,{body:a});let u=[];t.require_auth_time===true&&u.push("auth_time"),t.default_max_age!==void 0&&(Z$1(t.default_max_age,true,'"client.default_max_age"'),u.push("auth_time"));let{claims:h,jwt:c}=await gt$1(e,t,a.id_token,u);bt$1(t,h),Rt$1(h),ht$1.set(n,c),xe$1.set(a,h);}if(a.token_type!=="dpop"&&a.token_type!=="bearer")throw new T("unsupported `token_type` value",{cause:{body:a}});return a}function ft$1(e){let t;if(t=at$1(e))throw new k$1("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}function pt$1(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw i$1('unexpected JWT "aud" (audience) claim value',E$1,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw i$1('unexpected JWT "aud" (audience) claim value',E$1,{expected:e,claims:t.claims,claim:"aud"});return t}function wt$1(e,t){let n=e[ae$1]?.(t)??e.issuer;if(t.claims.iss!==n)throw i$1('unexpected JWT "iss" (issuer) claim value',E$1,{expected:n,claims:t.claims,claim:"iss"});return t}var Ce$1={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function yt$1(e,t){for(let n of e)if(t.claims[n]===void 0)throw i$1(`JWT "${n}" (${Ce$1[n]}) claim missing`,d$2,{claims:t.claims});return t}function _t$1(e,t){if(typeof t.claims[e]!="string")throw i$1(`unexpected JWT "${e}" (${Ce$1[e]}) claim type`,d$2,{claims:t.claims});return t}function gt$1(e,t,n,r,o){return Et$1(n,xt$1.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Be$1(t),Ge$1(t)).then(yt$1.bind(void 0,["aud","exp","iat","iss","sub",...r])).then(wt$1.bind(void 0,e)).then(pt$1.bind(void 0,t.client_id)).then(_t$1.bind(void 0,"sub"))}function Rt$1(e){e.auth_time!==void 0&&Z$1(e.auth_time,true,'ID Token "auth_time" (authentication time)',d$2,{claims:e});}function bt$1(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw i$1('ID Token "aud" (audience) claim includes additional untrusted audiences',E$1,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw i$1('unexpected ID Token "azp" (authorized party) claim value',E$1,{expected:e.client_id,claims:t,claim:"azp"})}}var St$1="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Pt$1="OAUTH_RESPONSE_BODY_ERROR",K$1="OAUTH_UNSUPPORTED_OPERATION",At$1="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var U$1="OAUTH_PARSE_ERROR",d$2="OAUTH_INVALID_RESPONSE";var te$1="OAUTH_RESPONSE_IS_NOT_JSON",$$1="OAUTH_RESPONSE_IS_NOT_CONFORM",ne$1="OAUTH_HTTP_REQUEST_FORBIDDEN",re$1="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",j$1="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",E$1="OAUTH_JWT_CLAIM_COMPARISON_FAILED",F$1="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var Tt$1="OAUTH_MISSING_SERVER_METADATA",kt$1="OAUTH_INVALID_SERVER_METADATA";async function ve$1(e,t,n,r,o){return Se$1(e),Pe$1(t),dt$1(e,t,n,"client_credentials",new URLSearchParams(r),o)}async function De$1(e,t,n,r){return lt$1(e,t,n)}function oe$1(e){if(e.bodyUsed)throw l('"response" body has been used already',y$1)}async function Et$1(e,t,n,r,o){let{0:s,1:a,length:u}=e.split(".");if(u===5)throw new T("JWE decryption is not configured",{cause:e});if(u!==3)throw i$1("Invalid JWT",d$2,e);let h;try{h=JSON.parse(le$1(fe$1(s)));}catch(m){throw i$1("failed to parse JWT Header body as base64url encoded JSON",U$1,m)}if(!H$1(h))throw i$1("JWT Header must be a top level object",d$2,e);if(t(h),h.crit!==void 0)throw new T('no JWT "crit" header parameter extensions are supported',{cause:{header:h}});let c;try{c=JSON.parse(le$1(fe$1(a)));}catch(m){throw i$1("failed to parse JWT Payload body as base64url encoded JSON",U$1,m)}if(!H$1(c))throw i$1("JWT Payload must be a top level object",d$2,e);let p=Ve$1()+n;if(c.exp!==void 0){if(typeof c.exp!="number")throw i$1('unexpected JWT "exp" (expiration time) claim type',d$2,{claims:c});if(c.exp<=p-r)throw i$1('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',j$1,{claims:c,now:p,tolerance:r,claim:"exp"})}if(c.iat!==void 0&&typeof c.iat!="number")throw i$1('unexpected JWT "iat" (issued at) claim type',d$2,{claims:c});if(c.iss!==void 0&&typeof c.iss!="string")throw i$1('unexpected JWT "iss" (issuer) claim type',d$2,{claims:c});if(c.nbf!==void 0){if(typeof c.nbf!="number")throw i$1('unexpected JWT "nbf" (not before) claim type',d$2,{claims:c});if(c.nbf>p+r)throw i$1('unexpected JWT "nbf" (not before) claim value',j$1,{claims:c,now:p,tolerance:r,claim:"nbf"})}if(c.aud!==void 0&&typeof c.aud!="string"&&!Array.isArray(c.aud))throw i$1('unexpected JWT "aud" (audience) claim type',d$2,{claims:c});return {header:h,claims:c,jwt:e}}function xt$1(e,t,n,r){if(e!==void 0){if(typeof e=="string"?r.alg!==e:!e.includes(r.alg))throw i$1('unexpected JWT "alg" header parameter',d$2,{header:r,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(r.alg))throw i$1('unexpected JWT "alg" header parameter',d$2,{header:r,expected:t,reason:"authorization server metadata"});return}if(n!==void 0){if(typeof n=="string"?r.alg!==n:typeof n=="function"?!n(r.alg):!n.includes(r.alg))throw i$1('unexpected JWT "alg" header parameter',d$2,{header:r,expected:n,reason:"default value"});return}throw i$1('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n})}async function Ie$1(e,t=be){let n;try{n=await e.json();}catch(r){throw t(e),i$1('failed to parse "response" body as JSON',U$1,r)}if(!H$1(n))throw i$1('"response" body must be a top level object',d$2,{body:n});return n}var J$1=Symbol(),ae$1=Symbol();var B$1,Ue$1;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Ue$1="openid-client/v6.8.8",B$1={"user-agent":Ue$1});var R$1=e=>se$1.get(e),se$1;function ce$1(e){if(e!==void 0)return ee$1(e);let t=new WeakMap;return (n,r,o,s)=>{let a;return (a=t.get(r))||(Ct$1(r.client_secret,'"metadata.client_secret"'),a=ee$1(r.client_secret),t.set(r,a)),a(n,r,o,s)}}function Ct$1(e,t){if(typeof e!="string")throw x$1(`${t} must be a string`,V$1);if(e.length===0)throw x$1(`${t} must not be empty`,ue$1)}function vt$1(){return Ae$1()}var S$1=O$1;var ue$1="ERR_INVALID_ARG_VALUE",V$1="ERR_INVALID_ARG_TYPE";function x$1(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var C$1=class C extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor);}};new TextDecoder;function f(e,t,n){return new C$1(e,{cause:t,code:n})}function ie$1(e){if(e instanceof TypeError||e instanceof C$1||e instanceof g$1||e instanceof I$2||e instanceof k$1)throw e;if(e instanceof D$1)switch(e.code){case ne$1:throw f("only requests to HTTPS are allowed",e,e.code);case re$1:throw f("only requests to HTTP or HTTPS are allowed",e,e.code);case $$1:throw f("unexpected HTTP response status code",e.cause,e.code);case te$1:throw f("unexpected response content-type",e.cause,e.code);case U$1:throw f("parsing error occured",e,e.code);case d$2:throw f("invalid response encountered",e,e.code);case E$1:throw f("unexpected JWT claim value encountered",e,e.code);case F$1:throw f("unexpected JSON attribute value encountered",e,e.code);case j$1:throw f("JWT timestamp claim value failed validation",e,e.code);default:throw f(e.message,e,e.code)}if(e instanceof T)throw f("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case "OperationError":throw f("runtime operation error",e,K$1);case "NotSupportedError":throw f("runtime unsupported operation",e,K$1);case "TimeoutError":throw f("operation timed out",e,"OAUTH_TIMEOUT");case "AbortError":throw f("operation aborted",e,"OAUTH_ABORT")}throw new C$1("something went wrong",{cause:e})}function Dt$1(e,t,n){return e.origin==="https://login.microsoftonline.com"&&(!n?.algorithm||n.algorithm==="oidc")?(t[He$1]=true,true):false}function It$1(e,t){return !!(e.hostname.endsWith(".b2clogin.com")&&(!t?.algorithm||t.algorithm==="oidc"))}async function Le$1(e,t,n,r,o){let s=await Ut$1(e,o),a=new v(s,t,n,r),u=R$1(a);if(o?.[S$1]&&(u.fetch=o[S$1]),o?.timeout!==void 0&&(u.timeout=o.timeout),o?.execute)for(let h of o.execute)h(a);return a}async function Ut$1(e,t){if(!(e instanceof URL))throw x$1('"server" must be an instance of URL',V$1);let n=!e.href.includes("/.well-known/"),r=t?.timeout??30,o=AbortSignal.timeout(r*1e3),s=await(n?ge(e,{algorithm:t?.algorithm,[O$1]:t?.[S$1],[L$1]:t?.execute?.includes(G$1),signal:o,headers:new Headers(B$1)}):(t?.[S$1]||fetch)((z$1(e,!t?.execute?.includes(G$1)),e.href),{headers:Object.fromEntries(new Headers({accept:"application/json",...B$1}).entries()),body:void 0,method:"GET",redirect:"manual",signal:o})).then(a=>Re$1(J$1,a)).catch(ie$1);return n&&new URL(s.issuer).href!==e.href&&(Dt$1(e,s,t)||It$1(e,t)||(()=>{throw new C$1("discovered metadata issuer does not match the expected issuer",{code:F$1,cause:{expected:e.href,body:s,attribute:"issuer"}})})()),s}function Lt$1(e){return {supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===true}}}}function Ht(e){Object.defineProperties(e,Lt$1(e));}var He$1=Symbol(),v=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw x$1('"clientId" must be a non-empty string',V$1);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&n!==r.client_id)throw x$1('"clientId" and "metadata.client_id" must be the same',ue$1);let s={...structuredClone(r),client_id:n};s[W$1]=r?.[W$1]??0,s[M$1]=r?.[M$1]??30;let a;o?a=o:typeof s.client_secret=="string"&&s.client_secret.length?a=ce$1(s.client_secret):a=vt$1();let u=Object.freeze(s),h=structuredClone(t);He$1 in t&&(h[ae$1]=({claims:{tid:p}})=>t.issuer.replace("{tenantid}",p));let c=Object.freeze(h);se$1||=new WeakMap,se$1.set(this,{__proto__:null,as:c,c:u,auth:a,tlsOnly:true,timeout:30,jwksCache:{}});}serverMetadata(){let t=structuredClone(R$1(this).as);return Ht(t),t}clientMetadata(){return structuredClone(R$1(this).c)}get timeout(){return R$1(this).timeout}set timeout(t){R$1(this).timeout=t;}get[S$1](){return R$1(this).fetch}set[S$1](t){R$1(this).fetch=t;}};Object.freeze(v.prototype);function Nt$1(e){let t;return e.expires_in!==void 0&&(t=Date.now()+e.expires_in*1e3),{expiresIn:{__proto__:null,value(){if(t){let n=Date.now();return t>n?Math.floor((t-n)/1e3):0}}},claims:{__proto__:null,value(){return Oe$1(e)}}}}function jt$1(e){Object.defineProperties(e,Nt$1(e));}function G$1(e){R$1(e).tlsOnly=false;}async function de$1(e,t,n){Jt(e),t=new URLSearchParams(t);let{as:r,c:o,auth:s,fetch:a,tlsOnly:u,timeout:h}=R$1(e),c=await ve$1(r,o,s,t,{[O$1]:a,[L$1]:!u,DPoP:n?.DPoP,headers:new Headers(B$1),signal:qt(h)}).catch(ie$1),p=De$1(r,o,c),m;try{m=await p;}catch(P){ie$1(P);}return jt$1(m),m}function Jt(e){if(!(e instanceof v))throw x$1('"config" must be an instance of Configuration',V$1);if(Object.getPrototypeOf(e)!==v.prototype)throw x$1("subclassing Configuration is not allowed",ue$1)}function qt(e){return e?AbortSignal.timeout(e*1e3):void 0}var w$1=class w extends Error{code;constructor(t,n){super(t,{cause:n}),this.name="OAuthClientCredentialsError",this.code="ERR_OAUTH";}};var zt$1=6e4,Kt=new Set(["localhost","127.0.0.1"]),je$1=e=>e.protocol==="http:"&&Kt.has(e.hostname),$t$1=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,Ft$1=e=>{try{return new URL(e)}catch{return}},he$1=e=>e?`OAuth token request failed: ${e}`:"OAuth token request failed",Je$1=class e{#e;constructor(t,n,r,o){if(t.protocol!=="https:"&&!je$1(t))throw new w$1("OAuth client credentials require an https service URL; http is only allowed for localhost and 127.0.0.1");this.#e={issuer:t,clientId:n,clientSecret:r,fetchImpl:o?.fetch,clock:o?.clock??(()=>Date.now()),cachedToken:void 0,configuration:void 0,flight:void 0,generation:0};}static fromServiceUrl(t,n,r){let o=Ft$1(t);if(!o||o.protocol!=="http:"&&o.protocol!=="https:")throw new w$1("OAuth client credentials require an absolute service URL");return new e(new URL(o.origin),n,r)}async getAccessToken(){let{cachedToken:t,clock:n}=this.#e;if(t!==void 0&&t.expiresAt-n()>zt$1)return t.accessToken;if(this.#e.flight)return this.#e.flight;let r=this.#e.generation,o=this.#t(r).finally(()=>{this.#e.flight===o&&(this.#e.flight=void 0);});return this.#e.flight=o,o}invalidate(){this.#e.cachedToken=void 0,this.#e.generation+=1,this.#e.flight=void 0;}async#t(t){let n=await this.#n(),r;try{r=await de$1(n);}catch(s){throw s instanceof TypeError||s instanceof w$1?s:s instanceof g$1?new w$1(he$1(s.error),s):new w$1(he$1(),s)}let o=r.access_token;if(typeof o!="string"||o.length===0)throw new w$1(he$1());if(this.#e.generation===t){let s=r.expires_in;this.#e.cachedToken=$t$1(s)?{accessToken:o,expiresAt:this.#e.clock()+s*1e3}:void 0;}return o}async#n(){if(this.#e.configuration)return this.#e.configuration;let t=this.#e.fetchImpl??globalThis.fetch;try{let n=await Le$1(this.#e.issuer,this.#e.clientId,this.#e.clientSecret,ce$1(this.#e.clientSecret),{algorithm:"oauth2",[S$1]:t,...je$1(this.#e.issuer)?{execute:[G$1]}:{}});return this.#e.configuration=n,n}catch(n){throw n instanceof TypeError?n:new w$1("OAuth authorization server discovery failed",n)}}},$n=({grantType:e,clientSecret:t})=>{if(e!=="client_credentials")throw new w$1("Only the client_credentials grant is supported");if(globalThis.window!==void 0&&t.length>0)throw new w$1("Client credentials authentication is not supported in the browser")},Fn=async(e,t)=>{let n=await t();return n.status!==401?n:(await n.body?.cancel().catch(()=>{}),e.invalidate(),t())};
5
5
 
6
- Jt.object({sessionId:Jt.string().uuid()});Jt.object({platformId:Jt.string(),sourceId:Jt.string(),isFullApi:Jt.boolean().optional().default(false),timeOffset:Jt.number().default(0)});var i=Jt.object({uuid:Jt.string(),name:Jt.string(),notificationTopic:Jt.string().optional(),eventTopic:Jt.string().optional()});Jt.object({sessionId:Jt.string(),orgId:Jt.string(),userId:Jt.string(),platformId:Jt.string(),sourceId:Jt.string(),groups:Jt.array(i),mqtt:Jt.object({sessionRootTopic:Jt.string(),userNotificationEventsTopic:Jt.string(),allNotificationEventsTopic:Jt.string().optional(),notificationsRootTopic:Jt.string(),eventsRootTopic:Jt.string(),lastWillTopic:Jt.string(),url:Jt.string(),token:Jt.string(),userNotificationTopic:Jt.string()}).optional()}).strict();var e=Jt.enum(["new","update","delete"]),o=Jt.object({correlationId:Jt.string().optional(),targets:Jt.object({groups:Jt.array(Jt.string()).default([]),users:Jt.array(Jt.string()).default([])}),ttlSeconds:Jt.number().optional(),notificationClass:Jt.string().default("interactive").optional(),payload:Jt.unknown()});Jt.object({sessionId:Jt.string().uuid(),timeOffset:Jt.number(),notification:o});Jt.object({sessionId:Jt.string().uuid(),timeOffset:Jt.number().optional().default(0),ttlSeconds:Jt.number().optional(),payload:Jt.unknown()});var l=Jt.object({notificationId:Jt.string().uuid(),category:Jt.string(),type:Jt.string(),sourceId:Jt.string(),platformId:Jt.string(),userId:Jt.string().uuid(),userName:Jt.string().optional(),payload:Jt.unknown().optional(),correlationId:Jt.string().optional()}),f=Jt.object({action:e,notificationId:Jt.string().uuid(),originatingSessionId:Jt.string().uuid(),correlationId:Jt.string().optional(),target:Jt.string(),targetType:Jt.enum(["user","group"]),payload:Jt.unknown(),txInstanceId:Jt.string().uuid()}),n=Jt.object({category:Jt.string(),type:Jt.string(),payload:Jt.unknown().optional()});Jt.object({sessionId:Jt.string().uuid(),timeOffset:Jt.number().optional().default(0),event:n,targets:Jt.object({groups:Jt.array(Jt.string()).default([]),users:Jt.array(Jt.string()).default([])}).optional()});Jt.object({userId:Jt.string().uuid(),platformId:Jt.string(),sourceId:Jt.string(),notificationId:Jt.string().uuid(),category:Jt.string(),type:Jt.string(),sessionId:Jt.string().uuid(),payload:Jt.unknown().optional(),timestamp:Jt.date(),cursor:Jt.string().base64(),correlationId:Jt.string().nullish()});
6
+ var d$1=Object.defineProperty;var e$1=(c,a)=>{for(var b in a)d$1(c,b,{get:a[b],enumerable:true});};
7
+
8
+ var g;(function(r){r.assertEqual=a=>{};function e(a){}r.assertIs=e;function t(a){throw new Error}r.assertNever=t,r.arrayToEnum=a=>{let n={};for(let i of a)n[i]=i;return n},r.getValidEnumValues=a=>{let n=r.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),i={};for(let o of n)i[o]=a[o];return r.objectValues(i)},r.objectValues=a=>r.objectKeys(a).map(function(n){return a[n]}),r.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{let n=[];for(let i in a)Object.prototype.hasOwnProperty.call(a,i)&&n.push(i);return n},r.find=(a,n)=>{for(let i of a)if(n(i))return i},r.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function s(a,n=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(n)}r.joinValues=s,r.jsonStringifyReplacer=(a,n)=>typeof n=="bigint"?n.toString():n;})(g||(g={}));var ve;(function(r){r.mergeShapes=(e,t)=>({...e,...t});})(ve||(ve={}));var u=g.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),R=r=>{switch(typeof r){case "undefined":return u.undefined;case "string":return u.string;case "number":return Number.isNaN(r)?u.nan:u.number;case "boolean":return u.boolean;case "function":return u.function;case "bigint":return u.bigint;case "symbol":return u.symbol;case "object":return Array.isArray(r)?u.array:r===null?u.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?u.promise:typeof Map<"u"&&r instanceof Map?u.map:typeof Set<"u"&&r instanceof Set?u.set:typeof Date<"u"&&r instanceof Date?u.date:u.object;default:return u.unknown}};var c$1=g.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"]),Me=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),b=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s];},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s];};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(n){return n.message},s={_errors:[]},a=n=>{for(let i of n.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else {let o=s,f=0;for(;f<i.path.length;){let l=i.path[f];f===i.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(t(i))):o[l]=o[l]||{_errors:[]},o=o[l],f++;}}};return a(this),s}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,g.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},s=[];for(let a of this.issues)if(a.path.length>0){let n=a.path[0];t[n]=t[n]||[],t[n].push(e(a));}else s.push(e(a));return {formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};b.create=r=>new b(r);var Ve=(r,e)=>{let t;switch(r.code){case c$1.invalid_type:r.received===u.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case c$1.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,g.jsonStringifyReplacer)}`;break;case c$1.unrecognized_keys:t=`Unrecognized key(s) in object: ${g.joinValues(r.keys,", ")}`;break;case c$1.invalid_union:t="Invalid input";break;case c$1.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${g.joinValues(r.options)}`;break;case c$1.invalid_enum_value:t=`Invalid enum value. Expected ${g.joinValues(r.options)}, received '${r.received}'`;break;case c$1.invalid_arguments:t="Invalid function arguments";break;case c$1.invalid_return_type:t="Invalid function return type";break;case c$1.invalid_date:t="Invalid date";break;case c$1.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:g.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case c$1.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case c$1.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case c$1.custom:t="Invalid input";break;case c$1.invalid_intersection_types:t="Intersection results could not be merged";break;case c$1.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case c$1.not_finite:t="Number must be finite";break;default:t=e.defaultError,g.assertNever(r);}return {message:t}},I$1=Ve;var we=I$1;function Pe(r){we=r;}function re(){return we}var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message;})(h||(h={}));var ue=r=>{let{data:e,path:t,errorMaps:s,issueData:a}=r,n=[...t,...a.path||[]],i={...a,path:n};if(a.message!==void 0)return {...a,path:n,message:a.message};let o="",f=s.filter(l=>!!l).slice().reverse();for(let l of f)o=l(i,{data:e,defaultError:o}).message;return {...a,path:n,message:o}},ze=[];function d(r,e){let t=re(),s=ue({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===I$1?void 0:I$1].filter(a=>!!a)});r.common.issues.push(s);}var x=class r{constructor(){this.value="valid";}dirty(){this.value==="valid"&&(this.value="dirty");}abort(){this.value!=="aborted"&&(this.value="aborted");}static mergeArray(e,t){let s=[];for(let a of t){if(a.status==="aborted")return p$1;a.status==="dirty"&&e.dirty(),s.push(a.value);}return {status:e.value,value:s}}static async mergeObjectAsync(e,t){let s=[];for(let a of t){let n=await a.key,i=await a.value;s.push({key:n,value:i});}return r.mergeObjectSync(e,s)}static mergeObjectSync(e,t){let s={};for(let a of t){let{key:n,value:i}=a;if(n.status==="aborted"||i.status==="aborted")return p$1;n.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),n.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(s[n.value]=i.value);}return {status:e.value,value:s}}},p$1=Object.freeze({status:"aborted"}),D=r=>({status:"dirty",value:r}),k=r=>({status:"valid",value:r}),he=r=>r.status==="aborted",pe=r=>r.status==="dirty",M=r=>r.status==="valid",se=r=>typeof Promise<"u"&&r instanceof Promise;var O=class{constructor(e,t,s,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=a;}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}},Te=(r,e)=>{if(M(e))return {success:true,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return {success:false,get error(){if(this._error)return this._error;let t=new b(r.common.issues);return this._error=t,this._error}}};function y(r){if(!r)return {};let{errorMap:e,invalid_type_error:t,required_error:s,description:a}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(i,o)=>{let{message:f}=r;return i.code==="invalid_enum_value"?{message:f??o.defaultError}:typeof o.data>"u"?{message:f??s??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:f??t??o.defaultError}},description:a}}var _=class{get description(){return this._def.description}_getType(e){return R(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return {status:new x,ctx:{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(se(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 s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){let s={common:{issues:[],async:t?.async??false,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},a=this._parseSync({data:e,path:s.path,parent:s});return Te(s,a)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:t});return M(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=true),t.common={issues:[],async:true};}return this._parseAsync({data:e,path:[],parent:t}).then(s=>M(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:true},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},a=this._parse({data:e,path:s.path,parent:s}),n=await(se(a)?a:Promise.resolve(a));return Te(s,n)}refine(e,t){let s=a=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(a):t;return this._refinement((a,n)=>{let i=e(a),o=()=>n.addIssue({code:c$1.custom,...s(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(f=>f?true:(o(),false)):i?true:(o(),false)})}refinement(e,t){return this._refinement((s,a)=>e(s)?true:(a.addIssue(typeof t=="function"?t(s,a):t),false))}_refinement(e){return new S({schema:this,typeName:m.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 j.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $.create(this)}promise(){return z.create(this,this._def)}or(e){return J.create([this,e],this._def)}and(e){return Y.create(this,e,this._def)}transform(e){return new S({...y(this._def),schema:this,typeName:m.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new K({...y(this._def),innerType:this,defaultValue:t,typeName:m.ZodDefault})}brand(){return new le({typeName:m.ZodBranded,type:this,...y(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ee({...y(this._def),innerType:this,catchValue:t,typeName:m.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return fe.create(this,e)}readonly(){return te.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},De=/^c[^\s-]{8,}$/i,Le=/^[0-9a-z]+$/,Ue=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fe=/^[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,Be=/^[a-z0-9_-]{21}$/i,We=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,qe=/^[-+]?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)?)??$/,Je=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ye="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",xe,He=/^(?:(?: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])$/,Ge=/^(?:(?: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])$/,Qe=/^(([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]))$/,Xe=/^(([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])$/,Ke=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,et=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Oe="((\\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])))",tt=new RegExp(`^${Oe}$`);function Se(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return `([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function rt(r){return new RegExp(`^${Se(r)}$`)}function Ae(r){let e=`${Oe}T${Se(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function st(r,e){return !!((e==="v4"||!e)&&He.test(r)||(e==="v6"||!e)&&Qe.test(r))}function at(r,e){if(!We.test(r))return false;try{let[t]=r.split(".");if(!t)return !1;let s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),a=JSON.parse(atob(s));return !(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return false}}function nt(r,e){return !!((e==="v4"||!e)&&Ge.test(r)||(e==="v6"||!e)&&Xe.test(r))}var V=class r extends _{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==u.string){let n=this._getOrReturnCtx(e);return d(n,{code:c$1.invalid_type,expected:u.string,received:n.parsedType}),p$1}let s=new x,a;for(let n of this._def.checks)if(n.kind==="min")e.data.length<n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.too_small,minimum:n.value,type:"string",inclusive:true,exact:false,message:n.message}),s.dirty());else if(n.kind==="max")e.data.length>n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.too_big,maximum:n.value,type:"string",inclusive:true,exact:false,message:n.message}),s.dirty());else if(n.kind==="length"){let i=e.data.length>n.value,o=e.data.length<n.value;(i||o)&&(a=this._getOrReturnCtx(e,a),i?d(a,{code:c$1.too_big,maximum:n.value,type:"string",inclusive:true,exact:true,message:n.message}):o&&d(a,{code:c$1.too_small,minimum:n.value,type:"string",inclusive:true,exact:true,message:n.message}),s.dirty());}else if(n.kind==="email")Je.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"email",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="emoji")xe||(xe=new RegExp(Ye,"u")),xe.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"emoji",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="uuid")Fe.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"uuid",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="nanoid")Be.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"nanoid",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="cuid")De.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"cuid",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="cuid2")Le.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"cuid2",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="ulid")Ue.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"ulid",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="url")try{new URL(e.data);}catch{a=this._getOrReturnCtx(e,a),d(a,{validation:"url",code:c$1.invalid_string,message:n.message}),s.dirty();}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"regex",code:c$1.invalid_string,message:n.message}),s.dirty())):n.kind==="trim"?e.data=e.data.trim():n.kind==="includes"?e.data.includes(n.value,n.position)||(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),s.dirty()):n.kind==="toLowerCase"?e.data=e.data.toLowerCase():n.kind==="toUpperCase"?e.data=e.data.toUpperCase():n.kind==="startsWith"?e.data.startsWith(n.value)||(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.invalid_string,validation:{startsWith:n.value},message:n.message}),s.dirty()):n.kind==="endsWith"?e.data.endsWith(n.value)||(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.invalid_string,validation:{endsWith:n.value},message:n.message}),s.dirty()):n.kind==="datetime"?Ae(n).test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.invalid_string,validation:"datetime",message:n.message}),s.dirty()):n.kind==="date"?tt.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.invalid_string,validation:"date",message:n.message}),s.dirty()):n.kind==="time"?rt(n).test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.invalid_string,validation:"time",message:n.message}),s.dirty()):n.kind==="duration"?qe.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"duration",code:c$1.invalid_string,message:n.message}),s.dirty()):n.kind==="ip"?st(e.data,n.version)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"ip",code:c$1.invalid_string,message:n.message}),s.dirty()):n.kind==="jwt"?at(e.data,n.alg)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"jwt",code:c$1.invalid_string,message:n.message}),s.dirty()):n.kind==="cidr"?nt(e.data,n.version)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"cidr",code:c$1.invalid_string,message:n.message}),s.dirty()):n.kind==="base64"?Ke.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"base64",code:c$1.invalid_string,message:n.message}),s.dirty()):n.kind==="base64url"?et.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"base64url",code:c$1.invalid_string,message:n.message}),s.dirty()):g.assertNever(n);return {status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(a=>e.test(a),{validation:t,code:c$1.invalid_string,...h.errToObj(s)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:false,local:false,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??false,local:e?.local??false,...h.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,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...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}};V.create=r=>new V({checks:[],typeName:m.ZodString,coerce:r?.coerce??false,...y(r)});function it(r,e){let t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,a=t>s?t:s,n=Number.parseInt(r.toFixed(a).replace(".","")),i=Number.parseInt(e.toFixed(a).replace(".",""));return n%i/10**a}var L=class r extends _{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)!==u.number){let n=this._getOrReturnCtx(e);return d(n,{code:c$1.invalid_type,expected:u.number,received:n.parsedType}),p$1}let s,a=new x;for(let n of this._def.checks)n.kind==="int"?g.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.invalid_type,expected:"integer",received:"float",message:n.message}),a.dirty()):n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:false,message:n.message}),a.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:false,message:n.message}),a.dirty()):n.kind==="multipleOf"?it(e.data,n.value)!==0&&(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.not_multiple_of,multipleOf:n.value,message:n.message}),a.dirty()):n.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.not_finite,message:n.message}),a.dirty()):g.assertNever(n);return {status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,true,h.toString(t))}gt(e,t){return this.setLimit("min",e,false,h.toString(t))}lte(e,t){return this.setLimit("max",e,true,h.toString(t))}lt(e,t){return this.setLimit("max",e,false,h.toString(t))}setLimit(e,t,s,a){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(a)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:false,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:false,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:true,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:true,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:true,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:true,value:Number.MAX_SAFE_INTEGER,message:h.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"&&g.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return true;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);}return Number.isFinite(t)&&Number.isFinite(e)}};L.create=r=>new L({checks:[],typeName:m.ZodNumber,coerce:r?.coerce||false,...y(r)});var U=class r extends _{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)!==u.bigint)return this._getInvalidInput(e);let s,a=new x;for(let n of this._def.checks)n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),a.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),a.dirty()):n.kind==="multipleOf"?e.data%n.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.not_multiple_of,multipleOf:n.value,message:n.message}),a.dirty()):g.assertNever(n);return {status:a.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return d(t,{code:c$1.invalid_type,expected:u.bigint,received:t.parsedType}),p$1}gte(e,t){return this.setLimit("min",e,true,h.toString(t))}gt(e,t){return this.setLimit("min",e,false,h.toString(t))}lte(e,t){return this.setLimit("max",e,true,h.toString(t))}lt(e,t){return this.setLimit("max",e,false,h.toString(t))}setLimit(e,t,s,a){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(a)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:false,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:false,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:true,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:true,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.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}};U.create=r=>new U({checks:[],typeName:m.ZodBigInt,coerce:r?.coerce??false,...y(r)});var F=class extends _{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==u.boolean){let s=this._getOrReturnCtx(e);return d(s,{code:c$1.invalid_type,expected:u.boolean,received:s.parsedType}),p$1}return k(e.data)}};F.create=r=>new F({typeName:m.ZodBoolean,coerce:r?.coerce||false,...y(r)});var B=class r extends _{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==u.date){let n=this._getOrReturnCtx(e);return d(n,{code:c$1.invalid_type,expected:u.date,received:n.parsedType}),p$1}if(Number.isNaN(e.data.getTime())){let n=this._getOrReturnCtx(e);return d(n,{code:c$1.invalid_date}),p$1}let s=new x,a;for(let n of this._def.checks)n.kind==="min"?e.data.getTime()<n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.too_small,message:n.message,inclusive:true,exact:false,minimum:n.value,type:"date"}),s.dirty()):n.kind==="max"?e.data.getTime()>n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.too_big,message:n.message,inclusive:true,exact:false,maximum:n.value,type:"date"}),s.dirty()):g.assertNever(n);return {status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.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}};B.create=r=>new B({checks:[],coerce:r?.coerce||false,typeName:m.ZodDate,...y(r)});var ne=class extends _{_parse(e){if(this._getType(e)!==u.symbol){let s=this._getOrReturnCtx(e);return d(s,{code:c$1.invalid_type,expected:u.symbol,received:s.parsedType}),p$1}return k(e.data)}};ne.create=r=>new ne({typeName:m.ZodSymbol,...y(r)});var W=class extends _{_parse(e){if(this._getType(e)!==u.undefined){let s=this._getOrReturnCtx(e);return d(s,{code:c$1.invalid_type,expected:u.undefined,received:s.parsedType}),p$1}return k(e.data)}};W.create=r=>new W({typeName:m.ZodUndefined,...y(r)});var q=class extends _{_parse(e){if(this._getType(e)!==u.null){let s=this._getOrReturnCtx(e);return d(s,{code:c$1.invalid_type,expected:u.null,received:s.parsedType}),p$1}return k(e.data)}};q.create=r=>new q({typeName:m.ZodNull,...y(r)});var P=class extends _{constructor(){super(...arguments),this._any=true;}_parse(e){return k(e.data)}};P.create=r=>new P({typeName:m.ZodAny,...y(r)});var Z=class extends _{constructor(){super(...arguments),this._unknown=true;}_parse(e){return k(e.data)}};Z.create=r=>new Z({typeName:m.ZodUnknown,...y(r)});var A=class extends _{_parse(e){let t=this._getOrReturnCtx(e);return d(t,{code:c$1.invalid_type,expected:u.never,received:t.parsedType}),p$1}};A.create=r=>new A({typeName:m.ZodNever,...y(r)});var ie=class extends _{_parse(e){if(this._getType(e)!==u.undefined){let s=this._getOrReturnCtx(e);return d(s,{code:c$1.invalid_type,expected:u.void,received:s.parsedType}),p$1}return k(e.data)}};ie.create=r=>new ie({typeName:m.ZodVoid,...y(r)});var $=class r extends _{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==u.array)return d(t,{code:c$1.invalid_type,expected:u.array,received:t.parsedType}),p$1;if(a.exactLength!==null){let i=t.data.length>a.exactLength.value,o=t.data.length<a.exactLength.value;(i||o)&&(d(t,{code:i?c$1.too_big:c$1.too_small,minimum:o?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:true,exact:true,message:a.exactLength.message}),s.dirty());}if(a.minLength!==null&&t.data.length<a.minLength.value&&(d(t,{code:c$1.too_small,minimum:a.minLength.value,type:"array",inclusive:true,exact:false,message:a.minLength.message}),s.dirty()),a.maxLength!==null&&t.data.length>a.maxLength.value&&(d(t,{code:c$1.too_big,maximum:a.maxLength.value,type:"array",inclusive:true,exact:false,message:a.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>a.type._parseAsync(new O(t,i,t.path,o)))).then(i=>x.mergeArray(s,i));let n=[...t.data].map((i,o)=>a.type._parseSync(new O(t,i,t.path,o)));return x.mergeArray(s,n)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};$.create=(r,e)=>new $({type:r,minLength:null,maxLength:null,exactLength:null,typeName:m.ZodArray,...y(e)});function ae(r){if(r instanceof w){let e={};for(let t in r.shape){let s=r.shape[t];e[t]=C.create(ae(s));}return new w({...r._def,shape:()=>e})}else return r instanceof $?new $({...r._def,type:ae(r.element)}):r instanceof C?C.create(ae(r.unwrap())):r instanceof j?j.create(ae(r.unwrap())):r instanceof N$1?N$1.create(r.items.map(e=>ae(e))):r}var w=class r extends _{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=g.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==u.object){let l=this._getOrReturnCtx(e);return d(l,{code:c$1.invalid_type,expected:u.object,received:l.parsedType}),p$1}let{status:s,ctx:a}=this._processInputParams(e),{shape:n,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof A&&this._def.unknownKeys==="strip"))for(let l in a.data)i.includes(l)||o.push(l);let f=[];for(let l of i){let v=n[l],T=a.data[l];f.push({key:{status:"valid",value:l},value:v._parse(new O(a,T,a.path,l)),alwaysSet:l in a.data});}if(this._def.catchall instanceof A){let l=this._def.unknownKeys;if(l==="passthrough")for(let v of o)f.push({key:{status:"valid",value:v},value:{status:"valid",value:a.data[v]}});else if(l==="strict")o.length>0&&(d(a,{code:c$1.unrecognized_keys,keys:o}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else {let l=this._def.catchall;for(let v of o){let T=a.data[v];f.push({key:{status:"valid",value:v},value:l._parse(new O(a,T,a.path,v)),alwaysSet:v in a.data});}}return a.common.async?Promise.resolve().then(async()=>{let l=[];for(let v of f){let T=await v.key,be=await v.value;l.push({key:T,value:be,alwaysSet:v.alwaysSet});}return l}).then(l=>x.mergeObjectSync(s,l)):x.mergeObjectSync(s,f)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{let a=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:m.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let s of g.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let s of g.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}deepPartial(){return ae(this)}partial(e){let t={};for(let s of g.objectKeys(this.shape)){let a=this.shape[s];e&&!e[s]?t[s]=a:t[s]=a.optional();}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let s of g.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else {let n=this.shape[s];for(;n instanceof C;)n=n._def.innerType;t[s]=n;}return new r({...this._def,shape:()=>t})}keyof(){return Re(g.objectKeys(this.shape))}};w.create=(r,e)=>new w({shape:()=>r,unknownKeys:"strip",catchall:A.create(),typeName:m.ZodObject,...y(e)});w.strictCreate=(r,e)=>new w({shape:()=>r,unknownKeys:"strict",catchall:A.create(),typeName:m.ZodObject,...y(e)});w.lazycreate=(r,e)=>new w({shape:r,unknownKeys:"strip",catchall:A.create(),typeName:m.ZodObject,...y(e)});var J=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function a(n){for(let o of n)if(o.result.status==="valid")return o.result;for(let o of n)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=n.map(o=>new b(o.ctx.common.issues));return d(t,{code:c$1.invalid_union,unionErrors:i}),p$1}if(t.common.async)return Promise.all(s.map(async n=>{let i={...t,common:{...t.common,issues:[]},parent:null};return {result:await n._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(a);{let n,i=[];for(let f of s){let l={...t,common:{...t.common,issues:[]},parent:null},v=f._parseSync({data:t.data,path:t.path,parent:l});if(v.status==="valid")return v;v.status==="dirty"&&!n&&(n={result:v,ctx:l}),l.common.issues.length&&i.push(l.common.issues);}if(n)return t.common.issues.push(...n.ctx.common.issues),n.result;let o=i.map(f=>new b(f));return d(t,{code:c$1.invalid_union,unionErrors:o}),p$1}}get options(){return this._def.options}};J.create=(r,e)=>new J({options:r,typeName:m.ZodUnion,...y(e)});var E=r=>r instanceof H?E(r.schema):r instanceof S?E(r.innerType()):r instanceof G?[r.value]:r instanceof Q?r.options:r instanceof X?g.objectValues(r.enum):r instanceof K?E(r._def.innerType):r instanceof W?[void 0]:r instanceof q?[null]:r instanceof C?[void 0,...E(r.unwrap())]:r instanceof j?[null,...E(r.unwrap())]:r instanceof le||r instanceof te?E(r.unwrap()):r instanceof ee?E(r._def.innerType):[],me=class r extends _{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.object)return d(t,{code:c$1.invalid_type,expected:u.object,received:t.parsedType}),p$1;let s=this.discriminator,a=t.data[s],n=this.optionsMap.get(a);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(d(t,{code:c$1.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),p$1)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){let a=new Map;for(let n of t){let i=E(n.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(a.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);a.set(o,n);}}return new r({typeName:m.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...y(s)})}};function ke(r,e){let t=R(r),s=R(e);if(r===e)return {valid:true,data:r};if(t===u.object&&s===u.object){let a=g.objectKeys(e),n=g.objectKeys(r).filter(o=>a.indexOf(o)!==-1),i={...r,...e};for(let o of n){let f=ke(r[o],e[o]);if(!f.valid)return {valid:false};i[o]=f.data;}return {valid:true,data:i}}else if(t===u.array&&s===u.array){if(r.length!==e.length)return {valid:false};let a=[];for(let n=0;n<r.length;n++){let i=r[n],o=e[n],f=ke(i,o);if(!f.valid)return {valid:false};a.push(f.data);}return {valid:true,data:a}}else return t===u.date&&s===u.date&&+r==+e?{valid:true,data:r}:{valid:false}}var Y=class extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),a=(n,i)=>{if(he(n)||he(i))return p$1;let o=ke(n.value,i.value);return o.valid?((pe(n)||pe(i))&&t.dirty(),{status:t.value,value:o.data}):(d(s,{code:c$1.invalid_intersection_types}),p$1)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([n,i])=>a(n,i)):a(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};Y.create=(r,e,t)=>new Y({left:r,right:e,typeName:m.ZodIntersection,...y(t)});var N$1=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.array)return d(s,{code:c$1.invalid_type,expected:u.array,received:s.parsedType}),p$1;if(s.data.length<this._def.items.length)return d(s,{code:c$1.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"}),p$1;!this._def.rest&&s.data.length>this._def.items.length&&(d(s,{code:c$1.too_big,maximum:this._def.items.length,inclusive:true,exact:false,type:"array"}),t.dirty());let n=[...s.data].map((i,o)=>{let f=this._def.items[o]||this._def.rest;return f?f._parse(new O(s,i,s.path,o)):null}).filter(i=>!!i);return s.common.async?Promise.all(n).then(i=>x.mergeArray(t,i)):x.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};N$1.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new N$1({items:r,typeName:m.ZodTuple,rest:null,...y(e)})};var ye=class r extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.object)return d(s,{code:c$1.invalid_type,expected:u.object,received:s.parsedType}),p$1;let a=[],n=this._def.keyType,i=this._def.valueType;for(let o in s.data)a.push({key:n._parse(new O(s,o,s.path,o)),value:i._parse(new O(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?x.mergeObjectAsync(t,a):x.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof _?new r({keyType:e,valueType:t,typeName:m.ZodRecord,...y(s)}):new r({keyType:V.create(),valueType:e,typeName:m.ZodRecord,...y(t)})}},oe=class extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.map)return d(s,{code:c$1.invalid_type,expected:u.map,received:s.parsedType}),p$1;let a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map(([o,f],l)=>({key:a._parse(new O(s,o,s.path,[l,"key"])),value:n._parse(new O(s,f,s.path,[l,"value"]))}));if(s.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let f of i){let l=await f.key,v=await f.value;if(l.status==="aborted"||v.status==="aborted")return p$1;(l.status==="dirty"||v.status==="dirty")&&t.dirty(),o.set(l.value,v.value);}return {status:t.value,value:o}})}else {let o=new Map;for(let f of i){let l=f.key,v=f.value;if(l.status==="aborted"||v.status==="aborted")return p$1;(l.status==="dirty"||v.status==="dirty")&&t.dirty(),o.set(l.value,v.value);}return {status:t.value,value:o}}}};oe.create=(r,e,t)=>new oe({valueType:e,keyType:r,typeName:m.ZodMap,...y(t)});var ce=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.set)return d(s,{code:c$1.invalid_type,expected:u.set,received:s.parsedType}),p$1;let a=this._def;a.minSize!==null&&s.data.size<a.minSize.value&&(d(s,{code:c$1.too_small,minimum:a.minSize.value,type:"set",inclusive:true,exact:false,message:a.minSize.message}),t.dirty()),a.maxSize!==null&&s.data.size>a.maxSize.value&&(d(s,{code:c$1.too_big,maximum:a.maxSize.value,type:"set",inclusive:true,exact:false,message:a.maxSize.message}),t.dirty());let n=this._def.valueType;function i(f){let l=new Set;for(let v of f){if(v.status==="aborted")return p$1;v.status==="dirty"&&t.dirty(),l.add(v.value);}return {status:t.value,value:l}}let o=[...s.data.values()].map((f,l)=>n._parse(new O(s,f,s.path,l)));return s.common.async?Promise.all(o).then(f=>i(f)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ce.create=(r,e)=>new ce({valueType:r,minSize:null,maxSize:null,typeName:m.ZodSet,...y(e)});var _e=class r extends _{constructor(){super(...arguments),this.validate=this.implement;}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.function)return d(t,{code:c$1.invalid_type,expected:u.function,received:t.parsedType}),p$1;function s(o,f){return ue({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,re(),I$1].filter(l=>!!l),issueData:{code:c$1.invalid_arguments,argumentsError:f}})}function a(o,f){return ue({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,re(),I$1].filter(l=>!!l),issueData:{code:c$1.invalid_return_type,returnTypeError:f}})}let n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof z){let o=this;return k(async function(...f){let l=new b([]),v=await o._def.args.parseAsync(f,n).catch(ge=>{throw l.addIssue(s(f,ge)),l}),T=await Reflect.apply(i,this,v);return await o._def.returns._def.type.parseAsync(T,n).catch(ge=>{throw l.addIssue(a(T,ge)),l})})}else {let o=this;return k(function(...f){let l=o._def.args.safeParse(f,n);if(!l.success)throw new b([s(f,l.error)]);let v=Reflect.apply(i,this,l.data),T=o._def.returns.safeParse(v,n);if(!T.success)throw new b([a(v,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:N$1.create(e).rest(Z.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new r({args:e||N$1.create([]).rest(Z.create()),returns:t||Z.create(),typeName:m.ZodFunction,...y(s)})}},H=class extends _{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})}};H.create=(r,e)=>new H({getter:r,typeName:m.ZodLazy,...y(e)});var G=class extends _{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return d(t,{received:t.data,code:c$1.invalid_literal,expected:this._def.value}),p$1}return {status:"valid",value:e.data}}get value(){return this._def.value}};G.create=(r,e)=>new G({value:r,typeName:m.ZodLiteral,...y(e)});function Re(r,e){return new Q({values:r,typeName:m.ZodEnum,...y(e)})}var Q=class r extends _{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),s=this._def.values;return d(t,{expected:g.joinValues(s),received:t.parsedType,code:c$1.invalid_type}),p$1}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return d(t,{received:t.data,code:c$1.invalid_enum_value,options:s}),p$1}return k(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 r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}};Q.create=Re;var X=class extends _{_parse(e){let t=g.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==u.string&&s.parsedType!==u.number){let a=g.objectValues(t);return d(s,{expected:g.joinValues(a),received:s.parsedType,code:c$1.invalid_type}),p$1}if(this._cache||(this._cache=new Set(g.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let a=g.objectValues(t);return d(s,{received:s.data,code:c$1.invalid_enum_value,options:a}),p$1}return k(e.data)}get enum(){return this._def.values}};X.create=(r,e)=>new X({values:r,typeName:m.ZodNativeEnum,...y(e)});var z=class extends _{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.promise&&t.common.async===false)return d(t,{code:c$1.invalid_type,expected:u.promise,received:t.parsedType}),p$1;let s=t.parsedType===u.promise?t.data:Promise.resolve(t.data);return k(s.then(a=>this._def.type.parseAsync(a,{path:t.path,errorMap:t.common.contextualErrorMap})))}};z.create=(r,e)=>new z({type:r,typeName:m.ZodPromise,...y(e)});var S=class extends _{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===m.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),a=this._def.effect||null,n={addIssue:i=>{d(s,i),i.fatal?t.abort():t.dirty();},get path(){return s.path}};if(n.addIssue=n.addIssue.bind(n),a.type==="preprocess"){let i=a.transform(s.data,n);if(s.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return p$1;let f=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return f.status==="aborted"?p$1:f.status==="dirty"?D(f.value):t.value==="dirty"?D(f.value):f});{if(t.value==="aborted")return p$1;let o=this._def.schema._parseSync({data:i,path:s.path,parent:s});return o.status==="aborted"?p$1:o.status==="dirty"?D(o.value):t.value==="dirty"?D(o.value):o}}if(a.type==="refinement"){let i=o=>{let f=a.refinement(o,n);if(s.common.async)return Promise.resolve(f);if(f instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===false){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?p$1:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?p$1:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(a.type==="transform")if(s.common.async===false){let i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!M(i))return p$1;let o=a.transform(i.value,n);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:s.data,path:s.path,parent:s}).then(i=>M(i)?Promise.resolve(a.transform(i.value,n)).then(o=>({status:t.value,value:o})):p$1);g.assertNever(a);}};S.create=(r,e,t)=>new S({schema:r,typeName:m.ZodEffects,effect:e,...y(t)});S.createWithPreprocess=(r,e,t)=>new S({schema:e,effect:{type:"preprocess",transform:r},typeName:m.ZodEffects,...y(t)});var C=class extends _{_parse(e){return this._getType(e)===u.undefined?k(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};C.create=(r,e)=>new C({innerType:r,typeName:m.ZodOptional,...y(e)});var j=class extends _{_parse(e){return this._getType(e)===u.null?k(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};j.create=(r,e)=>new j({innerType:r,typeName:m.ZodNullable,...y(e)});var K=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===u.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};K.create=(r,e)=>new K({innerType:r,typeName:m.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...y(e)});var ee=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return se(a)?a.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new b(s.common.issues)},input:s.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new b(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ee.create=(r,e)=>new ee({innerType:r,typeName:m.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...y(e)});var de=class extends _{_parse(e){if(this._getType(e)!==u.nan){let s=this._getOrReturnCtx(e);return d(s,{code:c$1.invalid_type,expected:u.nan,received:s.parsedType}),p$1}return {status:"valid",value:e.data}}};de.create=r=>new de({typeName:m.ZodNaN,...y(r)});var ot=Symbol("zod_brand"),le=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},fe=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return (async()=>{let n=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?p$1:n.status==="dirty"?(t.dirty(),D(n.value)):this._def.out._parseAsync({data:n.value,path:s.path,parent:s})})();{let a=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?p$1:a.status==="dirty"?(t.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:s.path,parent:s})}}static create(e,t){return new r({in:e,out:t,typeName:m.ZodPipeline})}},te=class extends _{_parse(e){let t=this._def.innerType._parse(e),s=a=>(M(a)&&(a.value=Object.freeze(a.value)),a);return se(t)?t.then(a=>s(a)):s(t)}unwrap(){return this._def.innerType}};te.create=(r,e)=>new te({innerType:r,typeName:m.ZodReadonly,...y(e)});function Ce(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Ne(r,e={},t){return r?P.create().superRefine((s,a)=>{let n=r(s);if(n instanceof Promise)return n.then(i=>{if(!i){let o=Ce(e,s),f=o.fatal??t??true;a.addIssue({code:"custom",...o,fatal:f});}});if(!n){let i=Ce(e,s),o=i.fatal??t??true;a.addIssue({code:"custom",...i,fatal:o});}}):P.create()}var ct={object:w.lazycreate},m;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly";})(m||(m={}));var dt=(r,e={message:`Input not instance of ${r.name}`})=>Ne(t=>t instanceof r,e),je=V.create,Ie=L.create,ut=de.create,lt=U.create,Ee=F.create,ft=B.create,ht=ne.create,pt=W.create,mt=q.create,yt=P.create,_t=Z.create,gt=A.create,vt=ie.create,xt=$.create,kt=w.create,bt=w.strictCreate,wt=J.create,Tt=me.create,Ct=Y.create,Ot=N$1.create,St=ye.create,At=oe.create,Rt=ce.create,Nt=_e.create,jt=H.create,It=G.create,Et=Q.create,Zt=X.create,$t=z.create,Mt=S.create,Vt=C.create,Pt=j.create,zt=S.createWithPreprocess,Dt=fe.create,Lt=()=>je().optional(),Ut=()=>Ie().optional(),Ft=()=>Ee().optional(),Bt={string:(r=>V.create({...r,coerce:true})),number:(r=>L.create({...r,coerce:true})),boolean:(r=>F.create({...r,coerce:true})),bigint:(r=>U.create({...r,coerce:true})),date:(r=>B.create({...r,coerce:true}))};var Wt=p$1;var Ze={};e$1(Ze,{BRAND:()=>ot,DIRTY:()=>D,EMPTY_PATH:()=>ze,INVALID:()=>p$1,NEVER:()=>Wt,OK:()=>k,ParseStatus:()=>x,Schema:()=>_,ZodAny:()=>P,ZodArray:()=>$,ZodBigInt:()=>U,ZodBoolean:()=>F,ZodBranded:()=>le,ZodCatch:()=>ee,ZodDate:()=>B,ZodDefault:()=>K,ZodDiscriminatedUnion:()=>me,ZodEffects:()=>S,ZodEnum:()=>Q,ZodError:()=>b,ZodFirstPartyTypeKind:()=>m,ZodFunction:()=>_e,ZodIntersection:()=>Y,ZodIssueCode:()=>c$1,ZodLazy:()=>H,ZodLiteral:()=>G,ZodMap:()=>oe,ZodNaN:()=>de,ZodNativeEnum:()=>X,ZodNever:()=>A,ZodNull:()=>q,ZodNullable:()=>j,ZodNumber:()=>L,ZodObject:()=>w,ZodOptional:()=>C,ZodParsedType:()=>u,ZodPipeline:()=>fe,ZodPromise:()=>z,ZodReadonly:()=>te,ZodRecord:()=>ye,ZodSchema:()=>_,ZodSet:()=>ce,ZodString:()=>V,ZodSymbol:()=>ne,ZodTransformer:()=>S,ZodTuple:()=>N$1,ZodType:()=>_,ZodUndefined:()=>W,ZodUnion:()=>J,ZodUnknown:()=>Z,ZodVoid:()=>ie,addIssueToContext:()=>d,any:()=>yt,array:()=>xt,bigint:()=>lt,boolean:()=>Ee,coerce:()=>Bt,custom:()=>Ne,date:()=>ft,datetimeRegex:()=>Ae,defaultErrorMap:()=>I$1,discriminatedUnion:()=>Tt,effect:()=>Mt,enum:()=>Et,function:()=>Nt,getErrorMap:()=>re,getParsedType:()=>R,instanceof:()=>dt,intersection:()=>Ct,isAborted:()=>he,isAsync:()=>se,isDirty:()=>pe,isValid:()=>M,late:()=>ct,lazy:()=>jt,literal:()=>It,makeIssue:()=>ue,map:()=>At,nan:()=>ut,nativeEnum:()=>Zt,never:()=>gt,null:()=>mt,nullable:()=>Pt,number:()=>Ie,object:()=>kt,objectUtil:()=>ve,oboolean:()=>Ft,onumber:()=>Ut,optional:()=>Vt,ostring:()=>Lt,pipeline:()=>Dt,preprocess:()=>zt,promise:()=>$t,quotelessJson:()=>Me,record:()=>St,set:()=>Rt,setErrorMap:()=>Pe,strictObject:()=>bt,string:()=>je,symbol:()=>ht,transformer:()=>Mt,tuple:()=>Ot,undefined:()=>pt,union:()=>wt,unknown:()=>_t,util:()=>g,void:()=>vt});
9
+
10
+ Ze.object({sessionId:Ze.string().uuid()});var o=Ze.string().min(1).max(255).regex(/^[^/+#]+$/,'Must not contain "/", "+" or "#"');Ze.object({platformId:o,sourceId:Ze.string(),isFullApi:Ze.boolean().optional().default(false),timeOffset:Ze.number().default(0)});var n=Ze.object({uuid:Ze.string(),name:Ze.string(),notificationTopic:Ze.string().optional(),eventTopic:Ze.string().optional()});Ze.object({sessionId:Ze.string(),orgId:Ze.string(),userId:Ze.string(),platformId:Ze.string(),sourceId:Ze.string(),groups:Ze.array(n),mqtt:Ze.object({sessionRootTopic:Ze.string(),userNotificationEventsTopic:Ze.string(),allNotificationEventsTopic:Ze.string().optional(),notificationsRootTopic:Ze.string(),lastWillTopic:Ze.string(),url:Ze.string(),token:Ze.string(),userNotificationTopic:Ze.string(),localSessionExpiryHandling:Ze.boolean()}).optional()}).strict();Ze.object({title:Ze.string().optional(),date:Ze.number().optional(),appId:Ze.string().optional(),stream:Ze.object({appId:Ze.string().optional()}).optional()}).passthrough();var e=Ze.object({groups:Ze.array(Ze.string()).default([]),users:Ze.array(Ze.string().min(1).max(255).regex(/^[\w+.@-]+$/)).default([])});Ze.object({action:Ze.literal("forward"),actionData:Ze.object({id:Ze.string().min(1),forwardTargets:e})});var a=Ze.enum(["reuse","new"]);Ze.object({action:Ze.literal("raise-intent"),actionData:Ze.object({intentName:Ze.string().min(1),context:Ze.object({type:Ze.string().min(1)}).passthrough(),targetApp:Ze.string().min(1).optional(),instanceBehaviour:a.optional()})});Ze.object({action:Ze.literal("open"),actionData:Ze.object({id:Ze.string().min(1),context:Ze.object({type:Ze.string().min(1)}).passthrough().optional()})});Ze.object({forwardActionId:Ze.string().min(1)});var r=Ze.enum(["new","update","delete"]),i=Ze.object({correlationId:Ze.string().optional(),targets:e,ttlSeconds:Ze.number().optional(),notificationClass:o.default("interactive").optional(),payload:Ze.unknown()}),s=Ze.object({sessionId:Ze.string().uuid(),timeOffset:Ze.number(),notification:i});s.extend({notification:i.omit({targets:true}).strict()});Ze.object({sessionId:Ze.string().uuid(),timeOffset:Ze.number().optional().default(0),ttlSeconds:Ze.number().optional(),payload:Ze.unknown()});var p=Ze.enum(["users","groups"]),I=Ze.object({notificationId:Ze.string().uuid(),category:Ze.string(),type:Ze.string(),sourceId:Ze.string(),originatingSessionId:Ze.string().uuid(),platformId:Ze.string(),userId:Ze.string().uuid(),userName:Ze.string().optional(),payload:Ze.unknown().optional(),correlationId:Ze.string().optional()}),N=Ze.object({action:r,notificationId:Ze.string().uuid(),originatingSessionId:Ze.string().uuid(),correlationId:Ze.string().optional(),target:Ze.string(),targetType:p,payload:Ze.unknown(),txInstanceId:Ze.string().uuid()}),c=Ze.object({category:Ze.string(),type:Ze.string(),payload:Ze.unknown().optional()});Ze.object({sessionId:Ze.string().uuid(),timeOffset:Ze.number().optional().default(0),event:c,targets:e.nullable().optional()});Ze.object({userId:Ze.string().uuid(),platformId:Ze.string(),sourceId:Ze.string(),notificationId:Ze.string().uuid(),category:Ze.string(),type:Ze.string(),sessionId:Ze.string().uuid(),payload:Ze.unknown().optional(),timestamp:Ze.date(),cursor:Ze.string().base64(),correlationId:Ze.string().nullish(),targets:e.optional()});
7
11
 
8
12
  class CloudNotificationAPIError extends Error {
9
13
  code;
@@ -18,6 +22,11 @@ class AuthorizationError extends CloudNotificationAPIError {
18
22
  super(message, code, undefined);
19
23
  }
20
24
  }
25
+ class OAuthAuthenticationError extends CloudNotificationAPIError {
26
+ constructor(message, code = 'ERR_OAUTH', cause) {
27
+ super(message, code, cause);
28
+ }
29
+ }
21
30
  class SessionNotConnectedError extends CloudNotificationAPIError {
22
31
  constructor(message = 'Session not connected', code = 'ERR_SESSION_NOT_CONNECTED') {
23
32
  super(message, code, undefined);
@@ -52,6 +61,16 @@ class InvalidMessageFormatError extends CloudNotificationAPIError {
52
61
  // Error codes as defined in https://docs.emqx.com/en/cloud/latest/connect_to_deployments/mqtt_client_error_codes.html
53
62
  const BadUserNamePasswordError = 134;
54
63
 
64
+ const rethrowAsOAuthAuthenticationError = (error) => {
65
+ if (error instanceof w$1) {
66
+ throw new OAuthAuthenticationError(error.message, 'ERR_OAUTH', error);
67
+ }
68
+ if (error instanceof TypeError) {
69
+ throw new OAuthAuthenticationError('OAuth access token could not be obtained', 'ERR_OAUTH', error);
70
+ }
71
+ throw error;
72
+ };
73
+
55
74
  class EventController {
56
75
  #eventListeners = new Map();
57
76
  addEventListener(type, callback) {
@@ -81,6 +100,108 @@ class EventController {
81
100
  }
82
101
  }
83
102
 
103
+ class TimeDifferenceTracker {
104
+ #timeServerUrl;
105
+ #intervalMs;
106
+ #samples;
107
+ #authenticatedFetch;
108
+ #currentOffset = 0;
109
+ #timerId;
110
+ #stopped = false;
111
+ #logger;
112
+ constructor(timeServerUrl, authenticatedFetch, logger, intervalMs = 60 * 60 * 1000, samples = 10) {
113
+ this.#timeServerUrl = timeServerUrl;
114
+ this.#logger = logger;
115
+ this.#authenticatedFetch = authenticatedFetch;
116
+ this.#intervalMs = intervalMs;
117
+ this.#samples = samples;
118
+ }
119
+ async start() {
120
+ await this.updateTimeOffset();
121
+ }
122
+ stop() {
123
+ this.#stopped = true;
124
+ if (this.#timerId) {
125
+ clearInterval(this.#timerId);
126
+ this.#timerId = undefined;
127
+ }
128
+ }
129
+ async updateTimeOffset() {
130
+ if (this.#timerId) {
131
+ clearInterval(this.#timerId);
132
+ this.#timerId = undefined;
133
+ }
134
+ try {
135
+ this.#currentOffset = await this.#getAverageOffset();
136
+ this.#logger('debug', `Time offset: ${this.#currentOffset} ms`);
137
+ if (this.#stopped) {
138
+ return this.#currentOffset;
139
+ }
140
+ this.#timerId = setInterval(async () => {
141
+ try {
142
+ this.#currentOffset = await this.#getAverageOffset();
143
+ this.#logger('debug', `Time offset: ${this.#currentOffset} ms`);
144
+ }
145
+ catch {
146
+ this.#logger('error', `Failed to update time offset`);
147
+ }
148
+ }, this.#intervalMs);
149
+ return this.#currentOffset;
150
+ }
151
+ catch (error) {
152
+ if (error instanceof OAuthAuthenticationError) {
153
+ throw error;
154
+ }
155
+ this.#logger('error', `Failed to update time offset`);
156
+ }
157
+ }
158
+ get currentOffset() {
159
+ return this.#currentOffset;
160
+ }
161
+ async #measureOffset() {
162
+ const start = Date.now();
163
+ const response = await this.#authenticatedFetch(`${this.#timeServerUrl}/api/time`, {
164
+ method: 'GET',
165
+ });
166
+ if (response.status === 401) {
167
+ return 'unauthorized';
168
+ }
169
+ const end = Date.now();
170
+ const data = await response.json();
171
+ const rtt = end - start;
172
+ const clientMidpoint = (start + end) / 2;
173
+ return {
174
+ offset: data.serverTime - clientMidpoint,
175
+ rtt,
176
+ };
177
+ }
178
+ async #getAverageOffset() {
179
+ const results = [];
180
+ for (let index = 0; index < this.#samples && !this.#stopped; index++) {
181
+ try {
182
+ const result = await this.#measureOffset();
183
+ if (result === 'unauthorized') {
184
+ break;
185
+ }
186
+ results.push(result);
187
+ }
188
+ catch (error) {
189
+ if (error instanceof OAuthAuthenticationError) {
190
+ throw error;
191
+ }
192
+ // Just ignore any time get failures
193
+ }
194
+ await new Promise((res) => setTimeout(res, 50));
195
+ }
196
+ if (results.length === 0) {
197
+ return this.#currentOffset;
198
+ }
199
+ // Filter out top 20% RTTs as outliers
200
+ const filtered = results.sort((a, b) => a.rtt - b.rtt).slice(0, Math.max(1, Math.floor(results.length * 0.8)));
201
+ return filtered.reduce((sum, r) => sum + r.offset, 0) / filtered.length;
202
+ }
203
+ }
204
+
84
205
  function validateConnectParameters(parameters) {
85
206
  if (!parameters) {
86
207
  throw new Error('Connect parameters must be provided');
@@ -96,6 +217,17 @@ function validateConnectParameters(parameters) {
96
217
  (!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
97
218
  throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
98
219
  }
220
+ if (parameters.authenticationType === 'oauth') {
221
+ if (!parameters.oauthAuthenticationParameters?.clientId?.trim() || !parameters.oauthAuthenticationParameters?.clientSecret?.trim()) {
222
+ throw new OAuthAuthenticationError('oauthAuthenticationParameters must be provided when using oauth authentication');
223
+ }
224
+ try {
225
+ $n(parameters.oauthAuthenticationParameters);
226
+ }
227
+ catch (error) {
228
+ rethrowAsOAuthAuthenticationError(error);
229
+ }
230
+ }
99
231
  }
100
232
  function handleAPIException(logger, error, message, exceptionConstructor) {
101
233
  if (error instanceof Error) {
@@ -116,9 +248,18 @@ async function checkResponse(logger, response, failMessage, failCode) {
116
248
  throw new CloudNotificationAPIError(`${failMessage} (HTTP ${response.status}: ${response.statusText})`, failCode, responseBody);
117
249
  }
118
250
  }
119
- function getRequestHeaders(connectionParameters) {
251
+ async function getRequestHeaders(connectionParameters, tokenClient) {
120
252
  const headers = {};
121
253
  headers['Content-Type'] = 'application/json';
254
+ if (connectionParameters.authenticationType === 'oauth' && tokenClient) {
255
+ try {
256
+ const accessToken = await tokenClient.getAccessToken();
257
+ headers['Authorization'] = `Bearer ${accessToken}`;
258
+ }
259
+ catch (error) {
260
+ rethrowAsOAuthAuthenticationError(error);
261
+ }
262
+ }
122
263
  if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
123
264
  const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
124
265
  if (!tokenResult) {
@@ -190,87 +331,6 @@ class SetWithTTL {
190
331
  }
191
332
  }
192
333
 
193
- class TimeDifferenceTracker {
194
- #timeServerUrl;
195
- #intervalMs;
196
- #samples;
197
- #connectionParams;
198
- #currentOffset = 0;
199
- #timerId;
200
- #logger;
201
- constructor(timeServerUrl, connectionParameters, logger, intervalMs = 60 * 60 * 1000, samples = 10) {
202
- this.#timeServerUrl = timeServerUrl;
203
- this.#logger = logger;
204
- this.#connectionParams = connectionParameters;
205
- this.#intervalMs = intervalMs;
206
- this.#samples = samples;
207
- }
208
- async start() {
209
- await this.updateTimeOffset();
210
- }
211
- stop() {
212
- if (this.#timerId) {
213
- clearInterval(this.#timerId);
214
- this.#timerId = undefined;
215
- }
216
- }
217
- async updateTimeOffset() {
218
- if (this.#timerId) {
219
- clearInterval(this.#timerId);
220
- this.#timerId = undefined;
221
- }
222
- try {
223
- this.#currentOffset = await this.#getAverageOffset();
224
- this.#logger('debug', `Time offset: ${this.#currentOffset} ms`);
225
- this.#timerId = setInterval(async () => {
226
- this.#currentOffset = await this.#getAverageOffset();
227
- this.#logger('debug', `Time offset: ${this.#currentOffset} ms`);
228
- }, this.#intervalMs);
229
- return this.#currentOffset;
230
- }
231
- catch {
232
- this.#logger('error', `Failed to update time offset`);
233
- }
234
- }
235
- get currentOffset() {
236
- return this.#currentOffset;
237
- }
238
- async #measureOffset() {
239
- if (!this.#connectionParams) {
240
- throw new Error('Connection details not set');
241
- }
242
- const start = Date.now();
243
- const response = await fetch(`${this.#timeServerUrl}/api/time`, {
244
- method: 'GET',
245
- headers: getRequestHeaders(this.#connectionParams),
246
- });
247
- const end = Date.now();
248
- const data = await response.json();
249
- const rtt = end - start;
250
- const clientMidpoint = (start + end) / 2;
251
- return {
252
- offset: data.serverTime - clientMidpoint,
253
- rtt,
254
- };
255
- }
256
- async #getAverageOffset() {
257
- const results = [];
258
- for (let index = 0; index < this.#samples; index++) {
259
- try {
260
- const result = await this.#measureOffset();
261
- results.push(result);
262
- }
263
- catch {
264
- // Just ignore any time get failures
265
- }
266
- await new Promise((res) => setTimeout(res, 50));
267
- }
268
- // Filter out top 20% RTTs as outliers
269
- const filtered = results.sort((a, b) => a.rtt - b.rtt).slice(0, Math.floor(results.length * 0.8));
270
- return filtered.reduce((sum, r) => sum + r.offset, 0) / filtered.length;
271
- }
272
- }
273
-
274
334
  /**
275
335
  * Represents a single connection to the Cloud Notification service
276
336
  *
@@ -286,11 +346,14 @@ class CloudNotificationAPI {
286
346
  #deDuplicator;
287
347
  #reconnectRetries = 0;
288
348
  #connectionParams;
349
+ #tokenClient;
289
350
  #attemptingToReconnect = false;
351
+ #disconnecting = false;
290
352
  #events = new EventController();
291
353
  #defaultSubscriptionOptions = { qos: 2, nl: true };
292
354
  #logger = (level, message) => console[level](message);
293
355
  #getCurrentTimeOffset = () => this.#timeDifferenceTracker?.currentOffset || 0;
356
+ #sessionTimer;
294
357
  /**
295
358
  * Constructs a new instance of the CloudNotificationAPI
296
359
  *
@@ -326,22 +389,49 @@ class CloudNotificationAPI {
326
389
  * @returns A promise that resolves when the connection is established.
327
390
  * @throws {@link CloudNotificationAPIError} If an error occurs during connection.
328
391
  * @throws {@link AuthorizationError} If the connection is unauthorized.
392
+ * @throws {@link OAuthAuthenticationError} If OAuth parameters are invalid, the client credentials are rejected, or an access token cannot be obtained.
329
393
  */
330
394
  async connect(parameters) {
331
395
  validateConnectParameters(parameters);
396
+ const oauthParameters = parameters.oauthAuthenticationParameters;
397
+ if (parameters.authenticationType === 'oauth' && oauthParameters) {
398
+ try {
399
+ this.#tokenClient = Je$1.fromServiceUrl(this.#cloudNotificationSettings.url, oauthParameters.clientId, oauthParameters.clientSecret);
400
+ }
401
+ catch (error) {
402
+ rethrowAsOAuthAuthenticationError(error);
403
+ }
404
+ }
405
+ else {
406
+ this.#tokenClient = undefined;
407
+ }
332
408
  this.#connectionParams = parameters;
333
- if (this.#timeDifferenceTracker) {
334
- this.#timeDifferenceTracker.stop();
335
- this.#timeDifferenceTracker = undefined;
409
+ if (parameters.authenticationType === 'oauth' && this.#tokenClient) {
410
+ try {
411
+ await this.#tokenClient.getAccessToken();
412
+ }
413
+ catch (error) {
414
+ rethrowAsOAuthAuthenticationError(error);
415
+ }
416
+ }
417
+ this.#logger('info', 'Creating Notification service session');
418
+ this.#stopTimeSync();
419
+ this.#timeDifferenceTracker = new TimeDifferenceTracker(this.#cloudNotificationSettings.url, this.#authenticatedFetch, this.#logger);
420
+ try {
421
+ return await this.#createSession(this.#timeDifferenceTracker, parameters);
422
+ }
423
+ catch (error) {
424
+ this.#timeDifferenceTracker?.stop();
425
+ throw error;
336
426
  }
337
- this.#timeDifferenceTracker = new TimeDifferenceTracker(this.#cloudNotificationSettings.url, parameters, this.#logger);
427
+ }
428
+ async #createSession(timeDifferenceTracker, parameters) {
338
429
  if (this.#syncTime !== false) {
339
- await this.#timeDifferenceTracker.start();
430
+ await timeDifferenceTracker.start();
340
431
  }
341
- const { platformId, sourceId } = this.#connectionParams;
342
- const createSessionResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/sessions`, {
432
+ const { platformId, sourceId } = parameters;
433
+ const createSessionResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/sessions`, {
343
434
  method: 'POST',
344
- headers: getRequestHeaders(this.#connectionParams),
345
435
  body: JSON.stringify({
346
436
  platformId,
347
437
  sourceId,
@@ -354,9 +444,15 @@ class CloudNotificationAPI {
354
444
  throw new CloudNotificationAPIError(`Failed to connect to the Cloud Notification service: ${this.#cloudNotificationSettings.url}`, 'ERR_CONNECT', new Error(createSessionResponse.statusText));
355
445
  }
356
446
  this.#sessionDetails = (await createSessionResponse.json());
447
+ const { mqtt: _, ...sessionDetailsWithoutMQTT } = this.#sessionDetails;
448
+ this.#logger('info', `Notification service session created: ${JSON.stringify(sessionDetailsWithoutMQTT, null, 2)}`);
357
449
  // Now have the details from the server about where to connect to and a token to connect with
358
450
  // we can go ahead and connect to the MQTT server
359
451
  await this.#connectToMQTT();
452
+ // If local session expiry handling is enabled, start the session timer
453
+ if (this.#sessionDetails.mqtt?.localSessionExpiryHandling) {
454
+ this.#startSessionTimer();
455
+ }
360
456
  return { sessionId: this.#sessionDetails.sessionId, platformId, sourceId, userId: this.#sessionDetails.userId, groups: this.#sessionDetails.groups };
361
457
  }
362
458
  /**
@@ -371,7 +467,7 @@ class CloudNotificationAPI {
371
467
  /**
372
468
  * Posts a notification event to the Cloud Notification service.
373
469
  *
374
- * @param notificationId - The ID of the notification.
470
+ * @param notificationId - The ID of the notification or an array of notification IDs.
375
471
  * @param event - The event details, including category, type, and optional payload.
376
472
  * @returns A promise that resolves when the event is posted.
377
473
  * @throws {@link SessionNotConnectedError} If the session is not connected.
@@ -389,9 +485,10 @@ class CloudNotificationAPI {
389
485
  event,
390
486
  targets: options?.targets,
391
487
  };
392
- const publishResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/publications/${notificationId}/events`, {
488
+ const notificationIds = Array.isArray(notificationId) ? notificationId : [notificationId];
489
+ const notificationIdsString = notificationIds.join('&id=');
490
+ const publishResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/publications/events?id=${notificationIdsString}`, {
393
491
  method: 'POST',
394
- headers: getRequestHeaders(this.#connectionParams),
395
492
  body: JSON.stringify(publishPayload),
396
493
  });
397
494
  await checkResponse(this.#logger, publishResponse, 'Error posting notification event', 'ERR_POST_NOTIFICATION_EVENT');
@@ -408,13 +505,28 @@ class CloudNotificationAPI {
408
505
  * @returns A promise that resolves when the notification is removed.
409
506
  */
410
507
  async removeFromNotificationCenter(notificationId, targets) {
411
- return this.postNotificationEvent(notificationId, {
412
- category: 'notification-center-event',
413
- type: 'notification-closed',
414
- payload: {},
415
- }, {
416
- targets,
417
- });
508
+ return this.postNotificationEvent(notificationId, { category: 'notification-center-event', type: 'notification-closed', payload: {} }, { targets });
509
+ }
510
+ /**
511
+ * Post a notification-reminder-created event to the Cloud Notification service.
512
+ *
513
+ * @param notificationId - The ID of the notification or an array of notification IDs to mark as a reminder.
514
+ * @param payload - The payload of the reminder.
515
+ * @returns A promise that resolves when the notification-reminder-created event is posted.
516
+ * @throws {@link SessionNotConnectedError} If the session is not connected.
517
+ */
518
+ async setReminder(notificationId, payload, targets) {
519
+ return this.postNotificationEvent(notificationId, { category: 'notification-center-event', type: 'notification-reminder-created', payload }, { targets });
520
+ }
521
+ /**
522
+ * Post a notification-reminder-removed event to the Cloud Notification service.
523
+ *
524
+ * @param notificationId - The ID of the notification or an array of notification IDs to cancel the reminder for.
525
+ * @returns A promise that resolves when the notification-reminder-removed event is posted.
526
+ * @throws {@link SessionNotConnectedError} If the session is not connected.
527
+ */
528
+ async cancelReminder(notificationId, targets) {
529
+ return this.postNotificationEvent(notificationId, { category: 'notification-center-event', type: 'notification-reminder-removed' }, { targets });
418
530
  }
419
531
  /**
420
532
  * Raises a notification to the Cloud Notification service.
@@ -426,33 +538,22 @@ class CloudNotificationAPI {
426
538
  * @throws {@link PublishError} If an error occurs during publishing.
427
539
  */
428
540
  async raiseNotification(options, payload) {
429
- if (!this.#sessionDetails || !this.#connectionParams) {
430
- this.#logger('error', 'Invalid Session');
431
- throw new SessionNotConnectedError();
432
- }
433
- try {
434
- const publishPayload = {
435
- sessionId: this.#sessionDetails.sessionId,
436
- timeOffset: this.#getCurrentTimeOffset(),
437
- notification: {
438
- ttlSeconds: options.ttlSeconds,
439
- correlationId: options.correlationId,
440
- targets: options.targets,
441
- payload,
442
- },
443
- };
444
- const publishResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/publications`, {
445
- method: 'POST',
446
- headers: getRequestHeaders(this.#connectionParams),
447
- body: JSON.stringify(publishPayload),
448
- });
449
- await checkResponse(this.#logger, publishResponse, 'Error publishing notification', 'ERR_PUBLISH_NOTIFICATION');
450
- const publishResponseBody = (await publishResponse.json());
451
- return publishResponseBody;
452
- }
453
- catch (error) {
454
- handleAPIException(this.#logger, error, 'Error publishing notification', PublishError);
455
- }
541
+ return this.#publishNewNotification('/api/publications', { ...options, payload });
542
+ }
543
+ /**
544
+ * Raises a notification to the connected user via the Cloud Notification service.
545
+ *
546
+ * Unlike {@link raiseNotification}, no notification raise permissions are required and the notification
547
+ * is always targeted at the connected user only.
548
+ *
549
+ * @param options - The options for the notification.
550
+ * @param payload - The payload of the notification which should generally conform to the notification center schema
551
+ * @returns A promise that resolves with the notification raise result.
552
+ * @throws {@link SessionNotConnectedError} If the session is not connected.
553
+ * @throws {@link PublishError} If an error occurs during publishing.
554
+ */
555
+ async raiseNotificationToMe(options, payload) {
556
+ return this.#publishNewNotification('/api/publications/me', { ...options, payload });
456
557
  }
457
558
  /**
458
559
  * Raises a notification update to the Cloud Notification service.
@@ -475,9 +576,8 @@ class CloudNotificationAPI {
475
576
  ttlSeconds: options.ttlSeconds,
476
577
  payload,
477
578
  };
478
- const updateResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/publications/${notificationId}`, {
579
+ const updateResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/publications/${notificationId}`, {
479
580
  method: 'PATCH',
480
- headers: getRequestHeaders(this.#connectionParams),
481
581
  body: JSON.stringify(updatePayload),
482
582
  });
483
583
  await checkResponse(this.#logger, updateResponse, 'Error updating notification', 'ERR_UPDATING_NOTIFICATION');
@@ -501,9 +601,10 @@ class CloudNotificationAPI {
501
601
  throw new SessionNotConnectedError();
502
602
  }
503
603
  try {
504
- const deleteResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/publications/${notificationId}?sessionId=${this.#sessionDetails.sessionId}`, {
604
+ const notificationIds = Array.isArray(notificationId) ? notificationId : [notificationId];
605
+ const notificationIdsString = notificationIds.join('&id=');
606
+ const deleteResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/publications?id=${notificationIdsString}&sessionId=${this.#sessionDetails.sessionId}`, {
505
607
  method: 'DELETE',
506
- headers: getRequestHeaders(this.#connectionParams),
507
608
  });
508
609
  await checkResponse(this.#logger, deleteResponse, 'Error deleting notification', 'ERR_DELETE_NOTIFICATION');
509
610
  }
@@ -539,9 +640,8 @@ class CloudNotificationAPI {
539
640
  if ([...parameters].length > 0) {
540
641
  replayUrl += `?${parameters.toString()}`;
541
642
  }
542
- const replayResponse = await fetch(replayUrl, {
643
+ const replayResponse = await this.#authenticatedFetch(replayUrl, {
543
644
  method: 'POST',
544
- headers: getRequestHeaders(this.#connectionParams),
545
645
  body: JSON.stringify({
546
646
  sessionId: this.#sessionDetails.sessionId,
547
647
  }),
@@ -581,11 +681,35 @@ class CloudNotificationAPI {
581
681
  once(type, callback) {
582
682
  this.#events.once(type, callback);
583
683
  }
684
+ async #publishNewNotification(path, notification) {
685
+ if (!this.#sessionDetails || !this.#connectionParams) {
686
+ this.#logger('error', 'Invalid Session');
687
+ throw new SessionNotConnectedError();
688
+ }
689
+ try {
690
+ const publishResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}${path}`, {
691
+ method: 'POST',
692
+ body: JSON.stringify({
693
+ sessionId: this.#sessionDetails.sessionId,
694
+ timeOffset: this.#getCurrentTimeOffset(),
695
+ notification,
696
+ }),
697
+ });
698
+ await checkResponse(this.#logger, publishResponse, 'Error publishing notification', 'ERR_PUBLISH_NOTIFICATION');
699
+ const publishResponseBody = (await publishResponse.json());
700
+ return publishResponseBody;
701
+ }
702
+ catch (error) {
703
+ handleAPIException(this.#logger, error, 'Error publishing notification', PublishError);
704
+ }
705
+ }
584
706
  async #connectToMQTT() {
585
707
  if (!this.#sessionDetails || !this.#sessionDetails.mqtt) {
586
708
  this.#logger('error', 'Invalid Session');
587
709
  throw new SessionNotConnectedError();
588
710
  }
711
+ const { token: _, ...mqttDetailsWithoutToken } = this.#sessionDetails.mqtt;
712
+ this.#logger('info', `Connecting to MQTT server: ${JSON.stringify(mqttDetailsWithoutToken, null, 2)}`);
589
713
  const clientOptions = {
590
714
  keepalive: this.#keepAliveIntervalSeconds,
591
715
  clientId: this.#sessionDetails.sessionId,
@@ -601,14 +725,16 @@ class CloudNotificationAPI {
601
725
  username: this.#sessionDetails.mqtt.token,
602
726
  };
603
727
  this.#mqttClient = await mqtt.connectAsync(this.#sessionDetails.mqtt.url, clientOptions);
604
- this.#logger('debug', `Cloud Notifications successfully connected to notification backbone`);
605
728
  this.#mqttClient.on('error', async (error) => this.#mqttErrorHandler(error));
606
- this.#mqttClient.on('reconnect', () => this.#mqttReconnectionHandler());
729
+ this.#mqttClient.on('reconnect', async () => {
730
+ await this.#mqttReconnectionHandler();
731
+ });
607
732
  // Does not fire on initial connection, only successful reconnection attempts
608
733
  this.#mqttClient.on('connect', () => this.#mqttConnectionHandler());
609
734
  this.#mqttClient.on('message', (topic, message) => this.#mqttMessageHandler(topic, message));
610
735
  // Subscribe any session specific topics
611
736
  this.#mqttClient.subscribe(`${this.#sessionDetails.mqtt.sessionRootTopic}/#`);
737
+ this.#logger('info', 'Successfully connected to MQTT server');
612
738
  // Subscribe to the user notification delivery topics for groups and users
613
739
  await this.#subscribeToNotificationTopics();
614
740
  }
@@ -622,11 +748,11 @@ class CloudNotificationAPI {
622
748
  this.#attemptingToReconnect = true;
623
749
  this.#reconnectRetries += 1;
624
750
  this.#logger('debug', `Cloud Notifications attempting reconnection - ${this.#reconnectRetries}...`);
751
+ this.#events.emitEvent('reconnecting', this.#reconnectRetries);
625
752
  if (this.#reconnectRetries === this.#reconnectRetryLimit) {
626
753
  this.#logger('warn', `Cloud Notifications reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
627
- this.#disconnect(true);
754
+ await this.#disconnectAndLogFailure(true);
628
755
  }
629
- this.#events.emitEvent('reconnecting', this.#reconnectRetries);
630
756
  }
631
757
  async #mqttMessageHandler(topic, message) {
632
758
  if (!this.#sessionDetails) {
@@ -642,7 +768,14 @@ class CloudNotificationAPI {
642
768
  this.#logger('debug', `Session expired`);
643
769
  this.#events.emitEvent('session-expired');
644
770
  // TODO: Request new JWT if using JWT authentication
645
- await this.#extendSession();
771
+ const sessionId = this.#sessionDetails?.sessionId;
772
+ try {
773
+ await this.#extendSession();
774
+ }
775
+ catch (extendError) {
776
+ await this.#handleSessionExtendFailure(extendError, sessionId);
777
+ return;
778
+ }
646
779
  this.#logger('debug', `Session extended`);
647
780
  this.#events.emitEvent('session-extended');
648
781
  return;
@@ -704,6 +837,20 @@ class CloudNotificationAPI {
704
837
  }
705
838
  await Promise.all(subscribePromises);
706
839
  }
840
+ #authenticatedFetch = async (url, { method, body }) => {
841
+ const connectionParameters = this.#connectionParams;
842
+ if (!connectionParameters) {
843
+ throw new Error('Connect parameters must be provided');
844
+ }
845
+ const attempt = async () => {
846
+ const headers = await getRequestHeaders(connectionParameters, this.#tokenClient);
847
+ return fetch(url, { method, headers, body });
848
+ };
849
+ if (connectionParameters.authenticationType === 'oauth' && this.#tokenClient) {
850
+ return Fn(this.#tokenClient, attempt);
851
+ }
852
+ return attempt();
853
+ };
707
854
  async #extendSession() {
708
855
  if (!this.#sessionDetails) {
709
856
  return;
@@ -717,9 +864,8 @@ class CloudNotificationAPI {
717
864
  this.#mqttClient = undefined;
718
865
  this.#reconnectRetries = 0;
719
866
  this.#attemptingToReconnect = false;
720
- const extendResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/sessions`, {
867
+ const extendResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/sessions`, {
721
868
  method: 'PUT',
722
- headers: getRequestHeaders(this.#connectionParams),
723
869
  body: JSON.stringify({
724
870
  sessionId: this.#sessionDetails.sessionId,
725
871
  }),
@@ -730,23 +876,33 @@ class CloudNotificationAPI {
730
876
  this.#sessionDetails = (await extendResponse.json());
731
877
  this.#attemptingToReconnect = true;
732
878
  await this.#connectToMQTT();
879
+ // If local session expiry handling is enabled, start the session timer
880
+ if (this.#sessionDetails.mqtt?.localSessionExpiryHandling) {
881
+ this.#startSessionTimer();
882
+ }
733
883
  }
734
884
  catch (error) {
735
885
  throw new CloudNotificationAPIError('Error during session refresh', 'ERR_SESSION_EXTEND', error);
736
886
  }
737
887
  }
738
888
  async #disconnect(fireDisconnectedEvent) {
889
+ this.#stopTimeSync();
739
890
  if (!this.#sessionDetails) {
740
891
  return;
741
892
  }
893
+ this.#disconnecting = true;
742
894
  try {
743
895
  if (!this.#connectionParams) {
744
896
  throw new Error('Connect parameters must be provided');
745
897
  }
898
+ // Cancel session timer if it's running
899
+ if (this.#sessionTimer) {
900
+ clearTimeout(this.#sessionTimer);
901
+ this.#sessionTimer = undefined;
902
+ }
746
903
  // Clean up our session on the server
747
- const disconnectResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
904
+ const disconnectResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
748
905
  method: 'DELETE',
749
- headers: getRequestHeaders(this.#connectionParams),
750
906
  });
751
907
  if (disconnectResponse.status !== 204) {
752
908
  throw new CloudNotificationAPIError(`Error during session tear down - unexpected status ${disconnectResponse.status}`, 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
@@ -767,11 +923,131 @@ class CloudNotificationAPI {
767
923
  this.#mqttClient = undefined;
768
924
  this.#reconnectRetries = 0;
769
925
  this.#attemptingToReconnect = false;
926
+ this.#disconnecting = false;
770
927
  if (fireDisconnectedEvent) {
771
928
  this.#events.emitEvent('disconnected');
772
929
  }
773
930
  }
774
931
  }
932
+ async #disconnectAndLogFailure(fireDisconnectedEvent = false) {
933
+ try {
934
+ await this.#disconnect(fireDisconnectedEvent);
935
+ }
936
+ catch (error) {
937
+ this.#logger('error', `Session teardown failed: ${error instanceof Error ? error.message : String(error)}`);
938
+ }
939
+ }
940
+ #stopTimeSync() {
941
+ this.#timeDifferenceTracker?.stop();
942
+ this.#timeDifferenceTracker = undefined;
943
+ }
944
+ /**
945
+ * @param sessionId - The session that was being extended. The teardown is skipped when that session is already being disconnected or has been replaced.
946
+ */
947
+ async #handleSessionExtendFailure(error, sessionId) {
948
+ if (this.#disconnecting || !sessionId || this.#sessionDetails?.sessionId !== sessionId) {
949
+ this.#logger('debug', 'Ignoring a failed extend for a session that was disconnected or replaced');
950
+ return;
951
+ }
952
+ this.#logger('error', `Session extend failed: ${error instanceof Error ? error.message : String(error)}`);
953
+ this.#events.emitEvent('error', error instanceof Error ? error : new Error(String(error)));
954
+ await this.#disconnectAndLogFailure(true);
955
+ }
956
+ /**
957
+ * Extracts the expiration timestamp from a JWT token.
958
+ *
959
+ * @param token - The JWT token string
960
+ * @returns The expiration timestamp in seconds, or null if extraction fails
961
+ */
962
+ #extractExpirationFromJwt(token) {
963
+ if (!token) {
964
+ return null;
965
+ }
966
+ try {
967
+ // JWT tokens have three parts separated by dots: header.payload.signature
968
+ // The exp claim is in the payload
969
+ const parts = token.split('.');
970
+ if (parts.length < 2) {
971
+ this.#logger('warn', 'Invalid JWT token format: expected at least 2 parts');
972
+ return null;
973
+ }
974
+ const payload = parts[1];
975
+ // 'base64' also decodes unpadded base64url. The browser `buffer` polyfill has no 'base64url' encoding.
976
+ const decodedBytes = Buffer.from(payload, 'base64');
977
+ const payloadJson = decodedBytes.toString('utf8');
978
+ // Parse JSON to get the exp claim
979
+ const claims = JSON.parse(payloadJson);
980
+ const exp = claims.exp;
981
+ if (exp === undefined || exp === null) {
982
+ this.#logger('warn', "JWT token does not contain 'exp' claim");
983
+ return null;
984
+ }
985
+ if (typeof exp !== 'number') {
986
+ this.#logger('warn', `JWT token 'exp' claim is not a number: ${exp}`);
987
+ return null;
988
+ }
989
+ return exp;
990
+ }
991
+ catch (error) {
992
+ this.#logger('error', `Failed to extract expiration from JWT token: ${error instanceof Error ? error.message : error}`);
993
+ return null;
994
+ }
995
+ }
996
+ /**
997
+ * Start a session timer that will expire at the time specified in the JWT token's exp claim.
998
+ * On expiry, it will fire session expired event, extend the session, fire session extended event, and restart the timer.
999
+ */
1000
+ #startSessionTimer() {
1001
+ if (!this.#sessionDetails?.mqtt?.token) {
1002
+ this.#logger('warn', 'Cannot start session timer: session details or token not available');
1003
+ return;
1004
+ }
1005
+ // Extract expiration time from JWT token
1006
+ const expTimestamp = this.#extractExpirationFromJwt(this.#sessionDetails.mqtt.token);
1007
+ if (expTimestamp === null) {
1008
+ this.#logger('warn', 'Cannot start session timer: could not extract expiration from JWT token');
1009
+ return;
1010
+ }
1011
+ const currentTimeSeconds = Math.floor(Date.now() / 1000);
1012
+ const delaySeconds = expTimestamp - currentTimeSeconds;
1013
+ if (delaySeconds <= 0) {
1014
+ this.#logger('warn', 'JWT token has already expired or expires immediately');
1015
+ this.#events.emitEvent('session-expired');
1016
+ const sessionId = this.#sessionDetails.sessionId;
1017
+ this.#extendSession()
1018
+ .then(() => {
1019
+ this.#logger('debug', 'Session extended');
1020
+ this.#events.emitEvent('session-extended');
1021
+ })
1022
+ .catch((error) => this.#handleSessionExtendFailure(error, sessionId));
1023
+ return;
1024
+ }
1025
+ // Clear any existing timer
1026
+ if (this.#sessionTimer) {
1027
+ clearTimeout(this.#sessionTimer);
1028
+ }
1029
+ const expirationTimeString = new Date(expTimestamp * 1000).toISOString();
1030
+ this.#logger('debug', `Starting session timer to expire in ${delaySeconds} seconds (at ${expirationTimeString})`);
1031
+ this.#sessionTimer = setTimeout(async () => {
1032
+ const sessionId = this.#sessionDetails?.sessionId;
1033
+ try {
1034
+ this.#logger('debug', 'Session timer expired');
1035
+ this.#events.emitEvent('session-expired');
1036
+ await this.#extendSession();
1037
+ this.#logger('debug', 'Session extended');
1038
+ this.#events.emitEvent('session-extended');
1039
+ }
1040
+ catch (error) {
1041
+ await this.#handleSessionExtendFailure(error, sessionId);
1042
+ }
1043
+ }, delaySeconds * 1000);
1044
+ }
1045
+ #isGroupEventTopic(topic) {
1046
+ if (!this.#sessionDetails) {
1047
+ return false;
1048
+ }
1049
+ return this.#sessionDetails.groups.some((group) => group.eventTopic?.startsWith(topic));
1050
+ }
775
1051
  #handleMessage(topic, message, sessionDetails) {
776
1052
  if (message.length === 0 || !sessionDetails || !sessionDetails.mqtt) {
777
1053
  // Ignore clean up messages
@@ -779,16 +1055,20 @@ class CloudNotificationAPI {
779
1055
  }
780
1056
  try {
781
1057
  const messagePayload = JSON.parse(message.toString());
1058
+ // NOTE: uncomment this to debug message payloads
1059
+ // this.#logger('info', `Received message on topic ${topic} with payload ${JSON.stringify(messagePayload)}`);
782
1060
  if (topic.startsWith(sessionDetails.mqtt.notificationsRootTopic)) {
783
1061
  this.#handleNotificationMessage(messagePayload);
784
- // The following line allows for both group and user targeted events as well as event for self published notifications. The payload is the same for both scenarios.
785
1062
  }
786
- else if (topic === sessionDetails.mqtt.userNotificationEventsTopic || topic.startsWith(sessionDetails.mqtt.eventsRootTopic)) {
1063
+ else if (topic === sessionDetails.mqtt.userNotificationEventsTopic) {
787
1064
  this.#handleUserNotificationEventMessage(messagePayload);
788
1065
  }
789
1066
  else if (topic === sessionDetails.mqtt.allNotificationEventsTopic) {
790
1067
  this.#handleAllNotificationEventMessage(messagePayload);
791
1068
  }
1069
+ else if (this.#isGroupEventTopic(topic)) {
1070
+ this.#handleGroupNotificationEventMessage(messagePayload);
1071
+ }
792
1072
  else {
793
1073
  this.#logger('warn', `Received message on unknown topic ${topic}`);
794
1074
  this.#events.emitEvent('error', new CloudNotificationAPIError(`Received message on unknown topic ${topic}`, 'ERR_UNKNOWN_TOPIC'));
@@ -800,7 +1080,7 @@ class CloudNotificationAPI {
800
1080
  }
801
1081
  }
802
1082
  #handleNotificationMessage(messagePayload) {
803
- const parseResult = f.safeParse(messagePayload);
1083
+ const parseResult = N.safeParse(messagePayload);
804
1084
  if (!parseResult.success) {
805
1085
  this.#logger('warn', `Received invalid notification message payload format ${parseResult.error?.toString()}`);
806
1086
  throw new InvalidMessageFormatError(parseResult);
@@ -817,40 +1097,57 @@ class CloudNotificationAPI {
817
1097
  this.#deDuplicator.add(txInstanceId);
818
1098
  this.#sendNotificationDeliveredStatus(notificationId);
819
1099
  let targetName = target;
820
- if (targetType === 'group') {
1100
+ if (targetType === 'groups') {
821
1101
  targetName = this.#lookupGroupNameByUuid(target);
822
1102
  }
1103
+ const makePayload = (action) => ({ action, notificationId, correlationId, target, targetName, targetType, payload });
823
1104
  switch (action) {
824
1105
  case 'new': {
825
- this.#events.emitEvent('new-notification', { action: 'new', notificationId, correlationId, target, targetName, targetType, payload });
1106
+ this.#events.emitEvent('new-notification', makePayload('new'));
826
1107
  break;
827
1108
  }
828
1109
  case 'update': {
829
- this.#events.emitEvent('update-notification', { action: 'update', notificationId, correlationId, target, targetName, targetType, payload });
1110
+ this.#events.emitEvent('update-notification', makePayload('update'));
830
1111
  break;
831
1112
  }
832
1113
  case 'delete': {
833
- this.#events.emitEvent('delete-notification', { action: 'delete', notificationId, correlationId, target, targetName, targetType, payload });
1114
+ this.#events.emitEvent('delete-notification', makePayload('delete'));
834
1115
  break;
835
1116
  }
836
1117
  // No default - Schema validation will prevent this
837
1118
  }
838
1119
  }
839
1120
  #handleUserNotificationEventMessage(messagePayload) {
840
- const parseResult = l.safeParse(messagePayload);
841
- if (!parseResult.success) {
842
- this.#logger('warn', `Received invalid notification event message payload format ${parseResult.error?.toString()}`);
843
- throw new InvalidMessageFormatError(parseResult);
1121
+ const event = this.#parseNotificationEventMessage(messagePayload);
1122
+ if (event.originatingSessionId === this.#sessionDetails?.sessionId) {
1123
+ this.#logger('debug', `Received notification event from our own session, ignoring. (session id: ${event.originatingSessionId})`);
1124
+ return;
844
1125
  }
845
- this.#events.emitEvent('notification-event', parseResult.data);
1126
+ this.#events.emitEvent('notification-event', event);
1127
+ }
1128
+ #handleGroupNotificationEventMessage(messagePayload) {
1129
+ const event = this.#parseNotificationEventMessage(messagePayload);
1130
+ if (event.originatingSessionId === this.#sessionDetails?.sessionId) {
1131
+ this.#logger('debug', `Received notification event from our own session, ignoring. (session id: ${event.originatingSessionId})`);
1132
+ return;
1133
+ }
1134
+ this.#events.emitEvent('notification-event', event);
846
1135
  }
847
1136
  #handleAllNotificationEventMessage(messagePayload) {
848
- const parseResult = l.safeParse(messagePayload);
1137
+ const event = this.#parseNotificationEventMessage(messagePayload);
1138
+ if (event.originatingSessionId === this.#sessionDetails?.sessionId) {
1139
+ this.#logger('debug', `Received notification event from our own session, ignoring. (session id: ${event.originatingSessionId})`);
1140
+ return;
1141
+ }
1142
+ this.#events.emitEvent('global-notification-event', event);
1143
+ }
1144
+ #parseNotificationEventMessage(messagePayload) {
1145
+ const parseResult = I.safeParse(messagePayload);
849
1146
  if (!parseResult.success) {
850
1147
  this.#logger('warn', `Received invalid notification event message payload format ${parseResult.error?.toString()}`);
851
1148
  throw new InvalidMessageFormatError(parseResult);
852
1149
  }
853
- this.#events.emitEvent('global-notification-event', parseResult.data);
1150
+ return parseResult.data;
854
1151
  }
855
1152
  #lookupGroupNameByUuid(uuid) {
856
1153
  if (!this.#sessionDetails) {
@@ -860,4 +1157,4 @@ class CloudNotificationAPI {
860
1157
  }
861
1158
  }
862
1159
 
863
- export { AuthorizationError, CloudNotificationAPI, CloudNotificationAPIError, EventPublishError, EventRetrievalError, InvalidMessageFormatError, NotificationRetrievalError, PublishError, SessionNotConnectedError };
1160
+ export { AuthorizationError, CloudNotificationAPI, CloudNotificationAPIError, EventPublishError, EventRetrievalError, InvalidMessageFormatError, NotificationRetrievalError, OAuthAuthenticationError, PublishError, SessionNotConnectedError, p as targetTypeSchema };