@openfin/cloud-notification-core-api 0.0.1-alpha.0c7a36f → 0.0.1-alpha.0cd5817

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 +619 -530
  3. package/index.cjs +458 -155
  4. package/index.mjs +457 -156
  5. package/package.json +6 -8
package/index.cjs CHANGED
@@ -1,11 +1,19 @@
1
1
  'use strict';
2
2
 
3
3
  var buffer = require('buffer');
4
+ require('fs');
5
+ require('path');
4
6
  var mqtt = require('mqtt');
5
7
 
6
- 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=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.undefined;case "string":return f.string;case "number":return isNaN(r)?f.nan:f.number;case "boolean":return f.boolean;case "function":return f.function;case "bigint":return f.bigint;case "symbol":return f.symbol;case "object":return Array.isArray(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r instanceof Date?f.date:f.object;default:return f.unknown}},d$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"]),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$1.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case d$1.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,g.jsonStringifyReplacer)}`;break;case d$1.unrecognized_keys:t=`Unrecognized key(s) in object: ${g.joinValues(r.keys,", ")}`;break;case d$1.invalid_union:t="Invalid input";break;case d$1.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${g.joinValues(r.options)}`;break;case d$1.invalid_enum_value:t=`Invalid enum value. Expected ${g.joinValues(r.options)}, received '${r.received}'`;break;case d$1.invalid_arguments:t="Invalid function arguments";break;case d$1.invalid_return_type:t="Invalid function return type";break;case d$1.invalid_date:t="Invalid date";break;case d$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 d$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==="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$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 d$1.custom:t="Invalid input";break;case d$1.invalid_intersection_types:t="Intersection results could not be merged";break;case d$1.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case d$1.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$1.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.string){let a=this._getOrReturnCtx(e);return u(a,{code:d$1.invalid_type,expected:f.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$1.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$1.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$1.too_big,maximum:a.value,type:"string",inclusive:true,exact:true,message:a.message}):o&&u(n,{code:d$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$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){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.number){let a=this._getOrReturnCtx(e);return u(a,{code:d$1.invalid_type,expected:f.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$1.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$1.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$1.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$1.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$1.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.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$1.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$1.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$1.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$1.invalid_type,expected:f.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.boolean){let s=this._getOrReturnCtx(e);return u(s,{code:d$1.invalid_type,expected:f.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.date){let a=this._getOrReturnCtx(e);return u(a,{code:d$1.invalid_type,expected:f.date,received:a.parsedType}),v}if(isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return u(a,{code:d$1.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$1.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$1.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.symbol){let s=this._getOrReturnCtx(e);return u(s,{code:d$1.invalid_type,expected:f.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.undefined){let s=this._getOrReturnCtx(e);return u(s,{code:d$1.invalid_type,expected:f.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.null){let s=this._getOrReturnCtx(e);return u(s,{code:d$1.invalid_type,expected:f.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$1.invalid_type,expected:f.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.undefined){let s=this._getOrReturnCtx(e);return u(s,{code:d$1.invalid_type,expected:f.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.array)return u(t,{code:d$1.invalid_type,expected:f.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$1.too_big:d$1.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$1.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$1.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.object){let c=this._getOrReturnCtx(e);return u(c,{code:d$1.invalid_type,expected:f.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$1.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$1.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$1.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.object)return u(t,{code:d$1.invalid_type,expected:f.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$1.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.object&&s===f.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.array&&s===f.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.date&&s===f.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$1.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.array)return u(s,{code:d$1.invalid_type,expected:f.array,received:s.parsedType}),v;if(s.data.length<this._def.items.length)return u(s,{code:d$1.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$1.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.object)return u(s,{code:d$1.invalid_type,expected:f.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.map)return u(s,{code:d$1.invalid_type,expected:f.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.set)return u(s,{code:d$1.invalid_type,expected:f.set,received:s.parsedType}),v;let n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(u(s,{code:d$1.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$1.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.function)return u(t,{code:d$1.invalid_type,expected:f.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$1.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$1.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$1.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$1.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$1.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.string&&s.parsedType!==f.number){let n=g.objectValues(t);return u(s,{expected:g.joinValues(n),received:s.parsedType,code:d$1.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$1.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.promise&&t.common.async===false)return u(t,{code:d$1.invalid_type,expected:f.promise,received:t.parsedType}),v;let s=t.parsedType===f.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.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.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.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.nan){let s=this._getOrReturnCtx(e);return u(s,{code:d$1.invalid_type,expected:f.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,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$1,quotelessJson:ze,ZodError:T});
8
+ 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$2="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$2,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$2,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$2);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$2)}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$2,o);return}throw l(`${n} must be a positive number`,y$2,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$2,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$2);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$2)}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())};
7
9
 
8
- 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 e=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(e),mqtt:Jt.object({sessionRootTopic:Jt.string(),userNotificationEventsTopic:Jt.string(),allNotificationEventsTopic:Jt.string().optional(),notificationsRootTopic:Jt.string(),lastWillTopic:Jt.string(),url:Jt.string(),token:Jt.string(),userNotificationTopic:Jt.string()}).optional()}).strict();var i=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 n=Jt.enum(["users","groups"]),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()}),d=Jt.object({action:i,notificationId:Jt.string().uuid(),originatingSessionId:Jt.string().uuid(),correlationId:Jt.string().optional(),target:Jt.string(),targetType:n,payload:Jt.unknown(),txInstanceId:Jt.string().uuid()}),r=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:r,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()});
10
+ var d$1=Object.defineProperty;var e$1=(c,a)=>{for(var b in a)d$1(c,b,{get:a[b],enumerable:true});};
11
+
12
+ 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$1(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$1(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$1(this._def),innerType:this,defaultValue:t,typeName:m.ZodDefault})}brand(){return new le({typeName:m.ZodBranded,type:this,...y$1(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ee({...y$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(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$1(e)});w.strictCreate=(r,e)=>new w({shape:()=>r,unknownKeys:"strict",catchall:A.create(),typeName:m.ZodObject,...y$1(e)});w.lazycreate=(r,e)=>new w({shape:r,unknownKeys:"strip",catchall:A.create(),typeName:m.ZodObject,...y$1(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$1(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$1(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$1(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$1(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$1(s)}):new r({keyType:V.create(),valueType:e,typeName:m.ZodRecord,...y$1(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$1(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$1(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$1(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$1(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$1(e)});function Re(r,e){return new Q({values:r,typeName:m.ZodEnum,...y$1(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$1(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$1(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$1(t)});S.createWithPreprocess=(r,e,t)=>new S({schema:e,effect:{type:"preprocess",transform:r},typeName:m.ZodEffects,...y$1(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$1(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$1(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$1(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$1(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$1(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$1(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});
13
+
14
+ 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()});
15
+
16
+ var y=e=>{let n=e.replaceAll("-","+").replaceAll("_","/");return n.padEnd(n.length+(4-n.length%4)%4,"=")};
9
17
 
10
18
  class CloudNotificationAPIError extends Error {
11
19
  code;
@@ -20,6 +28,11 @@ class AuthorizationError extends CloudNotificationAPIError {
20
28
  super(message, code, undefined);
21
29
  }
22
30
  }
31
+ class OAuthAuthenticationError extends CloudNotificationAPIError {
32
+ constructor(message, code = 'ERR_OAUTH', cause) {
33
+ super(message, code, cause);
34
+ }
35
+ }
23
36
  class SessionNotConnectedError extends CloudNotificationAPIError {
24
37
  constructor(message = 'Session not connected', code = 'ERR_SESSION_NOT_CONNECTED') {
25
38
  super(message, code, undefined);
@@ -54,6 +67,16 @@ class InvalidMessageFormatError extends CloudNotificationAPIError {
54
67
  // Error codes as defined in https://docs.emqx.com/en/cloud/latest/connect_to_deployments/mqtt_client_error_codes.html
55
68
  const BadUserNamePasswordError = 134;
56
69
 
70
+ const rethrowAsOAuthAuthenticationError = (error) => {
71
+ if (error instanceof w$1) {
72
+ throw new OAuthAuthenticationError(error.message, 'ERR_OAUTH', error);
73
+ }
74
+ if (error instanceof TypeError) {
75
+ throw new OAuthAuthenticationError('OAuth access token could not be obtained', 'ERR_OAUTH', error);
76
+ }
77
+ throw error;
78
+ };
79
+
57
80
  class EventController {
58
81
  #eventListeners = new Map();
59
82
  addEventListener(type, callback) {
@@ -83,6 +106,108 @@ class EventController {
83
106
  }
84
107
  }
85
108
 
109
+ class TimeDifferenceTracker {
110
+ #timeServerUrl;
111
+ #intervalMs;
112
+ #samples;
113
+ #authenticatedFetch;
114
+ #currentOffset = 0;
115
+ #timerId;
116
+ #stopped = false;
117
+ #logger;
118
+ constructor(timeServerUrl, authenticatedFetch, logger, intervalMs = 60 * 60 * 1000, samples = 10) {
119
+ this.#timeServerUrl = timeServerUrl;
120
+ this.#logger = logger;
121
+ this.#authenticatedFetch = authenticatedFetch;
122
+ this.#intervalMs = intervalMs;
123
+ this.#samples = samples;
124
+ }
125
+ async start() {
126
+ await this.updateTimeOffset();
127
+ }
128
+ stop() {
129
+ this.#stopped = true;
130
+ if (this.#timerId) {
131
+ clearInterval(this.#timerId);
132
+ this.#timerId = undefined;
133
+ }
134
+ }
135
+ async updateTimeOffset() {
136
+ if (this.#timerId) {
137
+ clearInterval(this.#timerId);
138
+ this.#timerId = undefined;
139
+ }
140
+ try {
141
+ this.#currentOffset = await this.#getAverageOffset();
142
+ this.#logger('debug', `Time offset: ${this.#currentOffset} ms`);
143
+ if (this.#stopped) {
144
+ return this.#currentOffset;
145
+ }
146
+ this.#timerId = setInterval(async () => {
147
+ try {
148
+ this.#currentOffset = await this.#getAverageOffset();
149
+ this.#logger('debug', `Time offset: ${this.#currentOffset} ms`);
150
+ }
151
+ catch {
152
+ this.#logger('error', `Failed to update time offset`);
153
+ }
154
+ }, this.#intervalMs);
155
+ return this.#currentOffset;
156
+ }
157
+ catch (error) {
158
+ if (error instanceof OAuthAuthenticationError) {
159
+ throw error;
160
+ }
161
+ this.#logger('error', `Failed to update time offset`);
162
+ }
163
+ }
164
+ get currentOffset() {
165
+ return this.#currentOffset;
166
+ }
167
+ async #measureOffset() {
168
+ const start = Date.now();
169
+ const response = await this.#authenticatedFetch(`${this.#timeServerUrl}/api/time`, {
170
+ method: 'GET',
171
+ });
172
+ if (response.status === 401) {
173
+ return 'unauthorized';
174
+ }
175
+ const end = Date.now();
176
+ const data = await response.json();
177
+ const rtt = end - start;
178
+ const clientMidpoint = (start + end) / 2;
179
+ return {
180
+ offset: data.serverTime - clientMidpoint,
181
+ rtt,
182
+ };
183
+ }
184
+ async #getAverageOffset() {
185
+ const results = [];
186
+ for (let index = 0; index < this.#samples && !this.#stopped; index++) {
187
+ try {
188
+ const result = await this.#measureOffset();
189
+ if (result === 'unauthorized') {
190
+ break;
191
+ }
192
+ results.push(result);
193
+ }
194
+ catch (error) {
195
+ if (error instanceof OAuthAuthenticationError) {
196
+ throw error;
197
+ }
198
+ // Just ignore any time get failures
199
+ }
200
+ await new Promise((res) => setTimeout(res, 50));
201
+ }
202
+ if (results.length === 0) {
203
+ return this.#currentOffset;
204
+ }
205
+ // Filter out top 20% RTTs as outliers
206
+ const filtered = results.sort((a, b) => a.rtt - b.rtt).slice(0, Math.max(1, Math.floor(results.length * 0.8)));
207
+ return filtered.reduce((sum, r) => sum + r.offset, 0) / filtered.length;
208
+ }
209
+ }
210
+
86
211
  function validateConnectParameters(parameters) {
87
212
  if (!parameters) {
88
213
  throw new Error('Connect parameters must be provided');
@@ -98,6 +223,17 @@ function validateConnectParameters(parameters) {
98
223
  (!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
99
224
  throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
100
225
  }
226
+ if (parameters.authenticationType === 'oauth') {
227
+ if (!parameters.oauthAuthenticationParameters?.clientId?.trim() || !parameters.oauthAuthenticationParameters?.clientSecret?.trim()) {
228
+ throw new OAuthAuthenticationError('oauthAuthenticationParameters must be provided when using oauth authentication');
229
+ }
230
+ try {
231
+ $n(parameters.oauthAuthenticationParameters);
232
+ }
233
+ catch (error) {
234
+ rethrowAsOAuthAuthenticationError(error);
235
+ }
236
+ }
101
237
  }
102
238
  function handleAPIException(logger, error, message, exceptionConstructor) {
103
239
  if (error instanceof Error) {
@@ -118,9 +254,18 @@ async function checkResponse(logger, response, failMessage, failCode) {
118
254
  throw new CloudNotificationAPIError(`${failMessage} (HTTP ${response.status}: ${response.statusText})`, failCode, responseBody);
119
255
  }
120
256
  }
121
- function getRequestHeaders(connectionParameters) {
257
+ async function getRequestHeaders(connectionParameters, tokenClient) {
122
258
  const headers = {};
123
259
  headers['Content-Type'] = 'application/json';
260
+ if (connectionParameters.authenticationType === 'oauth' && tokenClient) {
261
+ try {
262
+ const accessToken = await tokenClient.getAccessToken();
263
+ headers['Authorization'] = `Bearer ${accessToken}`;
264
+ }
265
+ catch (error) {
266
+ rethrowAsOAuthAuthenticationError(error);
267
+ }
268
+ }
124
269
  if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
125
270
  const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
126
271
  if (!tokenResult) {
@@ -192,87 +337,6 @@ class SetWithTTL {
192
337
  }
193
338
  }
194
339
 
195
- class TimeDifferenceTracker {
196
- #timeServerUrl;
197
- #intervalMs;
198
- #samples;
199
- #connectionParams;
200
- #currentOffset = 0;
201
- #timerId;
202
- #logger;
203
- constructor(timeServerUrl, connectionParameters, logger, intervalMs = 60 * 60 * 1000, samples = 10) {
204
- this.#timeServerUrl = timeServerUrl;
205
- this.#logger = logger;
206
- this.#connectionParams = connectionParameters;
207
- this.#intervalMs = intervalMs;
208
- this.#samples = samples;
209
- }
210
- async start() {
211
- await this.updateTimeOffset();
212
- }
213
- stop() {
214
- if (this.#timerId) {
215
- clearInterval(this.#timerId);
216
- this.#timerId = undefined;
217
- }
218
- }
219
- async updateTimeOffset() {
220
- if (this.#timerId) {
221
- clearInterval(this.#timerId);
222
- this.#timerId = undefined;
223
- }
224
- try {
225
- this.#currentOffset = await this.#getAverageOffset();
226
- this.#logger('debug', `Time offset: ${this.#currentOffset} ms`);
227
- this.#timerId = setInterval(async () => {
228
- this.#currentOffset = await this.#getAverageOffset();
229
- this.#logger('debug', `Time offset: ${this.#currentOffset} ms`);
230
- }, this.#intervalMs);
231
- return this.#currentOffset;
232
- }
233
- catch {
234
- this.#logger('error', `Failed to update time offset`);
235
- }
236
- }
237
- get currentOffset() {
238
- return this.#currentOffset;
239
- }
240
- async #measureOffset() {
241
- if (!this.#connectionParams) {
242
- throw new Error('Connection details not set');
243
- }
244
- const start = Date.now();
245
- const response = await fetch(`${this.#timeServerUrl}/api/time`, {
246
- method: 'GET',
247
- headers: getRequestHeaders(this.#connectionParams),
248
- });
249
- const end = Date.now();
250
- const data = await response.json();
251
- const rtt = end - start;
252
- const clientMidpoint = (start + end) / 2;
253
- return {
254
- offset: data.serverTime - clientMidpoint,
255
- rtt,
256
- };
257
- }
258
- async #getAverageOffset() {
259
- const results = [];
260
- for (let index = 0; index < this.#samples; index++) {
261
- try {
262
- const result = await this.#measureOffset();
263
- results.push(result);
264
- }
265
- catch {
266
- // Just ignore any time get failures
267
- }
268
- await new Promise((res) => setTimeout(res, 50));
269
- }
270
- // Filter out top 20% RTTs as outliers
271
- const filtered = results.sort((a, b) => a.rtt - b.rtt).slice(0, Math.floor(results.length * 0.8));
272
- return filtered.reduce((sum, r) => sum + r.offset, 0) / filtered.length;
273
- }
274
- }
275
-
276
340
  /**
277
341
  * Represents a single connection to the Cloud Notification service
278
342
  *
@@ -288,11 +352,14 @@ class CloudNotificationAPI {
288
352
  #deDuplicator;
289
353
  #reconnectRetries = 0;
290
354
  #connectionParams;
355
+ #tokenClient;
291
356
  #attemptingToReconnect = false;
357
+ #disconnecting = false;
292
358
  #events = new EventController();
293
359
  #defaultSubscriptionOptions = { qos: 2, nl: true };
294
360
  #logger = (level, message) => console[level](message);
295
361
  #getCurrentTimeOffset = () => this.#timeDifferenceTracker?.currentOffset || 0;
362
+ #sessionTimer;
296
363
  /**
297
364
  * Constructs a new instance of the CloudNotificationAPI
298
365
  *
@@ -328,22 +395,49 @@ class CloudNotificationAPI {
328
395
  * @returns A promise that resolves when the connection is established.
329
396
  * @throws {@link CloudNotificationAPIError} If an error occurs during connection.
330
397
  * @throws {@link AuthorizationError} If the connection is unauthorized.
398
+ * @throws {@link OAuthAuthenticationError} If OAuth parameters are invalid, the client credentials are rejected, or an access token cannot be obtained.
331
399
  */
332
400
  async connect(parameters) {
333
401
  validateConnectParameters(parameters);
402
+ const oauthParameters = parameters.oauthAuthenticationParameters;
403
+ if (parameters.authenticationType === 'oauth' && oauthParameters) {
404
+ try {
405
+ this.#tokenClient = Je$1.fromServiceUrl(this.#cloudNotificationSettings.url, oauthParameters.clientId, oauthParameters.clientSecret);
406
+ }
407
+ catch (error) {
408
+ rethrowAsOAuthAuthenticationError(error);
409
+ }
410
+ }
411
+ else {
412
+ this.#tokenClient = undefined;
413
+ }
334
414
  this.#connectionParams = parameters;
335
- if (this.#timeDifferenceTracker) {
336
- this.#timeDifferenceTracker.stop();
337
- this.#timeDifferenceTracker = undefined;
415
+ if (parameters.authenticationType === 'oauth' && this.#tokenClient) {
416
+ try {
417
+ await this.#tokenClient.getAccessToken();
418
+ }
419
+ catch (error) {
420
+ rethrowAsOAuthAuthenticationError(error);
421
+ }
422
+ }
423
+ this.#logger('info', 'Creating Notification service session');
424
+ this.#stopTimeSync();
425
+ this.#timeDifferenceTracker = new TimeDifferenceTracker(this.#cloudNotificationSettings.url, this.#authenticatedFetch, this.#logger);
426
+ try {
427
+ return await this.#createSession(this.#timeDifferenceTracker, parameters);
428
+ }
429
+ catch (error) {
430
+ this.#timeDifferenceTracker?.stop();
431
+ throw error;
338
432
  }
339
- this.#timeDifferenceTracker = new TimeDifferenceTracker(this.#cloudNotificationSettings.url, parameters, this.#logger);
433
+ }
434
+ async #createSession(timeDifferenceTracker, parameters) {
340
435
  if (this.#syncTime !== false) {
341
- await this.#timeDifferenceTracker.start();
436
+ await timeDifferenceTracker.start();
342
437
  }
343
- const { platformId, sourceId } = this.#connectionParams;
344
- const createSessionResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/sessions`, {
438
+ const { platformId, sourceId } = parameters;
439
+ const createSessionResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/sessions`, {
345
440
  method: 'POST',
346
- headers: getRequestHeaders(this.#connectionParams),
347
441
  body: JSON.stringify({
348
442
  platformId,
349
443
  sourceId,
@@ -356,9 +450,15 @@ class CloudNotificationAPI {
356
450
  throw new CloudNotificationAPIError(`Failed to connect to the Cloud Notification service: ${this.#cloudNotificationSettings.url}`, 'ERR_CONNECT', new Error(createSessionResponse.statusText));
357
451
  }
358
452
  this.#sessionDetails = (await createSessionResponse.json());
453
+ const { mqtt: _, ...sessionDetailsWithoutMQTT } = this.#sessionDetails;
454
+ this.#logger('info', `Notification service session created: ${JSON.stringify(sessionDetailsWithoutMQTT, null, 2)}`);
359
455
  // Now have the details from the server about where to connect to and a token to connect with
360
456
  // we can go ahead and connect to the MQTT server
361
457
  await this.#connectToMQTT();
458
+ // If local session expiry handling is enabled, start the session timer
459
+ if (this.#sessionDetails.mqtt?.localSessionExpiryHandling) {
460
+ this.#startSessionTimer();
461
+ }
362
462
  return { sessionId: this.#sessionDetails.sessionId, platformId, sourceId, userId: this.#sessionDetails.userId, groups: this.#sessionDetails.groups };
363
463
  }
364
464
  /**
@@ -373,7 +473,7 @@ class CloudNotificationAPI {
373
473
  /**
374
474
  * Posts a notification event to the Cloud Notification service.
375
475
  *
376
- * @param notificationId - The ID of the notification.
476
+ * @param notificationId - The ID of the notification or an array of notification IDs.
377
477
  * @param event - The event details, including category, type, and optional payload.
378
478
  * @returns A promise that resolves when the event is posted.
379
479
  * @throws {@link SessionNotConnectedError} If the session is not connected.
@@ -391,9 +491,10 @@ class CloudNotificationAPI {
391
491
  event,
392
492
  targets: options?.targets,
393
493
  };
394
- const publishResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/publications/${notificationId}/events`, {
494
+ const notificationIds = Array.isArray(notificationId) ? notificationId : [notificationId];
495
+ const notificationIdsString = notificationIds.join('&id=');
496
+ const publishResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/publications/events?id=${notificationIdsString}`, {
395
497
  method: 'POST',
396
- headers: getRequestHeaders(this.#connectionParams),
397
498
  body: JSON.stringify(publishPayload),
398
499
  });
399
500
  await checkResponse(this.#logger, publishResponse, 'Error posting notification event', 'ERR_POST_NOTIFICATION_EVENT');
@@ -410,13 +511,28 @@ class CloudNotificationAPI {
410
511
  * @returns A promise that resolves when the notification is removed.
411
512
  */
412
513
  async removeFromNotificationCenter(notificationId, targets) {
413
- return this.postNotificationEvent(notificationId, {
414
- category: 'notification-center-event',
415
- type: 'notification-closed',
416
- payload: {},
417
- }, {
418
- targets,
419
- });
514
+ return this.postNotificationEvent(notificationId, { category: 'notification-center-event', type: 'notification-closed', payload: {} }, { targets });
515
+ }
516
+ /**
517
+ * Post a notification-reminder-created event to the Cloud Notification service.
518
+ *
519
+ * @param notificationId - The ID of the notification or an array of notification IDs to mark as a reminder.
520
+ * @param payload - The payload of the reminder.
521
+ * @returns A promise that resolves when the notification-reminder-created event is posted.
522
+ * @throws {@link SessionNotConnectedError} If the session is not connected.
523
+ */
524
+ async setReminder(notificationId, payload, targets) {
525
+ return this.postNotificationEvent(notificationId, { category: 'notification-center-event', type: 'notification-reminder-created', payload }, { targets });
526
+ }
527
+ /**
528
+ * Post a notification-reminder-removed event to the Cloud Notification service.
529
+ *
530
+ * @param notificationId - The ID of the notification or an array of notification IDs to cancel the reminder for.
531
+ * @returns A promise that resolves when the notification-reminder-removed event is posted.
532
+ * @throws {@link SessionNotConnectedError} If the session is not connected.
533
+ */
534
+ async cancelReminder(notificationId, targets) {
535
+ return this.postNotificationEvent(notificationId, { category: 'notification-center-event', type: 'notification-reminder-removed' }, { targets });
420
536
  }
421
537
  /**
422
538
  * Raises a notification to the Cloud Notification service.
@@ -428,33 +544,22 @@ class CloudNotificationAPI {
428
544
  * @throws {@link PublishError} If an error occurs during publishing.
429
545
  */
430
546
  async raiseNotification(options, payload) {
431
- if (!this.#sessionDetails || !this.#connectionParams) {
432
- this.#logger('error', 'Invalid Session');
433
- throw new SessionNotConnectedError();
434
- }
435
- try {
436
- const publishPayload = {
437
- sessionId: this.#sessionDetails.sessionId,
438
- timeOffset: this.#getCurrentTimeOffset(),
439
- notification: {
440
- ttlSeconds: options.ttlSeconds,
441
- correlationId: options.correlationId,
442
- targets: options.targets,
443
- payload,
444
- },
445
- };
446
- const publishResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/publications`, {
447
- method: 'POST',
448
- headers: getRequestHeaders(this.#connectionParams),
449
- body: JSON.stringify(publishPayload),
450
- });
451
- await checkResponse(this.#logger, publishResponse, 'Error publishing notification', 'ERR_PUBLISH_NOTIFICATION');
452
- const publishResponseBody = (await publishResponse.json());
453
- return publishResponseBody;
454
- }
455
- catch (error) {
456
- handleAPIException(this.#logger, error, 'Error publishing notification', PublishError);
457
- }
547
+ return this.#publishNewNotification('/api/publications', { ...options, payload });
548
+ }
549
+ /**
550
+ * Raises a notification to the connected user via the Cloud Notification service.
551
+ *
552
+ * Unlike {@link raiseNotification}, no notification raise permissions are required and the notification
553
+ * is always targeted at the connected user only.
554
+ *
555
+ * @param options - The options for the notification.
556
+ * @param payload - The payload of the notification which should generally conform to the notification center schema
557
+ * @returns A promise that resolves with the notification raise result.
558
+ * @throws {@link SessionNotConnectedError} If the session is not connected.
559
+ * @throws {@link PublishError} If an error occurs during publishing.
560
+ */
561
+ async raiseNotificationToMe(options, payload) {
562
+ return this.#publishNewNotification('/api/publications/me', { ...options, payload });
458
563
  }
459
564
  /**
460
565
  * Raises a notification update to the Cloud Notification service.
@@ -477,9 +582,8 @@ class CloudNotificationAPI {
477
582
  ttlSeconds: options.ttlSeconds,
478
583
  payload,
479
584
  };
480
- const updateResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/publications/${notificationId}`, {
585
+ const updateResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/publications/${notificationId}`, {
481
586
  method: 'PATCH',
482
- headers: getRequestHeaders(this.#connectionParams),
483
587
  body: JSON.stringify(updatePayload),
484
588
  });
485
589
  await checkResponse(this.#logger, updateResponse, 'Error updating notification', 'ERR_UPDATING_NOTIFICATION');
@@ -503,9 +607,10 @@ class CloudNotificationAPI {
503
607
  throw new SessionNotConnectedError();
504
608
  }
505
609
  try {
506
- const deleteResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/publications/${notificationId}?sessionId=${this.#sessionDetails.sessionId}`, {
610
+ const notificationIds = Array.isArray(notificationId) ? notificationId : [notificationId];
611
+ const notificationIdsString = notificationIds.join('&id=');
612
+ const deleteResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/publications?id=${notificationIdsString}&sessionId=${this.#sessionDetails.sessionId}`, {
507
613
  method: 'DELETE',
508
- headers: getRequestHeaders(this.#connectionParams),
509
614
  });
510
615
  await checkResponse(this.#logger, deleteResponse, 'Error deleting notification', 'ERR_DELETE_NOTIFICATION');
511
616
  }
@@ -541,9 +646,8 @@ class CloudNotificationAPI {
541
646
  if ([...parameters].length > 0) {
542
647
  replayUrl += `?${parameters.toString()}`;
543
648
  }
544
- const replayResponse = await fetch(replayUrl, {
649
+ const replayResponse = await this.#authenticatedFetch(replayUrl, {
545
650
  method: 'POST',
546
- headers: getRequestHeaders(this.#connectionParams),
547
651
  body: JSON.stringify({
548
652
  sessionId: this.#sessionDetails.sessionId,
549
653
  }),
@@ -583,11 +687,35 @@ class CloudNotificationAPI {
583
687
  once(type, callback) {
584
688
  this.#events.once(type, callback);
585
689
  }
690
+ async #publishNewNotification(path, notification) {
691
+ if (!this.#sessionDetails || !this.#connectionParams) {
692
+ this.#logger('error', 'Invalid Session');
693
+ throw new SessionNotConnectedError();
694
+ }
695
+ try {
696
+ const publishResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}${path}`, {
697
+ method: 'POST',
698
+ body: JSON.stringify({
699
+ sessionId: this.#sessionDetails.sessionId,
700
+ timeOffset: this.#getCurrentTimeOffset(),
701
+ notification,
702
+ }),
703
+ });
704
+ await checkResponse(this.#logger, publishResponse, 'Error publishing notification', 'ERR_PUBLISH_NOTIFICATION');
705
+ const publishResponseBody = (await publishResponse.json());
706
+ return publishResponseBody;
707
+ }
708
+ catch (error) {
709
+ handleAPIException(this.#logger, error, 'Error publishing notification', PublishError);
710
+ }
711
+ }
586
712
  async #connectToMQTT() {
587
713
  if (!this.#sessionDetails || !this.#sessionDetails.mqtt) {
588
714
  this.#logger('error', 'Invalid Session');
589
715
  throw new SessionNotConnectedError();
590
716
  }
717
+ const { token: _, ...mqttDetailsWithoutToken } = this.#sessionDetails.mqtt;
718
+ this.#logger('info', `Connecting to MQTT server: ${JSON.stringify(mqttDetailsWithoutToken, null, 2)}`);
591
719
  const clientOptions = {
592
720
  keepalive: this.#keepAliveIntervalSeconds,
593
721
  clientId: this.#sessionDetails.sessionId,
@@ -603,14 +731,16 @@ class CloudNotificationAPI {
603
731
  username: this.#sessionDetails.mqtt.token,
604
732
  };
605
733
  this.#mqttClient = await mqtt.connectAsync(this.#sessionDetails.mqtt.url, clientOptions);
606
- this.#logger('debug', `Cloud Notifications successfully connected to notification backbone`);
607
734
  this.#mqttClient.on('error', async (error) => this.#mqttErrorHandler(error));
608
- this.#mqttClient.on('reconnect', () => this.#mqttReconnectionHandler());
735
+ this.#mqttClient.on('reconnect', async () => {
736
+ await this.#mqttReconnectionHandler();
737
+ });
609
738
  // Does not fire on initial connection, only successful reconnection attempts
610
739
  this.#mqttClient.on('connect', () => this.#mqttConnectionHandler());
611
740
  this.#mqttClient.on('message', (topic, message) => this.#mqttMessageHandler(topic, message));
612
741
  // Subscribe any session specific topics
613
742
  this.#mqttClient.subscribe(`${this.#sessionDetails.mqtt.sessionRootTopic}/#`);
743
+ this.#logger('info', 'Successfully connected to MQTT server');
614
744
  // Subscribe to the user notification delivery topics for groups and users
615
745
  await this.#subscribeToNotificationTopics();
616
746
  }
@@ -624,11 +754,11 @@ class CloudNotificationAPI {
624
754
  this.#attemptingToReconnect = true;
625
755
  this.#reconnectRetries += 1;
626
756
  this.#logger('debug', `Cloud Notifications attempting reconnection - ${this.#reconnectRetries}...`);
757
+ this.#events.emitEvent('reconnecting', this.#reconnectRetries);
627
758
  if (this.#reconnectRetries === this.#reconnectRetryLimit) {
628
759
  this.#logger('warn', `Cloud Notifications reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
629
- this.#disconnect(true);
760
+ await this.#disconnectAndLogFailure(true);
630
761
  }
631
- this.#events.emitEvent('reconnecting', this.#reconnectRetries);
632
762
  }
633
763
  async #mqttMessageHandler(topic, message) {
634
764
  if (!this.#sessionDetails) {
@@ -644,7 +774,14 @@ class CloudNotificationAPI {
644
774
  this.#logger('debug', `Session expired`);
645
775
  this.#events.emitEvent('session-expired');
646
776
  // TODO: Request new JWT if using JWT authentication
647
- await this.#extendSession();
777
+ const sessionId = this.#sessionDetails?.sessionId;
778
+ try {
779
+ await this.#extendSession();
780
+ }
781
+ catch (extendError) {
782
+ await this.#handleSessionExtendFailure(extendError, sessionId);
783
+ return;
784
+ }
648
785
  this.#logger('debug', `Session extended`);
649
786
  this.#events.emitEvent('session-extended');
650
787
  return;
@@ -706,6 +843,20 @@ class CloudNotificationAPI {
706
843
  }
707
844
  await Promise.all(subscribePromises);
708
845
  }
846
+ #authenticatedFetch = async (url, { method, body }) => {
847
+ const connectionParameters = this.#connectionParams;
848
+ if (!connectionParameters) {
849
+ throw new Error('Connect parameters must be provided');
850
+ }
851
+ const attempt = async () => {
852
+ const headers = await getRequestHeaders(connectionParameters, this.#tokenClient);
853
+ return fetch(url, { method, headers, body });
854
+ };
855
+ if (connectionParameters.authenticationType === 'oauth' && this.#tokenClient) {
856
+ return Fn(this.#tokenClient, attempt);
857
+ }
858
+ return attempt();
859
+ };
709
860
  async #extendSession() {
710
861
  if (!this.#sessionDetails) {
711
862
  return;
@@ -719,9 +870,8 @@ class CloudNotificationAPI {
719
870
  this.#mqttClient = undefined;
720
871
  this.#reconnectRetries = 0;
721
872
  this.#attemptingToReconnect = false;
722
- const extendResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/sessions`, {
873
+ const extendResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/sessions`, {
723
874
  method: 'PUT',
724
- headers: getRequestHeaders(this.#connectionParams),
725
875
  body: JSON.stringify({
726
876
  sessionId: this.#sessionDetails.sessionId,
727
877
  }),
@@ -732,23 +882,33 @@ class CloudNotificationAPI {
732
882
  this.#sessionDetails = (await extendResponse.json());
733
883
  this.#attemptingToReconnect = true;
734
884
  await this.#connectToMQTT();
885
+ // If local session expiry handling is enabled, start the session timer
886
+ if (this.#sessionDetails.mqtt?.localSessionExpiryHandling) {
887
+ this.#startSessionTimer();
888
+ }
735
889
  }
736
890
  catch (error) {
737
891
  throw new CloudNotificationAPIError('Error during session refresh', 'ERR_SESSION_EXTEND', error);
738
892
  }
739
893
  }
740
894
  async #disconnect(fireDisconnectedEvent) {
895
+ this.#stopTimeSync();
741
896
  if (!this.#sessionDetails) {
742
897
  return;
743
898
  }
899
+ this.#disconnecting = true;
744
900
  try {
745
901
  if (!this.#connectionParams) {
746
902
  throw new Error('Connect parameters must be provided');
747
903
  }
904
+ // Cancel session timer if it's running
905
+ if (this.#sessionTimer) {
906
+ clearTimeout(this.#sessionTimer);
907
+ this.#sessionTimer = undefined;
908
+ }
748
909
  // Clean up our session on the server
749
- const disconnectResponse = await fetch(`${this.#cloudNotificationSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
910
+ const disconnectResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
750
911
  method: 'DELETE',
751
- headers: getRequestHeaders(this.#connectionParams),
752
912
  });
753
913
  if (disconnectResponse.status !== 204) {
754
914
  throw new CloudNotificationAPIError(`Error during session tear down - unexpected status ${disconnectResponse.status}`, 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
@@ -769,11 +929,130 @@ class CloudNotificationAPI {
769
929
  this.#mqttClient = undefined;
770
930
  this.#reconnectRetries = 0;
771
931
  this.#attemptingToReconnect = false;
932
+ this.#disconnecting = false;
772
933
  if (fireDisconnectedEvent) {
773
934
  this.#events.emitEvent('disconnected');
774
935
  }
775
936
  }
776
937
  }
938
+ async #disconnectAndLogFailure(fireDisconnectedEvent = false) {
939
+ try {
940
+ await this.#disconnect(fireDisconnectedEvent);
941
+ }
942
+ catch (error) {
943
+ this.#logger('error', `Session teardown failed: ${error instanceof Error ? error.message : String(error)}`);
944
+ }
945
+ }
946
+ #stopTimeSync() {
947
+ this.#timeDifferenceTracker?.stop();
948
+ this.#timeDifferenceTracker = undefined;
949
+ }
950
+ /**
951
+ * @param sessionId - The session that was being extended. The teardown is skipped when that session is already being disconnected or has been replaced.
952
+ */
953
+ async #handleSessionExtendFailure(error, sessionId) {
954
+ if (this.#disconnecting || !sessionId || this.#sessionDetails?.sessionId !== sessionId) {
955
+ this.#logger('debug', 'Ignoring a failed extend for a session that was disconnected or replaced');
956
+ return;
957
+ }
958
+ this.#logger('error', `Session extend failed: ${error instanceof Error ? error.message : String(error)}`);
959
+ this.#events.emitEvent('error', error instanceof Error ? error : new Error(String(error)));
960
+ await this.#disconnectAndLogFailure(true);
961
+ }
962
+ /**
963
+ * Extracts the expiration timestamp from a JWT token.
964
+ *
965
+ * @param token - The JWT token string
966
+ * @returns The expiration timestamp in seconds, or null if extraction fails
967
+ */
968
+ #extractExpirationFromJwt(token) {
969
+ if (!token) {
970
+ return null;
971
+ }
972
+ try {
973
+ // JWT tokens have three parts separated by dots: header.payload.signature
974
+ // The exp claim is in the payload
975
+ const parts = token.split('.');
976
+ if (parts.length < 2) {
977
+ this.#logger('warn', 'Invalid JWT token format: expected at least 2 parts');
978
+ return null;
979
+ }
980
+ const payload = parts[1];
981
+ const decodedBytes = buffer.Buffer.from(y(payload), 'base64');
982
+ const payloadJson = decodedBytes.toString('utf8');
983
+ // Parse JSON to get the exp claim
984
+ const claims = JSON.parse(payloadJson);
985
+ const exp = claims.exp;
986
+ if (exp === undefined || exp === null) {
987
+ this.#logger('warn', "JWT token does not contain 'exp' claim");
988
+ return null;
989
+ }
990
+ if (typeof exp !== 'number') {
991
+ this.#logger('warn', `JWT token 'exp' claim is not a number: ${exp}`);
992
+ return null;
993
+ }
994
+ return exp;
995
+ }
996
+ catch (error) {
997
+ this.#logger('error', `Failed to extract expiration from JWT token: ${error instanceof Error ? error.message : error}`);
998
+ return null;
999
+ }
1000
+ }
1001
+ /**
1002
+ * Start a session timer that will expire at the time specified in the JWT token's exp claim.
1003
+ * On expiry, it will fire session expired event, extend the session, fire session extended event, and restart the timer.
1004
+ */
1005
+ #startSessionTimer() {
1006
+ if (!this.#sessionDetails?.mqtt?.token) {
1007
+ this.#logger('warn', 'Cannot start session timer: session details or token not available');
1008
+ return;
1009
+ }
1010
+ // Extract expiration time from JWT token
1011
+ const expTimestamp = this.#extractExpirationFromJwt(this.#sessionDetails.mqtt.token);
1012
+ if (expTimestamp === null) {
1013
+ this.#logger('warn', 'Cannot start session timer: could not extract expiration from JWT token');
1014
+ return;
1015
+ }
1016
+ const currentTimeSeconds = Math.floor(Date.now() / 1000);
1017
+ const delaySeconds = expTimestamp - currentTimeSeconds;
1018
+ if (delaySeconds <= 0) {
1019
+ this.#logger('warn', 'JWT token has already expired or expires immediately');
1020
+ this.#events.emitEvent('session-expired');
1021
+ const sessionId = this.#sessionDetails.sessionId;
1022
+ this.#extendSession()
1023
+ .then(() => {
1024
+ this.#logger('debug', 'Session extended');
1025
+ this.#events.emitEvent('session-extended');
1026
+ })
1027
+ .catch((error) => this.#handleSessionExtendFailure(error, sessionId));
1028
+ return;
1029
+ }
1030
+ // Clear any existing timer
1031
+ if (this.#sessionTimer) {
1032
+ clearTimeout(this.#sessionTimer);
1033
+ }
1034
+ const expirationTimeString = new Date(expTimestamp * 1000).toISOString();
1035
+ this.#logger('debug', `Starting session timer to expire in ${delaySeconds} seconds (at ${expirationTimeString})`);
1036
+ this.#sessionTimer = setTimeout(async () => {
1037
+ const sessionId = this.#sessionDetails?.sessionId;
1038
+ try {
1039
+ this.#logger('debug', 'Session timer expired');
1040
+ this.#events.emitEvent('session-expired');
1041
+ await this.#extendSession();
1042
+ this.#logger('debug', 'Session extended');
1043
+ this.#events.emitEvent('session-extended');
1044
+ }
1045
+ catch (error) {
1046
+ await this.#handleSessionExtendFailure(error, sessionId);
1047
+ }
1048
+ }, delaySeconds * 1000);
1049
+ }
1050
+ #isGroupEventTopic(topic) {
1051
+ if (!this.#sessionDetails) {
1052
+ return false;
1053
+ }
1054
+ return this.#sessionDetails.groups.some((group) => group.eventTopic?.startsWith(topic));
1055
+ }
777
1056
  #handleMessage(topic, message, sessionDetails) {
778
1057
  if (message.length === 0 || !sessionDetails || !sessionDetails.mqtt) {
779
1058
  // Ignore clean up messages
@@ -781,6 +1060,8 @@ class CloudNotificationAPI {
781
1060
  }
782
1061
  try {
783
1062
  const messagePayload = JSON.parse(message.toString());
1063
+ // NOTE: uncomment this to debug message payloads
1064
+ // this.#logger('info', `Received message on topic ${topic} with payload ${JSON.stringify(messagePayload)}`);
784
1065
  if (topic.startsWith(sessionDetails.mqtt.notificationsRootTopic)) {
785
1066
  this.#handleNotificationMessage(messagePayload);
786
1067
  }
@@ -790,6 +1071,9 @@ class CloudNotificationAPI {
790
1071
  else if (topic === sessionDetails.mqtt.allNotificationEventsTopic) {
791
1072
  this.#handleAllNotificationEventMessage(messagePayload);
792
1073
  }
1074
+ else if (this.#isGroupEventTopic(topic)) {
1075
+ this.#handleGroupNotificationEventMessage(messagePayload);
1076
+ }
793
1077
  else {
794
1078
  this.#logger('warn', `Received message on unknown topic ${topic}`);
795
1079
  this.#events.emitEvent('error', new CloudNotificationAPIError(`Received message on unknown topic ${topic}`, 'ERR_UNKNOWN_TOPIC'));
@@ -801,7 +1085,7 @@ class CloudNotificationAPI {
801
1085
  }
802
1086
  }
803
1087
  #handleNotificationMessage(messagePayload) {
804
- const parseResult = d.safeParse(messagePayload);
1088
+ const parseResult = N.safeParse(messagePayload);
805
1089
  if (!parseResult.success) {
806
1090
  this.#logger('warn', `Received invalid notification message payload format ${parseResult.error?.toString()}`);
807
1091
  throw new InvalidMessageFormatError(parseResult);
@@ -821,37 +1105,54 @@ class CloudNotificationAPI {
821
1105
  if (targetType === 'groups') {
822
1106
  targetName = this.#lookupGroupNameByUuid(target);
823
1107
  }
1108
+ const makePayload = (action) => ({ action, notificationId, correlationId, target, targetName, targetType, payload });
824
1109
  switch (action) {
825
1110
  case 'new': {
826
- this.#events.emitEvent('new-notification', { action: 'new', notificationId, correlationId, target, targetName, targetType, payload });
1111
+ this.#events.emitEvent('new-notification', makePayload('new'));
827
1112
  break;
828
1113
  }
829
1114
  case 'update': {
830
- this.#events.emitEvent('update-notification', { action: 'update', notificationId, correlationId, target, targetName, targetType, payload });
1115
+ this.#events.emitEvent('update-notification', makePayload('update'));
831
1116
  break;
832
1117
  }
833
1118
  case 'delete': {
834
- this.#events.emitEvent('delete-notification', { action: 'delete', notificationId, correlationId, target, targetName, targetType, payload });
1119
+ this.#events.emitEvent('delete-notification', makePayload('delete'));
835
1120
  break;
836
1121
  }
837
1122
  // No default - Schema validation will prevent this
838
1123
  }
839
1124
  }
840
1125
  #handleUserNotificationEventMessage(messagePayload) {
841
- const parseResult = l.safeParse(messagePayload);
842
- if (!parseResult.success) {
843
- this.#logger('warn', `Received invalid notification event message payload format ${parseResult.error?.toString()}`);
844
- throw new InvalidMessageFormatError(parseResult);
1126
+ const event = this.#parseNotificationEventMessage(messagePayload);
1127
+ if (event.originatingSessionId === this.#sessionDetails?.sessionId) {
1128
+ this.#logger('debug', `Received notification event from our own session, ignoring. (session id: ${event.originatingSessionId})`);
1129
+ return;
845
1130
  }
846
- this.#events.emitEvent('notification-event', parseResult.data);
1131
+ this.#events.emitEvent('notification-event', event);
1132
+ }
1133
+ #handleGroupNotificationEventMessage(messagePayload) {
1134
+ const event = this.#parseNotificationEventMessage(messagePayload);
1135
+ if (event.originatingSessionId === this.#sessionDetails?.sessionId) {
1136
+ this.#logger('debug', `Received notification event from our own session, ignoring. (session id: ${event.originatingSessionId})`);
1137
+ return;
1138
+ }
1139
+ this.#events.emitEvent('notification-event', event);
847
1140
  }
848
1141
  #handleAllNotificationEventMessage(messagePayload) {
849
- const parseResult = l.safeParse(messagePayload);
1142
+ const event = this.#parseNotificationEventMessage(messagePayload);
1143
+ if (event.originatingSessionId === this.#sessionDetails?.sessionId) {
1144
+ this.#logger('debug', `Received notification event from our own session, ignoring. (session id: ${event.originatingSessionId})`);
1145
+ return;
1146
+ }
1147
+ this.#events.emitEvent('global-notification-event', event);
1148
+ }
1149
+ #parseNotificationEventMessage(messagePayload) {
1150
+ const parseResult = I.safeParse(messagePayload);
850
1151
  if (!parseResult.success) {
851
1152
  this.#logger('warn', `Received invalid notification event message payload format ${parseResult.error?.toString()}`);
852
1153
  throw new InvalidMessageFormatError(parseResult);
853
1154
  }
854
- this.#events.emitEvent('global-notification-event', parseResult.data);
1155
+ return parseResult.data;
855
1156
  }
856
1157
  #lookupGroupNameByUuid(uuid) {
857
1158
  if (!this.#sessionDetails) {
@@ -868,5 +1169,7 @@ exports.EventPublishError = EventPublishError;
868
1169
  exports.EventRetrievalError = EventRetrievalError;
869
1170
  exports.InvalidMessageFormatError = InvalidMessageFormatError;
870
1171
  exports.NotificationRetrievalError = NotificationRetrievalError;
1172
+ exports.OAuthAuthenticationError = OAuthAuthenticationError;
871
1173
  exports.PublishError = PublishError;
872
1174
  exports.SessionNotConnectedError = SessionNotConnectedError;
1175
+ exports.targetTypeSchema = p;